filename
stringlengths
5
42
content
stringlengths
15
319k
Pi.lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Topology.UniformSpace.UniformEmbedding /-! # Indexed product of uniform spaces -/ noncomputable section open scoped Uniformity Topology open Filter UniformSpace Function Set universe u variable {ι ι' β : Type*} (α : ι → Type u) [U : ∀ i, UniformSpace (α i)] [UniformSpace β] instance Pi.uniformSpace : UniformSpace (∀ i, α i) := UniformSpace.ofCoreEq (⨅ i, UniformSpace.comap (eval i) (U i)).toCore Pi.topologicalSpace <| Eq.symm toTopologicalSpace_iInf lemma Pi.uniformSpace_eq : Pi.uniformSpace α = ⨅ i, UniformSpace.comap (eval i) (U i) := by ext : 1; rfl theorem Pi.uniformity : 𝓤 (∀ i, α i) = ⨅ i : ι, (Filter.comap fun a => (a.1 i, a.2 i)) (𝓤 (α i)) := iInf_uniformity variable {α} instance [Countable ι] [∀ i, IsCountablyGenerated (𝓤 (α i))] : IsCountablyGenerated (𝓤 (∀ i, α i)) := by rw [Pi.uniformity] infer_instance theorem uniformContinuous_pi {β : Type*} [UniformSpace β] {f : β → ∀ i, α i} : UniformContinuous f ↔ ∀ i, UniformContinuous fun x => f x i := by simp only [UniformContinuous, Pi.uniformity, tendsto_iInf, tendsto_comap_iff, Function.comp_def] variable (α) theorem Pi.uniformContinuous_proj (i : ι) : UniformContinuous fun a : ∀ i : ι, α i => a i := uniformContinuous_pi.1 uniformContinuous_id i theorem Pi.uniformContinuous_precomp' (φ : ι' → ι) : UniformContinuous (fun (f : (∀ i, α i)) (j : ι') ↦ f (φ j)) := uniformContinuous_pi.mpr fun j ↦ uniformContinuous_proj α (φ j) theorem Pi.uniformContinuous_precomp (φ : ι' → ι) : UniformContinuous (· ∘ φ : (ι → β) → (ι' → β)) := Pi.uniformContinuous_precomp' _ φ theorem Pi.uniformContinuous_postcomp' {β : ι → Type*} [∀ i, UniformSpace (β i)] {g : ∀ i, α i → β i} (hg : ∀ i, UniformContinuous (g i)) : UniformContinuous (fun (f : (∀ i, α i)) (i : ι) ↦ g i (f i)) := uniformContinuous_pi.mpr fun i ↦ (hg i).comp <| uniformContinuous_proj α i theorem Pi.uniformContinuous_postcomp {α : Type*} [UniformSpace α] {g : α → β} (hg : UniformContinuous g) : UniformContinuous (g ∘ · : (ι → α) → (ι → β)) := Pi.uniformContinuous_postcomp' _ fun _ ↦ hg lemma Pi.uniformSpace_comap_precomp' (φ : ι' → ι) : UniformSpace.comap (fun g i' ↦ g (φ i')) (Pi.uniformSpace (fun i' ↦ α (φ i'))) = ⨅ i', UniformSpace.comap (eval (φ i')) (U (φ i')) := by simp [Pi.uniformSpace_eq, UniformSpace.comap_iInf, ← UniformSpace.comap_comap, comp_def] lemma Pi.uniformSpace_comap_precomp (φ : ι' → ι) : UniformSpace.comap (· ∘ φ) (Pi.uniformSpace (fun _ ↦ β)) = ⨅ i', UniformSpace.comap (eval (φ i')) ‹UniformSpace β› := uniformSpace_comap_precomp' (fun _ ↦ β) φ lemma Pi.uniformContinuous_restrict (S : Set ι) : UniformContinuous (S.restrict : (∀ i : ι, α i) → (∀ i : S, α i)) := Pi.uniformContinuous_precomp' _ ((↑) : S → ι) lemma Pi.uniformSpace_comap_restrict (S : Set ι) : UniformSpace.comap (S.restrict) (Pi.uniformSpace (fun i : S ↦ α i)) = ⨅ i ∈ S, UniformSpace.comap (eval i) (U i) := by simp +unfoldPartialApp [← iInf_subtype'', ← uniformSpace_comap_precomp' _ ((↑) : S → ι), Set.restrict] lemma cauchy_pi_iff [Nonempty ι] {l : Filter (∀ i, α i)} : Cauchy l ↔ ∀ i, Cauchy (map (eval i) l) := by simp_rw [Pi.uniformSpace_eq, cauchy_iInf_uniformSpace, cauchy_comap_uniformSpace] lemma cauchy_pi_iff' {l : Filter (∀ i, α i)} [l.NeBot] : Cauchy l ↔ ∀ i, Cauchy (map (eval i) l) := by simp_rw [Pi.uniformSpace_eq, cauchy_iInf_uniformSpace', cauchy_comap_uniformSpace] lemma Cauchy.pi [Nonempty ι] {l : ∀ i, Filter (α i)} (hl : ∀ i, Cauchy (l i)) : Cauchy (Filter.pi l) := by have := fun i ↦ (hl i).1 simpa [cauchy_pi_iff] instance Pi.complete [∀ i, CompleteSpace (α i)] : CompleteSpace (∀ i, α i) where complete {f} hf := by have := hf.1 simp_rw [cauchy_pi_iff', cauchy_iff_exists_le_nhds] at hf choose x hx using hf use x rwa [nhds_pi, le_pi] lemma Pi.uniformSpace_comap_restrict_sUnion (𝔖 : Set (Set ι)) : UniformSpace.comap (⋃₀ 𝔖).restrict (Pi.uniformSpace (fun i : (⋃₀ 𝔖) ↦ α i)) = ⨅ S ∈ 𝔖, UniformSpace.comap S.restrict (Pi.uniformSpace (fun i : S ↦ α i)) := by simp_rw [Pi.uniformSpace_comap_restrict α, iInf_sUnion] /- An infimum of complete uniformities is complete, as long as the whole family is bounded by some common T2 topology. -/ protected theorem CompleteSpace.iInf {ι X : Type*} {u : ι → UniformSpace X} (hu : ∀ i, @CompleteSpace X (u i)) (ht : ∃ t, @T2Space X t ∧ ∀ i, (u i).toTopologicalSpace ≤ t) : @CompleteSpace X (⨅ i, u i) := by -- We can assume `X` is nonempty. nontriviality X rcases ht with ⟨t, ht, hut⟩ -- The diagonal map `(X, ⨅ i, u i) → ∀ i, (X, u i)` is a uniform embedding. have : @IsUniformInducing X (ι → X) (⨅ i, u i) (Pi.uniformSpace (U := u)) (const ι) := by simp_rw [isUniformInducing_iff, iInf_uniformity, Pi.uniformity, Filter.comap_iInf, Filter.comap_comap, comp_def, const, Prod.eta, comap_id'] -- Hence, it suffices to show that its range, the diagonal, is closed in `Π i, (X, u i)`. simp_rw [@completeSpace_iff_isComplete_range _ _ (_) (_) _ this, range_const_eq_diagonal, setOf_forall] -- The separation of `t` ensures that this is the case in `Π i, (X, t)`, hence the result -- since the topology associated to each `u i` is finer than `t`. have : Pi.topologicalSpace (t₂ := fun i ↦ (u i).toTopologicalSpace) ≤ Pi.topologicalSpace (t₂ := fun _ ↦ t) := iInf_mono fun i ↦ induced_mono <| hut i refine IsClosed.isComplete <| .mono ?_ this exact isClosed_iInter fun i ↦ isClosed_iInter fun j ↦ isClosed_eq (continuous_apply _) (continuous_apply _)
Arithcc.lean
/- Copyright (c) 2020 Xi Wang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Xi Wang -/ import Mathlib.Data.Nat.Basic import Mathlib.Order.Basic import Mathlib.Tactic.Common /-! # A compiler for arithmetic expressions A formalization of the correctness of a compiler from arithmetic expressions to machine language described by McCarthy and Painter, which is considered the first proof of compiler correctness. ## Main definitions * `Expr` : the syntax of the source language. * `value` : the semantics of the source language. * `Instruction`: the syntax of the target language. * `step` : the semantics of the target language. * `compile` : the compiler. ## Main results * `compiler_correctness`: the compiler correctness theorem. ## Notation * `≃[t]/ac`: partial equality of two machine states excluding registers x ≥ t and the accumulator. * `≃[t]` : partial equality of two machine states excluding registers x ≥ t. ## References * John McCarthy and James Painter. Correctness of a compiler for arithmetic expressions. In Mathematical Aspects of Computer Science, volume 19 of Proceedings of Symposia in Applied Mathematics. American Mathematical Society, 1967. <http://jmc.stanford.edu/articles/mcpain/mcpain.pdf> ## Tags compiler -/ namespace Arithcc section Types /-! ### Types -/ /-- Value type shared by both source and target languages. -/ abbrev Word := ℕ /-- Variable identifier type in the source language. -/ abbrev Identifier := String /-- Register name type in the target language. -/ abbrev Register := ℕ theorem Register.lt_succ_self : ∀ r : Register, r < r + 1 := Nat.lt_succ_self theorem Register.le_of_lt_succ {r₁ r₂ : Register} : r₁ < r₂ + 1 → r₁ ≤ r₂ := Nat.le_of_succ_le_succ end Types section Source /-! ### Source language -/ /-- An expression in the source language is formed by constants, variables, and sums. -/ inductive Expr | const (v : Word) : Expr | var (x : Identifier) : Expr | sum (s₁ s₂ : Expr) : Expr deriving Inhabited /-- The semantics of the source language (2.1). -/ @[simp] def value : Expr → (Identifier → Word) → Word | Expr.const v, _ => v | Expr.var x, ξ => ξ x | Expr.sum s₁ s₂, ξ => value s₁ ξ + value s₂ ξ end Source section Target /-! ### Target language -/ /-- Instructions of the target machine language (3.1--3.7). -/ inductive Instruction | li : Word → Instruction | load : Register → Instruction | sto : Register → Instruction | add : Register → Instruction deriving Inhabited /-- Machine state consists of the accumulator and a vector of registers. The paper uses two functions `c` and `a` for accessing both the accumulator and registers. For clarity, we make accessing the accumulator explicit and use `read`/`write` for registers. -/ structure State where mk :: ac : Word rs : Register → Word instance : Inhabited State := ⟨{ ac := 0 rs := fun _ => 0 }⟩ /-- This is similar to the `c` function (3.8), but for registers only. -/ @[simp] def read (r : Register) (η : State) : Word := η.rs r /-- This is similar to the `a` function (3.9), but for registers only. -/ @[simp] def write (r : Register) (v : Word) (η : State) : State := { η with rs := fun x => if x = r then v else η.rs x } /-- The semantics of the target language (3.11). -/ def step : Instruction → State → State | Instruction.li v, η => { η with ac := v } | Instruction.load r, η => { η with ac := read r η } | Instruction.sto r, η => write r η.ac η | Instruction.add r, η => { η with ac := read r η + η.ac } /-- The resulting machine state of running a target program from a given machine state (3.12). -/ @[simp] def outcome : List Instruction → State → State | [], η => η | i :: is, η => outcome is (step i η) /-- A lemma on the concatenation of two programs (3.13). -/ @[simp] theorem outcome_append (p₁ p₂ : List Instruction) (η : State) : outcome (p₁ ++ p₂) η = outcome p₂ (outcome p₁ η) := by induction p₁ generalizing η with | nil => simp | cons _ _ p₁_ih => simp [p₁_ih] end Target section Compiler open Instruction /-! ### Compiler -/ /-- Map a variable in the source expression to a machine register. -/ @[simp] def loc (ν : Identifier) (map : Identifier → Register) : Register := map ν /-- The implementation of the compiler (4.2). This definition explicitly takes a map from variables to registers. -/ @[simp↓] def compile (map : Identifier → Register) : Expr → Register → List Instruction | Expr.const v, _ => [li v] | Expr.var x, _ => [load (loc x map)] | Expr.sum s₁ s₂, t => compile map s₁ t ++ [sto t] ++ compile map s₂ (t + 1) ++ [add t] end Compiler section Correctness /-! ### Correctness -/ /-- Machine states ζ₁ and ζ₂ are equal except for the accumulator and registers {x | x ≥ t}. -/ def StateEqRs (t : Register) (ζ₁ ζ₂ : State) : Prop := ∀ r : Register, r < t → ζ₁.rs r = ζ₂.rs r notation:50 ζ₁ " ≃[" t "]/ac " ζ₂:50 => StateEqRs t ζ₁ ζ₂ @[refl] protected theorem StateEqRs.refl (t : Register) (ζ : State) : ζ ≃[t]/ac ζ := by simp [StateEqRs] @[symm] protected theorem StateEqRs.symm {t : Register} (ζ₁ ζ₂ : State) : ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₁ := by simp_all [StateEqRs] @[trans] protected theorem StateEqRs.trans {t : Register} (ζ₁ ζ₂ ζ₃ : State) : ζ₁ ≃[t]/ac ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := by simp_all [StateEqRs] /-- Machine states ζ₁ and ζ₂ are equal except for registers {x | x ≥ t}. -/ def StateEq (t : Register) (ζ₁ ζ₂ : State) : Prop := ζ₁.ac = ζ₂.ac ∧ StateEqRs t ζ₁ ζ₂ notation:50 ζ₁ " ≃[" t "] " ζ₂:50 => StateEq t ζ₁ ζ₂ @[refl] protected theorem StateEq.refl (t : Register) (ζ : State) : ζ ≃[t] ζ := by simp [StateEq]; rfl @[symm] protected theorem StateEq.symm {t : Register} (ζ₁ ζ₂ : State) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₁ := by simp [StateEq]; intros constructor <;> (symm; assumption) @[trans] protected theorem StateEq.trans {t : Register} (ζ₁ ζ₂ ζ₃ : State) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t] ζ₃ → ζ₁ ≃[t] ζ₃ := by simp [StateEq]; intros constructor · simp_all only · trans ζ₂ <;> assumption instance (t : Register) : Trans (StateEq (t + 1)) (StateEq (t + 1)) (StateEq (t + 1)) := ⟨@StateEq.trans _⟩ /-- Transitivity of chaining `≃[t]` and `≃[t]/ac`. -/ @[trans] protected theorem StateEqStateEqRs.trans (t : Register) (ζ₁ ζ₂ ζ₃ : State) : ζ₁ ≃[t] ζ₂ → ζ₂ ≃[t]/ac ζ₃ → ζ₁ ≃[t]/ac ζ₃ := by simp [StateEq]; intros trans ζ₂ <;> assumption instance (t : Register) : Trans (StateEq (t + 1)) (StateEqRs (t + 1)) (StateEqRs (t + 1)) := ⟨@StateEqStateEqRs.trans _⟩ /-- Writing the same value to register `t` gives `≃[t + 1]` from `≃[t]`. -/ theorem stateEq_implies_write_eq {t : Register} {ζ₁ ζ₂ : State} (h : ζ₁ ≃[t] ζ₂) (v : Word) : write t v ζ₁ ≃[t + 1] write t v ζ₂ := by simp [StateEq, StateEqRs] at * constructor; · exact h.1 intro r hr have hr : r ≤ t := Register.le_of_lt_succ hr rcases lt_or_eq_of_le hr with hr | hr · obtain ⟨_, h⟩ := h specialize h r hr simp_all · simp_all /-- Writing the same value to any register preserves `≃[t]/ac`. -/ theorem stateEqRs_implies_write_eq_rs {t : Register} {ζ₁ ζ₂ : State} (h : ζ₁ ≃[t]/ac ζ₂) (r : Register) (v : Word) : write r v ζ₁ ≃[t]/ac write r v ζ₂ := by simp [StateEqRs] at * intro r' hr' specialize h r' hr' congr /-- `≃[t + 1]` with writing to register `t` implies `≃[t]`. -/ theorem write_eq_implies_stateEq {t : Register} {v : Word} {ζ₁ ζ₂ : State} (h : ζ₁ ≃[t + 1] write t v ζ₂) : ζ₁ ≃[t] ζ₂ := by simp [StateEq, StateEqRs] at * constructor; · exact h.1 intro r hr obtain ⟨_, h⟩ := h specialize h r (lt_trans hr (Register.lt_succ_self _)) rwa [if_neg (ne_of_lt hr)] at h /-- The main **compiler correctness theorem**. Unlike Theorem 1 in the paper, both `map` and the assumption on `t` are explicit. -/ theorem compiler_correctness (map : Identifier → Register) (e : Expr) (ξ : Identifier → Word) (η : State) (t : Register) (hmap : ∀ x, read (loc x map) η = ξ x) (ht : ∀ x, loc x map < t) : outcome (compile map e t) η ≃[t] { η with ac := value e ξ } := by induction e generalizing η t with -- 5.I | const => simp [StateEq, step]; rfl -- 5.II | var => simp_all [StateEq, StateEqRs, step] -- 5.III | sum => rename_i e_s₁ e_s₂ e_ih_s₁ e_ih_s₂ simp only [compile, List.append_assoc, List.cons_append, outcome_append, outcome, value] generalize value e_s₁ ξ = ν₁ at e_ih_s₁ ⊢ generalize value e_s₂ ξ = ν₂ at e_ih_s₂ ⊢ generalize dν : ν₁ + ν₂ = ν generalize dζ₁ : outcome (compile _ e_s₁ t) η = ζ₁ generalize dζ₂ : step (Instruction.sto t) ζ₁ = ζ₂ generalize dζ₃ : outcome (compile _ e_s₂ (t + 1)) ζ₂ = ζ₃ generalize dζ₄ : step (Instruction.add t) ζ₃ = ζ₄ have hζ₁ : ζ₁ ≃[t] { η with ac := ν₁ } := calc ζ₁ = outcome (compile map e_s₁ t) η := by simp_all _ ≃[t] { η with ac := ν₁ } := by apply e_ih_s₁ <;> assumption have hζ₁_ν₁ : ζ₁.ac = ν₁ := by simp_all [StateEq] have hζ₂ : ζ₂ ≃[t + 1]/ac write t ν₁ η := calc ζ₂ = step (Instruction.sto t) ζ₁ := by simp_all _ = write t ζ₁.ac ζ₁ := by simp [step] _ = write t ν₁ ζ₁ := by simp_all _ ≃[t + 1] write t ν₁ { η with ac := ν₁ } := by apply stateEq_implies_write_eq hζ₁ _ ≃[t + 1]/ac write t ν₁ η := by apply stateEqRs_implies_write_eq_rs simp [StateEqRs] have ht' : ∀ x, loc x map < t + 1 := by intros apply lt_trans (ht _) (Register.lt_succ_self _) have hmap' : ∀ x, read (loc x map) ζ₂ = ξ x := by intro x calc read (loc x map) ζ₂ = read (loc x map) (write t ν₁ η) := hζ₂ _ (ht' _) _ = read (loc x map) η := by simp only [loc] at ht; simp [(ht _).ne] _ = ξ x := hmap x have hζ₃ : ζ₃ ≃[t + 1] { write t ν₁ η with ac := ν₂ } := calc ζ₃ = outcome (compile map e_s₂ (t + 1)) ζ₂ := by simp_all _ ≃[t + 1] { ζ₂ with ac := ν₂ } := by apply e_ih_s₂ <;> assumption _ ≃[t + 1] { write t ν₁ η with ac := ν₂ } := by simp [StateEq]; apply hζ₂ have hζ₃_ν₂ : ζ₃.ac = ν₂ := by simp_all [StateEq] have hζ₃_ν₁ : read t ζ₃ = ν₁ := by simp [StateEq, StateEqRs] at hζ₃ ⊢ obtain ⟨_, hζ₃⟩ := hζ₃ specialize hζ₃ t (Register.lt_succ_self _) simp_all have hζ₄ : ζ₄ ≃[t + 1] { write t ν₁ η with ac := ν } := calc ζ₄ = step (Instruction.add t) ζ₃ := by simp_all _ = { ζ₃ with ac := read t ζ₃ + ζ₃.ac } := by simp [step] _ = { ζ₃ with ac := ν } := by simp_all _ ≃[t + 1] { { write t ν₁ η with ac := ν₂ } with ac := ν } := by simp [StateEq] at hζ₃ ⊢; cases hζ₃; assumption _ ≃[t + 1] { write t ν₁ η with ac := ν } := by simp_all; rfl apply write_eq_implies_stateEq <;> assumption end Correctness section Test open Instruction /-- The example in the paper for compiling (x + 3) + (x + (y + 2)). -/ example (x y t : Register) : let map v := if v = "x" then x else if v = "y" then y else 0 let p := Expr.sum (Expr.sum (Expr.var "x") (Expr.const 3)) (Expr.sum (Expr.var "x") (Expr.sum (Expr.var "y") (Expr.const 2))) compile map p t = [load x, sto t, li 3, add t, sto t, load x, sto (t + 1), load y, sto (t + 2), li 2, add (t + 2), add (t + 1), add t] := rfl end Test end Arithcc
seq.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat. (******************************************************************************) (* The seq type is the ssreflect type for sequences; it is an alias for the *) (* standard Coq list type. The ssreflect library equips it with many *) (* operations, as well as eqType and predType (and, later, choiceType) *) (* structures. The operations are geared towards reflection: they generally *) (* expect and provide boolean predicates, e.g., the membership predicate *) (* expects an eqType. To avoid any confusion we do not Import the Coq List *) (* module. *) (* As there is no true subtyping in Coq, we don't use a type for non-empty *) (* sequences; rather, we pass explicitly the head and tail of the sequence. *) (* The empty sequence is especially bothersome for subscripting, since it *) (* forces us to pass a default value. This default value can often be hidden *) (* by a notation. *) (* Here is the list of seq operations: *) (* ** Constructors: *) (* seq T == the type of sequences of items of type T. *) (* bitseq == seq bool. *) (* [::], nil, Nil T == the empty sequence (of type T). *) (* x :: s, cons x s, Cons T x s == the sequence x followed by s (of type T). *) (* [:: x] == the singleton sequence. *) (* [:: x_0; ...; x_n] == the explicit sequence of the x_i. *) (* [:: x_0, ..., x_n & s] == the sequence of the x_i, followed by s. *) (* rcons s x == the sequence s, followed by x. *) (* All of the above, except rcons, can be used in patterns. We define a view *) (* lastP and an induction principle last_ind that can be used to decompose *) (* or traverse a sequence in a right to left order. The view lemma lastP has *) (* a dependent family type, so the ssreflect tactic case/lastP: p => [|p' x] *) (* will generate two subgoals in which p has been replaced by [::] and by *) (* rcons p' x, respectively. *) (* ** Factories: *) (* nseq n x == a sequence of n x's. *) (* ncons n x s == a sequence of n x's, followed by s. *) (* seqn n x_0 ... x_n-1 == the sequence of the x_i; can be partially applied. *) (* iota m n == the sequence m, m + 1, ..., m + n - 1. *) (* mkseq f n == the sequence f 0, f 1, ..., f (n - 1). *) (* ** Sequential access: *) (* head x0 s == the head (zero'th item) of s if s is non-empty, else x0. *) (* ohead s == None if s is empty, else Some x when the head of s is x. *) (* behead s == s minus its head, i.e., s' if s = x :: s', else [::]. *) (* last x s == the last element of x :: s (which is non-empty). *) (* belast x s == x :: s minus its last item. *) (* ** Dimensions: *) (* size s == the number of items (length) in s. *) (* shape ss == the sequence of sizes of the items of the sequence of *) (* sequences ss. *) (* ** Random access: *) (* nth x0 s i == the item i of s (numbered from 0), or x0 if s does *) (* not have at least i+1 items (i.e., size x <= i) *) (* s`_i == standard notation for nth x0 s i for a default x0, *) (* e.g., 0 for rings. *) (* onth s i == Some x if x is the i^th idem of s (numbered from 0), *) (* or None if size s <= i) *) (* set_nth x0 s i y == s where item i has been changed to y; if s does not *) (* have an item i, it is first padded with copies of x0 *) (* to size i+1. *) (* incr_nth s i == the nat sequence s with item i incremented (s is *) (* first padded with 0's to size i+1, if needed). *) (* ** Predicates: *) (* nilp s <=> s is [::]. *) (* := (size s == 0). *) (* x \in s == x appears in s (this requires an eqType for T). *) (* index x s == the first index at which x appears in s, or size s if *) (* x \notin s. *) (* has a s <=> a holds for some item in s, where a is an applicative *) (* bool predicate. *) (* all a s <=> a holds for all items in s. *) (* 'has_aP <-> the view reflect (exists2 x, x \in s & A x) (has a s), *) (* where aP x : reflect (A x) (a x). *) (* 'all_aP <=> the view for reflect {in s, forall x, A x} (all a s). *) (* all2 r s t <=> the (bool) relation r holds for all _respective_ items *) (* in s and t, which must also have the same size, i.e., *) (* for s := [:: x1; ...; x_m] and t := [:: y1; ...; y_n], *) (* the condition [&& r x_1 y_1, ..., r x_n y_n & m == n]. *) (* find p s == the index of the first item in s for which p holds, *) (* or size s if no such item is found. *) (* count p s == the number of items of s for which p holds. *) (* count_mem x s == the multiplicity of x in s, i.e., count (pred1 x) s. *) (* tally s == a tally of s, i.e., a sequence of (item, multiplicity) *) (* pairs for all items in sequence s (without duplicates). *) (* incr_tally bs x == increment the multiplicity of x in the tally bs, or add *) (* x with multiplicity 1 at then end if x is not in bs. *) (* bs \is a wf_tally <=> bs is well-formed tally, with no duplicate items or *) (* null multiplicities. *) (* tally_seq bs == the expansion of a tally bs into a sequence where each *) (* (x, n) pair expands into a sequence of n x's. *) (* constant s <=> all items in s are identical (trivial if s = [::]). *) (* uniq s <=> all the items in s are pairwise different. *) (* subseq s1 s2 <=> s1 is a subsequence of s2, i.e., s1 = mask m s2 for *) (* some m : bitseq (see below). *) (* infix s1 s2 <=> s1 is a contiguous subsequence of s2, i.e., *) (* s ++ s1 ++ s' = s2 for some sequences s, s'. *) (* prefix s1 s2 <=> s1 is a subchain of s2 appearing at the beginning *) (* of s2. *) (* suffix s1 s2 <=> s1 is a subchain of s2 appearing at the end of s2. *) (* infix_index s1 s2 <=> the first index at which s1 appears in s2, *) (* or (size s2).+1 if infix s1 s2 is false. *) (* perm_eq s1 s2 <=> s2 is a permutation of s1, i.e., s1 and s2 have the *) (* items (with the same repetitions), but possibly in a *) (* different order. *) (* perm_eql s1 s2 <-> s1 and s2 behave identically on the left of perm_eq. *) (* perm_eqr s1 s2 <-> s1 and s2 behave identically on the right of perm_eq. *) (* --> These left/right transitive versions of perm_eq make it easier to *) (* chain a sequence of equivalences. *) (* permutations s == a duplicate-free list of all permutations of s. *) (* ** Filtering: *) (* filter p s == the subsequence of s consisting of all the items *) (* for which the (boolean) predicate p holds. *) (* rem x s == the subsequence of s, where the first occurrence *) (* of x has been removed (compare filter (predC1 x) s *) (* where ALL occurrences of x are removed). *) (* undup s == the subsequence of s containing only the first *) (* occurrence of each item in s, i.e., s with all *) (* duplicates removed. *) (* mask m s == the subsequence of s selected by m : bitseq, with *) (* item i of s selected by bit i in m (extra items or *) (* bits are ignored. *) (* ** Surgery: *) (* s1 ++ s2, cat s1 s2 == the concatenation of s1 and s2. *) (* take n s == the sequence containing only the first n items of s *) (* (or all of s if size s <= n). *) (* drop n s == s minus its first n items ([::] if size s <= n) *) (* rot n s == s rotated left n times (or s if size s <= n). *) (* := drop n s ++ take n s *) (* rotr n s == s rotated right n times (or s if size s <= n). *) (* rev s == the (linear time) reversal of s. *) (* catrev s1 s2 == the reversal of s1 followed by s2 (this is the *) (* recursive form of rev). *) (* ** Dependent iterator: for s : seq S and t : S -> seq T *) (* [seq E | x <- s, y <- t] := flatten [seq [seq E | x <- t] | y <- s] *) (* == the sequence of all the f x y, with x and y drawn from *) (* s and t, respectively, in row-major order, *) (* and where t is possibly dependent in elements of s *) (* allpairs_dep f s t := self expanding definition for *) (* [seq f x y | x <- s, y <- t y] *) (* ** Iterators: for s == [:: x_1, ..., x_n], t == [:: y_1, ..., y_m], *) (* allpairs f s t := same as allpairs_dep but where t is non dependent, *) (* i.e. self expanding definition for *) (* [seq f x y | x <- s, y <- t] *) (* := [:: f x_1 y_1; ...; f x_1 y_m; f x_2 y_1; ...; f x_n y_m] *) (* allrel r xs ys := all [pred x | all (r x) ys] xs *) (* <=> r x y holds whenever x is in xs and y is in ys *) (* all2rel r xs := allrel r xs xs *) (* <=> the proposition r x y holds for all possible x, y in xs.*) (* pairwise r xs <=> the relation r holds for any i-th and j-th element of *) (* xs such that i < j. *) (* map f s == the sequence [:: f x_1, ..., f x_n]. *) (* pmap pf s == the sequence [:: y_i1, ..., y_ik] where i1 < ... < ik, *) (* pf x_i = Some y_i, and pf x_j = None iff j is not in *) (* {i1, ..., ik}. *) (* foldr f a s == the right fold of s by f (i.e., the natural iterator). *) (* := f x_1 (f x_2 ... (f x_n a)) *) (* sumn s == x_1 + (x_2 + ... + (x_n + 0)) (when s : seq nat). *) (* foldl f a s == the left fold of s by f. *) (* := f (f ... (f a x_1) ... x_n-1) x_n *) (* scanl f a s == the sequence of partial accumulators of foldl f a s. *) (* := [:: f a x_1; ...; foldl f a s] *) (* pairmap f a s == the sequence of f applied to consecutive items in a :: s. *) (* := [:: f a x_1; f x_1 x_2; ...; f x_n-1 x_n] *) (* zip s t == itemwise pairing of s and t (dropping any extra items). *) (* := [:: (x_1, y_1); ...; (x_mn, y_mn)] with mn = minn n m. *) (* unzip1 s == [:: (x_1).1; ...; (x_n).1] when s : seq (S * T). *) (* unzip2 s == [:: (x_1).2; ...; (x_n).2] when s : seq (S * T). *) (* flatten s == x_1 ++ ... ++ x_n ++ [::] when s : seq (seq T). *) (* reshape r s == s reshaped into a sequence of sequences whose sizes are *) (* given by r (truncating if s is too long or too short). *) (* := [:: [:: x_1; ...; x_r1]; *) (* [:: x_(r1 + 1); ...; x_(r0 + r1)]; *) (* ...; *) (* [:: x_(r1 + ... + r(k-1) + 1); ...; x_(r0 + ... rk)]] *) (* flatten_index sh r c == the index, in flatten ss, of the item of indexes *) (* (r, c) in any sequence of sequences ss of shape sh *) (* := sh_1 + sh_2 + ... + sh_r + c *) (* reshape_index sh i == the index, in reshape sh s, of the sequence *) (* containing the i-th item of s. *) (* reshape_offset sh i == the offset, in the (reshape_index sh i)-th *) (* sequence of reshape sh s of the i-th item of s *) (* ** Notation for manifest comprehensions: *) (* [seq x <- s | C] := filter (fun x => C) s. *) (* [seq E | x <- s] := map (fun x => E) s. *) (* [seq x <- s | C1 & C2] := [seq x <- s | C1 && C2]. *) (* [seq E | x <- s & C] := [seq E | x <- [seq x | C]]. *) (* --> The above allow optional type casts on the eigenvariables, as in *) (* [seq x : T <- s | C] or [seq E | x : T <- s, y : U <- t]. The cast may be *) (* needed as type inference considers E or C before s. *) (* We are quite systematic in providing lemmas to rewrite any composition *) (* of two operations. "rev", whose simplifications are not natural, is *) (* protected with simpl never. *) (* ** The following are equivalent: *) (* [<-> P0; P1; ..; Pn] <-> P0, P1, ..., Pn are all equivalent. *) (* := P0 -> P1 -> ... -> Pn -> P0 *) (* if T : [<-> P0; P1; ..; Pn] is such an equivalence, and i, j are in nat *) (* then T i j is a proof of the equivalence Pi <-> Pj between Pi and Pj; *) (* when i (resp. j) is out of bounds, Pi (resp. Pj) defaults to P0. *) (* The tactic tfae splits the goal into n+1 implications to prove. *) (* An example of use can be found in fingraph theorem orbitPcycle. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope seq_scope. Reserved Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" (format "[ '<->' '[' P0 ; '/' P1 ; '/' .. ; '/' Pn ']' ]"). Delimit Scope seq_scope with SEQ. Open Scope seq_scope. (* Inductive seq (T : Type) : Type := Nil | Cons of T & seq T. *) Notation seq := list. Bind Scope seq_scope with list. Arguments cons {T%_type} x s%_SEQ : rename. Arguments nil {T%_type} : rename. Notation Cons T := (@cons T) (only parsing). Notation Nil T := (@nil T) (only parsing). (* As :: and ++ are (improperly) declared in Init.datatypes, we only rebind *) (* them here. *) Infix "::" := cons : seq_scope. Notation "[ :: ]" := nil (format "[ :: ]") : seq_scope. Notation "[ :: x1 ]" := (x1 :: [::]) (format "[ :: x1 ]") : seq_scope. Notation "[ :: x & s ]" := (x :: s) (only parsing) : seq_scope. Notation "[ :: x1 , x2 , .. , xn & s ]" := (x1 :: x2 :: .. (xn :: s) ..) (format "'[hv' [ :: '[' x1 , '/' x2 , '/' .. , '/' xn ']' '/ ' & s ] ']'" ) : seq_scope. Notation "[ :: x1 ; x2 ; .. ; xn ]" := (x1 :: x2 :: .. [:: xn] ..) (format "[ :: '[' x1 ; '/' x2 ; '/' .. ; '/' xn ']' ]" ) : seq_scope. Section Sequences. Variable n0 : nat. (* numerical parameter for take, drop et al *) Variable T : Type. (* must come before the implicit Type *) Variable x0 : T. (* default for head/nth *) Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint size s := if s is _ :: s' then (size s').+1 else 0. Lemma size0nil s : size s = 0 -> s = [::]. Proof. by case: s. Qed. Definition nilp s := size s == 0. Lemma nilP s : reflect (s = [::]) (nilp s). Proof. by case: s => [|x s]; constructor. Qed. Definition ohead s := if s is x :: _ then Some x else None. Definition head s := if s is x :: _ then x else x0. Definition behead s := if s is _ :: s' then s' else [::]. Lemma size_behead s : size (behead s) = (size s).-1. Proof. by case: s. Qed. (* Factories *) Definition ncons n x := iter n (cons x). Definition nseq n x := ncons n x [::]. Lemma size_ncons n x s : size (ncons n x s) = n + size s. Proof. by elim: n => //= n ->. Qed. Lemma size_nseq n x : size (nseq n x) = n. Proof. by rewrite size_ncons addn0. Qed. (* n-ary, dependently typed constructor. *) Fixpoint seqn_type n := if n is n'.+1 then T -> seqn_type n' else seq T. Fixpoint seqn_rec f n : seqn_type n := if n is n'.+1 return seqn_type n then fun x => seqn_rec (fun s => f (x :: s)) n' else f [::]. Definition seqn := seqn_rec id. (* Sequence catenation "cat". *) Fixpoint cat s1 s2 := if s1 is x :: s1' then x :: s1' ++ s2 else s2 where "s1 ++ s2" := (cat s1 s2) : seq_scope. Lemma cat0s s : [::] ++ s = s. Proof. by []. Qed. Lemma cat1s x s : [:: x] ++ s = x :: s. Proof. by []. Qed. Lemma cat_cons x s1 s2 : (x :: s1) ++ s2 = x :: s1 ++ s2. Proof. by []. Qed. Lemma cat_nseq n x s : nseq n x ++ s = ncons n x s. Proof. by elim: n => //= n ->. Qed. Lemma nseqD n1 n2 x : nseq (n1 + n2) x = nseq n1 x ++ nseq n2 x. Proof. by rewrite cat_nseq /nseq /ncons iterD. Qed. Lemma cats0 s : s ++ [::] = s. Proof. by elim: s => //= x s ->. Qed. Lemma catA s1 s2 s3 : s1 ++ s2 ++ s3 = (s1 ++ s2) ++ s3. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma size_cat s1 s2 : size (s1 ++ s2) = size s1 + size s2. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma cat_nilp s1 s2 : nilp (s1 ++ s2) = nilp s1 && nilp s2. Proof. by case: s1. Qed. (* last, belast, rcons, and last induction. *) Fixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z]. Lemma rcons_cons x s z : rcons (x :: s) z = x :: rcons s z. Proof. by []. Qed. Lemma cats1 s z : s ++ [:: z] = rcons s z. Proof. by elim: s => //= x s ->. Qed. Fixpoint last x s := if s is x' :: s' then last x' s' else x. Fixpoint belast x s := if s is x' :: s' then x :: (belast x' s') else [::]. Lemma lastI x s : x :: s = rcons (belast x s) (last x s). Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cons x y s : last x (y :: s) = last y s. Proof. by []. Qed. Lemma size_rcons s x : size (rcons s x) = (size s).+1. Proof. by rewrite -cats1 size_cat addnC. Qed. Lemma size_belast x s : size (belast x s) = size s. Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cat x s1 s2 : last x (s1 ++ s2) = last (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma last_rcons x s z : last x (rcons s z) = z. Proof. by rewrite -cats1 last_cat. Qed. Lemma belast_cat x s1 s2 : belast x (s1 ++ s2) = belast x s1 ++ belast (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma belast_rcons x s z : belast x (rcons s z) = x :: s. Proof. by rewrite lastI -!cats1 belast_cat. Qed. Lemma cat_rcons x s1 s2 : rcons s1 x ++ s2 = s1 ++ x :: s2. Proof. by rewrite -cats1 -catA. Qed. Lemma rcons_cat x s1 s2 : rcons (s1 ++ s2) x = s1 ++ rcons s2 x. Proof. by rewrite -!cats1 catA. Qed. Variant last_spec : seq T -> Type := | LastNil : last_spec [::] | LastRcons s x : last_spec (rcons s x). Lemma lastP s : last_spec s. Proof. case: s => [|x s]; [left | rewrite lastI; right]. Qed. Lemma last_ind P : P [::] -> (forall s x, P s -> P (rcons s x)) -> forall s, P s. Proof. move=> Hnil Hlast s; rewrite -(cat0s s). elim: s [::] Hnil => [|x s2 IHs] s1 Hs1; first by rewrite cats0. by rewrite -cat_rcons; apply/IHs/Hlast. Qed. (* Sequence indexing. *) Fixpoint nth s n {struct n} := if s is x :: s' then if n is n'.+1 then @nth s' n' else x else x0. Fixpoint set_nth s n y {struct n} := if s is x :: s' then if n is n'.+1 then x :: @set_nth s' n' y else y :: s' else ncons n x0 [:: y]. Lemma nth0 s : nth s 0 = head s. Proof. by []. Qed. Lemma nth_default s n : size s <= n -> nth s n = x0. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma if_nth s b n : b || (size s <= n) -> (if b then nth s n else x0) = nth s n. Proof. by case: leqP; case: ifP => //= *; rewrite nth_default. Qed. Lemma nth_nil n : nth [::] n = x0. Proof. by case: n. Qed. Lemma nth_seq1 n x : nth [:: x] n = if n == 0 then x else x0. Proof. by case: n => [|[]]. Qed. Lemma last_nth x s : last x s = nth (x :: s) (size s). Proof. by elim: s x => [|y s IHs] x /=. Qed. Lemma nth_last s : nth s (size s).-1 = last x0 s. Proof. by case: s => //= x s; rewrite last_nth. Qed. Lemma nth_behead s n : nth (behead s) n = nth s n.+1. Proof. by case: s n => [|x s] [|n]. Qed. Lemma nth_cat s1 s2 n : nth (s1 ++ s2) n = if n < size s1 then nth s1 n else nth s2 (n - size s1). Proof. by elim: s1 n => [|x s1 IHs] []. Qed. Lemma nth_rcons s x n : nth (rcons s x) n = if n < size s then nth s n else if n == size s then x else x0. Proof. by elim: s n => [|y s IHs] [] //=; apply: nth_nil. Qed. Lemma nth_rcons_default s i : nth (rcons s x0) i = nth s i. Proof. by rewrite nth_rcons; case: ltngtP => //[/ltnW ?|->]; rewrite nth_default. Qed. Lemma nth_ncons m x s n : nth (ncons m x s) n = if n < m then x else nth s (n - m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma nth_nseq m x n : nth (nseq m x) n = (if n < m then x else x0). Proof. by elim: m n => [|m IHm] []. Qed. Lemma eq_from_nth s1 s2 : size s1 = size s2 -> (forall i, i < size s1 -> nth s1 i = nth s2 i) -> s1 = s2. Proof. elim: s1 s2 => [|x1 s1 IHs1] [|x2 s2] //= [eq_sz] eq_s12. by rewrite [x1](eq_s12 0) // (IHs1 s2) // => i; apply: (eq_s12 i.+1). Qed. Lemma size_set_nth s n y : size (set_nth s n y) = maxn n.+1 (size s). Proof. rewrite maxnC; elim: s n => [|x s IHs] [|n] //=. - by rewrite size_ncons addn1. - by rewrite IHs maxnSS. Qed. Lemma set_nth_nil n y : set_nth [::] n y = ncons n x0 [:: y]. Proof. by case: n. Qed. Lemma nth_set_nth s n y : nth (set_nth s n y) =1 [eta nth s with n |-> y]. Proof. elim: s n => [|x s IHs] [|n] [|m] //=; rewrite ?nth_nil ?IHs // nth_ncons eqSS. case: ltngtP => // [lt_nm | ->]; last by rewrite subnn. by rewrite nth_default // subn_gt0. Qed. Lemma set_set_nth s n1 y1 n2 y2 (s2 := set_nth s n2 y2) : set_nth (set_nth s n1 y1) n2 y2 = if n1 == n2 then s2 else set_nth s2 n1 y1. Proof. have [-> | ne_n12] := eqVneq. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnA maxnn. by do 2!rewrite !nth_set_nth /=; case: eqP. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnCA. by do 2!rewrite !nth_set_nth /=; case: eqP => // ->; case: eqVneq ne_n12. Qed. (* find, count, has, all. *) Section SeqFind. Variable a : pred T. Fixpoint find s := if s is x :: s' then if a x then 0 else (find s').+1 else 0. Fixpoint filter s := if s is x :: s' then if a x then x :: filter s' else filter s' else [::]. Fixpoint count s := if s is x :: s' then a x + count s' else 0. Fixpoint has s := if s is x :: s' then a x || has s' else false. Fixpoint all s := if s is x :: s' then a x && all s' else true. Lemma size_filter s : size (filter s) = count s. Proof. by elim: s => //= x s <-; case (a x). Qed. Lemma has_count s : has s = (0 < count s). Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma size_filter_gt0 s : (size (filter s) > 0) = (has s). Proof. by rewrite size_filter -has_count. Qed. Lemma count_size s : count s <= size s. Proof. by elim: s => //= x s; case: (a x); last apply: leqW. Qed. Lemma all_count s : all s = (count s == size s). Proof. elim: s => //= x s; case: (a x) => _ //=. by rewrite add0n eqn_leq andbC ltnNge count_size. Qed. Lemma filter_all s : all (filter s). Proof. by elim: s => //= x s IHs; case: ifP => //= ->. Qed. Lemma all_filterP s : reflect (filter s = s) (all s). Proof. apply: (iffP idP) => [| <-]; last exact: filter_all. by elim: s => //= x s IHs /andP[-> Hs]; rewrite IHs. Qed. Lemma filter_id s : filter (filter s) = filter s. Proof. by apply/all_filterP; apply: filter_all. Qed. Lemma has_find s : has s = (find s < size s). Proof. by elim: s => //= x s IHs; case (a x); rewrite ?leqnn. Qed. Lemma find_size s : find s <= size s. Proof. by elim: s => //= x s IHs; case (a x). Qed. Lemma find_cat s1 s2 : find (s1 ++ s2) = if has s1 then find s1 else size s1 + find s2. Proof. by elim: s1 => //= x s1 IHs; case: (a x) => //; rewrite IHs (fun_if succn). Qed. Lemma has_nil : has [::] = false. Proof. by []. Qed. Lemma has_seq1 x : has [:: x] = a x. Proof. exact: orbF. Qed. Lemma has_nseq n x : has (nseq n x) = (0 < n) && a x. Proof. by elim: n => //= n ->; apply: andKb. Qed. Lemma has_seqb (b : bool) x : has (nseq b x) = b && a x. Proof. by rewrite has_nseq lt0b. Qed. Lemma all_nil : all [::] = true. Proof. by []. Qed. Lemma all_seq1 x : all [:: x] = a x. Proof. exact: andbT. Qed. Lemma all_nseq n x : all (nseq n x) = (n == 0) || a x. Proof. by elim: n => //= n ->; apply: orKb. Qed. Lemma all_nseqb (b : bool) x : all (nseq b x) = b ==> a x. Proof. by rewrite all_nseq eqb0 implybE. Qed. Lemma filter_nseq n x : filter (nseq n x) = nseq (a x * n) x. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma count_nseq n x : count (nseq n x) = a x * n. Proof. by rewrite -size_filter filter_nseq size_nseq. Qed. Lemma find_nseq n x : find (nseq n x) = ~~ a x * n. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma nth_find s : has s -> a (nth s (find s)). Proof. by elim: s => //= x s IHs; case a_x: (a x). Qed. Lemma before_find s i : i < find s -> a (nth s i) = false. Proof. by elim: s i => //= x s IHs; case: ifP => // a'x [|i] // /(IHs i). Qed. Lemma hasNfind s : ~~ has s -> find s = size s. Proof. by rewrite has_find; case: ltngtP (find_size s). Qed. Lemma filter_cat s1 s2 : filter (s1 ++ s2) = filter s1 ++ filter s2. Proof. by elim: s1 => //= x s1 ->; case (a x). Qed. Lemma filter_rcons s x : filter (rcons s x) = if a x then rcons (filter s) x else filter s. Proof. by rewrite -!cats1 filter_cat /=; case (a x); rewrite /= ?cats0. Qed. Lemma count_cat s1 s2 : count (s1 ++ s2) = count s1 + count s2. Proof. by rewrite -!size_filter filter_cat size_cat. Qed. Lemma has_cat s1 s2 : has (s1 ++ s2) = has s1 || has s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs orbA. Qed. Lemma has_rcons s x : has (rcons s x) = a x || has s. Proof. by rewrite -cats1 has_cat has_seq1 orbC. Qed. Lemma all_cat s1 s2 : all (s1 ++ s2) = all s1 && all s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs andbA. Qed. Lemma all_rcons s x : all (rcons s x) = a x && all s. Proof. by rewrite -cats1 all_cat all_seq1 andbC. Qed. End SeqFind. Lemma find_pred0 s : find pred0 s = size s. Proof. by []. Qed. Lemma find_predT s : find predT s = 0. Proof. by case: s. Qed. Lemma eq_find a1 a2 : a1 =1 a2 -> find a1 =1 find a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_filter a1 a2 : a1 =1 a2 -> filter a1 =1 filter a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_count a1 a2 : a1 =1 a2 -> count a1 =1 count a2. Proof. by move=> Ea s; rewrite -!size_filter (eq_filter Ea). Qed. Lemma eq_has a1 a2 : a1 =1 a2 -> has a1 =1 has a2. Proof. by move=> Ea s; rewrite !has_count (eq_count Ea). Qed. Lemma eq_all a1 a2 : a1 =1 a2 -> all a1 =1 all a2. Proof. by move=> Ea s; rewrite !all_count (eq_count Ea). Qed. Lemma all_filter (p q : pred T) xs : all p (filter q xs) = all [pred i | q i ==> p i] xs. Proof. by elim: xs => //= x xs <-; case: (q x). Qed. Section SubPred. Variable (a1 a2 : pred T). Hypothesis s12 : subpred a1 a2. Lemma sub_find s : find a2 s <= find a1 s. Proof. by elim: s => //= x s IHs; case: ifP => // /(contraFF (@s12 x))->. Qed. Lemma sub_has s : has a1 s -> has a2 s. Proof. by rewrite !has_find; apply: leq_ltn_trans (sub_find s). Qed. Lemma sub_count s : count a1 s <= count a2 s. Proof. by elim: s => //= x s; apply: leq_add; case a1x: (a1 x); rewrite // s12. Qed. Lemma sub_all s : all a1 s -> all a2 s. Proof. by rewrite !all_count !eqn_leq !count_size => /leq_trans-> //; apply: sub_count. Qed. End SubPred. Lemma filter_pred0 s : filter pred0 s = [::]. Proof. by elim: s. Qed. Lemma filter_predT s : filter predT s = s. Proof. by elim: s => //= x s ->. Qed. Lemma filter_predI a1 a2 s : filter (predI a1 a2) s = filter a1 (filter a2 s). Proof. by elim: s => //= x s ->; rewrite andbC; case: (a2 x). Qed. Lemma count_pred0 s : count pred0 s = 0. Proof. by rewrite -size_filter filter_pred0. Qed. Lemma count_predT s : count predT s = size s. Proof. by rewrite -size_filter filter_predT. Qed. Lemma count_predUI a1 a2 s : count (predU a1 a2) s + count (predI a1 a2) s = count a1 s + count a2 s. Proof. elim: s => //= x s IHs; rewrite /= addnACA [RHS]addnACA IHs. by case: (a1 x) => //; rewrite addn0. Qed. Lemma count_predC a s : count a s + count (predC a) s = size s. Proof. by elim: s => //= x s IHs; rewrite addnACA IHs; case: (a _). Qed. Lemma count_filter a1 a2 s : count a1 (filter a2 s) = count (predI a1 a2) s. Proof. by rewrite -!size_filter filter_predI. Qed. Lemma has_pred0 s : has pred0 s = false. Proof. by rewrite has_count count_pred0. Qed. Lemma has_predT s : has predT s = (0 < size s). Proof. by rewrite has_count count_predT. Qed. Lemma has_predC a s : has (predC a) s = ~~ all a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma has_predU a1 a2 s : has (predU a1 a2) s = has a1 s || has a2 s. Proof. by elim: s => //= x s ->; rewrite -!orbA; do !bool_congr. Qed. Lemma all_pred0 s : all pred0 s = (size s == 0). Proof. by rewrite all_count count_pred0 eq_sym. Qed. Lemma all_predT s : all predT s. Proof. by rewrite all_count count_predT. Qed. Lemma allT (a : pred T) s : (forall x, a x) -> all a s. Proof. by move/eq_all->; apply/all_predT. Qed. Lemma all_predC a s : all (predC a) s = ~~ has a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma all_predI a1 a2 s : all (predI a1 a2) s = all a1 s && all a2 s. Proof. apply: (can_inj negbK); rewrite negb_and -!has_predC -has_predU. by apply: eq_has => x; rewrite /= negb_and. Qed. (* Surgery: drop, take, rot, rotr. *) Fixpoint drop n s {struct s} := match s, n with | _ :: s', n'.+1 => drop n' s' | _, _ => s end. Lemma drop_behead : drop n0 =1 iter n0 behead. Proof. by elim: n0 => [|n IHn] [|x s] //; rewrite iterSr -IHn. Qed. Lemma drop0 s : drop 0 s = s. Proof. by case: s. Qed. Lemma drop1 : drop 1 =1 behead. Proof. by case=> [|x [|y s]]. Qed. Lemma drop_oversize n s : size s <= n -> drop n s = [::]. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma drop_size s : drop (size s) s = [::]. Proof. by rewrite drop_oversize // leqnn. Qed. Lemma drop_cons x s : drop n0 (x :: s) = if n0 is n.+1 then drop n s else x :: s. Proof. by []. Qed. Lemma size_drop s : size (drop n0 s) = size s - n0. Proof. by elim: s n0 => [|x s IHs] []. Qed. Lemma drop_cat s1 s2 : drop n0 (s1 ++ s2) = if n0 < size s1 then drop n0 s1 ++ s2 else drop (n0 - size s1) s2. Proof. by elim: s1 n0 => [|x s1 IHs] []. Qed. Lemma drop_size_cat n s1 s2 : size s1 = n -> drop n (s1 ++ s2) = s2. Proof. by move <-; elim: s1 => //=; rewrite drop0. Qed. Lemma nconsK n x : cancel (ncons n x) (drop n). Proof. by elim: n => // -[]. Qed. Lemma drop_drop s n1 n2 : drop n1 (drop n2 s) = drop (n1 + n2) s. Proof. by elim: s n2 => // x s ihs [|n2]; rewrite ?drop0 ?addn0 ?addnS /=. Qed. Fixpoint take n s {struct s} := match s, n with | x :: s', n'.+1 => x :: take n' s' | _, _ => [::] end. Lemma take0 s : take 0 s = [::]. Proof. by case: s. Qed. Lemma take_oversize n s : size s <= n -> take n s = s. Proof. by elim: s n => [|x s IHs] [|n] //= /IHs->. Qed. Lemma take_size s : take (size s) s = s. Proof. exact: take_oversize. Qed. Lemma take_cons x s : take n0 (x :: s) = if n0 is n.+1 then x :: (take n s) else [::]. Proof. by []. Qed. Lemma drop_rcons s : n0 <= size s -> forall x, drop n0 (rcons s x) = rcons (drop n0 s) x. Proof. by elim: s n0 => [|y s IHs] []. Qed. Lemma cat_take_drop s : take n0 s ++ drop n0 s = s. Proof. by elim: s n0 => [|x s IHs] [|n] //=; rewrite IHs. Qed. Lemma size_takel s : n0 <= size s -> size (take n0 s) = n0. Proof. by move/subKn; rewrite -size_drop -[in size s](cat_take_drop s) size_cat addnK. Qed. Lemma size_take s : size (take n0 s) = if n0 < size s then n0 else size s. Proof. have [le_sn | lt_ns] := leqP (size s) n0; first by rewrite take_oversize. by rewrite size_takel // ltnW. Qed. Lemma size_take_min s : size (take n0 s) = minn n0 (size s). Proof. exact: size_take. Qed. Lemma take_cat s1 s2 : take n0 (s1 ++ s2) = if n0 < size s1 then take n0 s1 else s1 ++ take (n0 - size s1) s2. Proof. elim: s1 n0 => [|x s1 IHs] [|n] //=. by rewrite ltnS subSS -(fun_if (cons x)) -IHs. Qed. Lemma take_size_cat n s1 s2 : size s1 = n -> take n (s1 ++ s2) = s1. Proof. by move <-; elim: s1 => [|x s1 IHs]; rewrite ?take0 //= IHs. Qed. Lemma takel_cat s1 s2 : n0 <= size s1 -> take n0 (s1 ++ s2) = take n0 s1. Proof. by rewrite take_cat; case: ltngtP => // ->; rewrite subnn take0 take_size cats0. Qed. Lemma nth_drop s i : nth (drop n0 s) i = nth s (n0 + i). Proof. rewrite -[s in RHS]cat_take_drop nth_cat size_take ltnNge. case: ltnP => [?|le_s_n0]; rewrite ?(leq_trans le_s_n0) ?leq_addr ?addKn //=. by rewrite drop_oversize // !nth_default. Qed. Lemma find_ltn p s i : has p (take i s) -> find p s < i. Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs. Qed. Lemma has_take p s i : has p s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma has_take_leq (p : pred T) (s : seq T) i : i <= size s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma nth_take i : i < n0 -> forall s, nth (take n0 s) i = nth s i. Proof. move=> lt_i_n0 s; case lt_n0_s: (n0 < size s). by rewrite -[s in RHS]cat_take_drop nth_cat size_take lt_n0_s /= lt_i_n0. by rewrite -[s in LHS]cats0 take_cat lt_n0_s /= cats0. Qed. Lemma take_min i j s : take (minn i j) s = take i (take j s). Proof. by elim: s i j => //= a l IH [|i] [|j] //=; rewrite minnSS IH. Qed. Lemma take_takel i j s : i <= j -> take i (take j s) = take i s. Proof. by move=> ?; rewrite -take_min (minn_idPl _). Qed. Lemma take_taker i j s : j <= i -> take i (take j s) = take j s. Proof. by move=> ?; rewrite -take_min (minn_idPr _). Qed. Lemma take_drop i j s : take i (drop j s) = drop j (take (i + j) s). Proof. by rewrite addnC; elim: s i j => // x s IHs [|i] [|j] /=. Qed. Lemma takeD i j s : take (i + j) s = take i s ++ take j (drop i s). Proof. elim: i j s => [|i IHi] [|j] [|a s] //; first by rewrite take0 addn0 cats0. by rewrite addSn /= IHi. Qed. Lemma takeC i j s : take i (take j s) = take j (take i s). Proof. by rewrite -!take_min minnC. Qed. Lemma take_nseq i j x : i <= j -> take i (nseq j x) = nseq i x. Proof. by move=>/subnKC <-; rewrite nseqD take_size_cat // size_nseq. Qed. Lemma drop_nseq i j x : drop i (nseq j x) = nseq (j - i) x. Proof. case: (leqP i j) => [/subnKC {1}<-|/ltnW j_le_i]. by rewrite nseqD drop_size_cat // size_nseq. by rewrite drop_oversize ?size_nseq // (eqP j_le_i). Qed. (* drop_nth and take_nth below do NOT use the default n0, because the "n" *) (* can be inferred from the condition, whereas the nth default value x0 *) (* will have to be given explicitly (and this will provide "d" as well). *) Lemma drop_nth n s : n < size s -> drop n s = nth s n :: drop n.+1 s. Proof. by elim: s n => [|x s IHs] [|n] Hn //=; rewrite ?drop0 1?IHs. Qed. Lemma take_nth n s : n < size s -> take n.+1 s = rcons (take n s) (nth s n). Proof. by elim: s n => [|x s IHs] //= [|n] Hn /=; rewrite ?take0 -?IHs. Qed. (* Rotation *) Definition rot n s := drop n s ++ take n s. Lemma rot0 s : rot 0 s = s. Proof. by rewrite /rot drop0 take0 cats0. Qed. Lemma size_rot s : size (rot n0 s) = size s. Proof. by rewrite -[s in RHS]cat_take_drop /rot !size_cat addnC. Qed. Lemma rot_oversize n s : size s <= n -> rot n s = s. Proof. by move=> le_s_n; rewrite /rot take_oversize ?drop_oversize. Qed. Lemma rot_size s : rot (size s) s = s. Proof. exact: rot_oversize. Qed. Lemma has_rot s a : has a (rot n0 s) = has a s. Proof. by rewrite has_cat orbC -has_cat cat_take_drop. Qed. Lemma rot_size_cat s1 s2 : rot (size s1) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rot take_size_cat ?drop_size_cat. Qed. Definition rotr n s := rot (size s - n) s. Lemma rotK : cancel (rot n0) (rotr n0). Proof. move=> s; rewrite /rotr size_rot -size_drop {2}/rot. by rewrite rot_size_cat cat_take_drop. Qed. Lemma rot_inj : injective (rot n0). Proof. exact (can_inj rotK). Qed. (* (efficient) reversal *) Fixpoint catrev s1 s2 := if s1 is x :: s1' then catrev s1' (x :: s2) else s2. Definition rev s := catrev s [::]. Lemma catrev_catl s t u : catrev (s ++ t) u = catrev t (catrev s u). Proof. by elim: s u => /=. Qed. Lemma catrev_catr s t u : catrev s (t ++ u) = catrev s t ++ u. Proof. by elim: s t => //= x s IHs t; rewrite -IHs. Qed. Lemma catrevE s t : catrev s t = rev s ++ t. Proof. by rewrite -catrev_catr. Qed. Lemma rev_cons x s : rev (x :: s) = rcons (rev s) x. Proof. by rewrite -cats1 -catrevE. Qed. Lemma size_rev s : size (rev s) = size s. Proof. by elim: s => // x s IHs; rewrite rev_cons size_rcons IHs. Qed. Lemma rev_nilp s : nilp (rev s) = nilp s. Proof. by rewrite /nilp size_rev. Qed. Lemma rev_cat s t : rev (s ++ t) = rev t ++ rev s. Proof. by rewrite -catrev_catr -catrev_catl. Qed. Lemma rev_rcons s x : rev (rcons s x) = x :: rev s. Proof. by rewrite -cats1 rev_cat. Qed. Lemma revK : involutive rev. Proof. by elim=> //= x s IHs; rewrite rev_cons rev_rcons IHs. Qed. Lemma nth_rev n s : n < size s -> nth (rev s) n = nth s (size s - n.+1). Proof. elim/last_ind: s => // s x IHs in n *. rewrite rev_rcons size_rcons ltnS subSS -cats1 nth_cat /=. case: n => [|n] lt_n_s; first by rewrite subn0 ltnn subnn. by rewrite subnSK //= leq_subr IHs. Qed. Lemma filter_rev a s : filter a (rev s) = rev (filter a s). Proof. by elim: s => //= x s IH; rewrite fun_if !rev_cons filter_rcons IH. Qed. Lemma count_rev a s : count a (rev s) = count a s. Proof. by rewrite -!size_filter filter_rev size_rev. Qed. Lemma has_rev a s : has a (rev s) = has a s. Proof. by rewrite !has_count count_rev. Qed. Lemma all_rev a s : all a (rev s) = all a s. Proof. by rewrite !all_count count_rev size_rev. Qed. Lemma rev_nseq n x : rev (nseq n x) = nseq n x. Proof. by elim: n => // n IHn; rewrite -[in LHS]addn1 nseqD rev_cat IHn. Qed. End Sequences. Prenex Implicits size ncons nseq head ohead behead last rcons belast. Arguments seqn {T} n. Prenex Implicits cat take drop rot rotr catrev. Prenex Implicits find count nth all has filter. Arguments rev {T} s : simpl never. Arguments nth : simpl nomatch. Arguments set_nth : simpl nomatch. Arguments take : simpl nomatch. Arguments drop : simpl nomatch. Arguments nilP {T s}. Arguments all_filterP {T a s}. Arguments rotK n0 {T} s : rename. Arguments rot_inj {n0 T} [s1 s2] eq_rot_s12 : rename. Arguments revK {T} s : rename. Notation count_mem x := (count (pred_of_simpl (pred1 x))). Infix "++" := cat : seq_scope. Notation "[ 'seq' x <- s | C ]" := (filter (fun x => C%B) s) (x at level 99, format "[ '[hv' 'seq' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (format "[ '[hv' 'seq' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C ]" := (filter (fun x => C%B) s) (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' x : T <- s | C ]" := (filter (fun x : T => C%B) s) (only parsing). Notation "[ 'seq' x : T <- s | C1 & C2 ]" := [seq x : T <- s | C1 && C2] (only parsing). (* Double induction/recursion. *) Lemma seq_ind2 {S T} (P : seq S -> seq T -> Type) : P [::] [::] -> (forall x y s t, size s = size t -> P s t -> P (x :: s) (y :: t)) -> forall s t, size s = size t -> P s t. Proof. by move=> Pnil Pcons; elim=> [|x s IHs] [|y t] //= [eq_sz]; apply/Pcons/IHs. Qed. Section AllIff. (* The Following Are Equivalent *) (* We introduce a specific conjunction, used to chain the consecutive *) (* items in a circular list of implications *) Inductive all_iff_and (P Q : Prop) : Prop := AllIffConj of P & Q. Definition all_iff (P0 : Prop) (Ps : seq Prop) : Prop := let fix loop (P : Prop) (Qs : seq Prop) : Prop := if Qs is Q :: Qs then all_iff_and (P -> Q) (loop Q Qs) else P -> P0 in loop P0 Ps. Lemma all_iffLR P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m -> nth P0 (P0 :: Ps) n. Proof. move=> iffPs; have PsS n: nth P0 Ps n -> nth P0 Ps n.+1. elim: n P0 Ps iffPs => [|n IHn] P0 [|P [|Q Ps]] //= [iP0P] //; first by case. by rewrite nth_nil. by case=> iPQ iffPs; apply: IHn; split=> // /iP0P. have{PsS} lePs: {homo nth P0 Ps : m n / m <= n >-> (m -> n)}. by move=> m n /subnK<-; elim: {n}(n - m) => // n IHn /IHn; apply: PsS. move=> m n P_m; have{m P_m} hP0: P0. case: m P_m => //= m /(lePs m _ (leq_maxl m (size Ps))). by rewrite nth_default ?leq_maxr. case: n =>// n; apply: lePs 0 n (leq0n n) _. by case: Ps iffPs hP0 => // P Ps []. Qed. Lemma all_iffP P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m <-> nth P0 (P0 :: Ps) n. Proof. by move=> /all_iffLR-iffPs m n; split => /iffPs. Qed. End AllIff. Arguments all_iffLR {P0 Ps}. Arguments all_iffP {P0 Ps}. Coercion all_iffP : all_iff >-> Funclass. (* This means "the following are all equivalent: P0, ... Pn" *) Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" := (all_iff P0 (@cons Prop P1 (.. (@cons Prop Pn nil) ..))) : form_scope. Ltac tfae := do !apply: AllIffConj. Section FindSpec. Variable (T : Type) (a : {pred T}) (s : seq T). Variant find_spec : bool -> nat -> Type := | NotFound of ~~ has a s : find_spec false (size s) | Found (i : nat) of i < size s & (forall x0, a (nth x0 s i)) & (forall x0 j, j < i -> a (nth x0 s j) = false) : find_spec true i. Lemma findP : find_spec (has a s) (find a s). Proof. have [a_s|aNs] := boolP (has a s); last by rewrite hasNfind//; constructor. by constructor=> [|x0|x0]; rewrite -?has_find ?nth_find//; apply: before_find. Qed. End FindSpec. Arguments findP {T}. Section RotRcons. Variable T : Type. Implicit Types (x : T) (s : seq T). Lemma rot1_cons x s : rot 1 (x :: s) = rcons s x. Proof. by rewrite /rot /= take0 drop0 -cats1. Qed. Lemma rcons_inj s1 s2 x1 x2 : rcons s1 x1 = rcons s2 x2 :> seq T -> (s1, x1) = (s2, x2). Proof. by rewrite -!rot1_cons => /rot_inj[-> ->]. Qed. Lemma rcons_injl x : injective (rcons^~ x). Proof. by move=> s1 s2 /rcons_inj[]. Qed. Lemma rcons_injr s : injective (rcons s). Proof. by move=> x1 x2 /rcons_inj[]. Qed. End RotRcons. Arguments rcons_inj {T s1 x1 s2 x2} eq_rcons : rename. Arguments rcons_injl {T} x [s1 s2] eq_rcons : rename. Arguments rcons_injr {T} s [x1 x2] eq_rcons : rename. (* Equality and eqType for seq. *) Section EqSeq. Variables (n0 : nat) (T : eqType) (x0 : T). Local Notation nth := (nth x0). Implicit Types (x y z : T) (s : seq T). Fixpoint eqseq s1 s2 {struct s2} := match s1, s2 with | [::], [::] => true | x1 :: s1', x2 :: s2' => (x1 == x2) && eqseq s1' s2' | _, _ => false end. Lemma eqseqP : Equality.axiom eqseq. Proof. move; elim=> [|x1 s1 IHs] [|x2 s2]; do [by constructor | simpl]. have [<-|neqx] := x1 =P x2; last by right; case. by apply: (iffP (IHs s2)) => [<-|[]]. Qed. HB.instance Definition _ := hasDecEq.Build (seq T) eqseqP. Lemma eqseqE : eqseq = eq_op. Proof. by []. Qed. Lemma eqseq_cons x1 x2 s1 s2 : (x1 :: s1 == x2 :: s2) = (x1 == x2) && (s1 == s2). Proof. by []. Qed. Lemma eqseq_cat s1 s2 s3 s4 : size s1 = size s2 -> (s1 ++ s3 == s2 ++ s4) = (s1 == s2) && (s3 == s4). Proof. elim: s1 s2 => [|x1 s1 IHs] [|x2 s2] //= [sz12]. by rewrite !eqseq_cons -andbA IHs. Qed. Lemma eqseq_rcons s1 s2 x1 x2 : (rcons s1 x1 == rcons s2 x2) = (s1 == s2) && (x1 == x2). Proof. by rewrite -(can_eq revK) !rev_rcons eqseq_cons andbC (can_eq revK). Qed. Lemma size_eq0 s : (size s == 0) = (s == [::]). Proof. exact: (sameP nilP eqP). Qed. Lemma nilpE s : nilp s = (s == [::]). Proof. by case: s. Qed. Lemma has_filter a s : has a s = (filter a s != [::]). Proof. by rewrite -size_eq0 size_filter has_count lt0n. Qed. (* mem_seq and index. *) (* mem_seq defines a predType for seq. *) Fixpoint mem_seq (s : seq T) := if s is y :: s' then xpredU1 y (mem_seq s') else xpred0. Definition seq_eqclass := seq T. Identity Coercion seq_of_eqclass : seq_eqclass >-> seq. Coercion pred_of_seq (s : seq_eqclass) : {pred T} := mem_seq s. Canonical seq_predType := PredType (pred_of_seq : seq T -> pred T). (* The line below makes mem_seq a canonical instance of topred. *) Canonical mem_seq_predType := PredType mem_seq. Lemma in_cons y s x : (x \in y :: s) = (x == y) || (x \in s). Proof. by []. Qed. Lemma in_nil x : (x \in [::]) = false. Proof. by []. Qed. Lemma mem_seq1 x y : (x \in [:: y]) = (x == y). Proof. by rewrite in_cons orbF. Qed. (* to be repeated after the Section discharge. *) Let inE := (mem_seq1, in_cons, inE). Lemma forall_cons {P : T -> Prop} {a s} : {in a::s, forall x, P x} <-> P a /\ {in s, forall x, P x}. Proof. split=> [A|[A B]]; last by move => x /predU1P [-> //|]; apply: B. by split=> [|b Hb]; apply: A; rewrite !inE ?eqxx ?Hb ?orbT. Qed. Lemma exists_cons {P : T -> Prop} {a s} : (exists2 x, x \in a::s & P x) <-> P a \/ exists2 x, x \in s & P x. Proof. split=> [[x /predU1P[->|x_s] Px]|]; [by left| by right; exists x|]. by move=> [?|[x x_s ?]]; [exists a|exists x]; rewrite ?inE ?eqxx ?x_s ?orbT. Qed. Lemma mem_seq2 x y z : (x \in [:: y; z]) = xpred2 y z x. Proof. by rewrite !inE. Qed. Lemma mem_seq3 x y z t : (x \in [:: y; z; t]) = xpred3 y z t x. Proof. by rewrite !inE. Qed. Lemma mem_seq4 x y z t u : (x \in [:: y; z; t; u]) = xpred4 y z t u x. Proof. by rewrite !inE. Qed. Lemma mem_cat x s1 s2 : (x \in s1 ++ s2) = (x \in s1) || (x \in s2). Proof. by elim: s1 => //= y s1 IHs; rewrite !inE /= -orbA -IHs. Qed. Lemma mem_rcons s y : rcons s y =i y :: s. Proof. by move=> x; rewrite -cats1 /= mem_cat mem_seq1 orbC in_cons. Qed. Lemma mem_head x s : x \in x :: s. Proof. exact: predU1l. Qed. Lemma mem_last x s : last x s \in x :: s. Proof. by rewrite lastI mem_rcons mem_head. Qed. Lemma mem_behead s : {subset behead s <= s}. Proof. by case: s => // y s x; apply: predU1r. Qed. Lemma mem_belast s y : {subset belast y s <= y :: s}. Proof. by move=> x ys'x; rewrite lastI mem_rcons mem_behead. Qed. Lemma mem_nth s n : n < size s -> nth s n \in s. Proof. by elim: s n => // x s IHs [_|n sz_s]; rewrite ?mem_head // mem_behead ?IHs. Qed. Lemma mem_take s x : x \in take n0 s -> x \in s. Proof. by move=> s0x; rewrite -(cat_take_drop n0 s) mem_cat /= s0x. Qed. Lemma mem_drop s x : x \in drop n0 s -> x \in s. Proof. by move=> s0'x; rewrite -(cat_take_drop n0 s) mem_cat /= s0'x orbT. Qed. Lemma last_eq s z x y : x != y -> z != y -> (last x s == y) = (last z s == y). Proof. by move=> /negPf xz /negPf yz; case: s => [|t s]//; rewrite xz yz. Qed. Section Filters. Implicit Type a : pred T. Lemma hasP {a s} : reflect (exists2 x, x \in s & a x) (has a s). Proof. elim: s => [|y s IHs] /=; first by right; case. exact: equivP (orPP idP IHs) (iff_sym exists_cons). Qed. Lemma allP {a s} : reflect {in s, forall x, a x} (all a s). Proof. elim: s => [|/= y s IHs]; first by left. exact: equivP (andPP idP IHs) (iff_sym forall_cons). Qed. Lemma hasPn a s : reflect {in s, forall x, ~~ a x} (~~ has a s). Proof. by rewrite -all_predC; apply: allP. Qed. Lemma allPn a s : reflect (exists2 x, x \in s & ~~ a x) (~~ all a s). Proof. by rewrite -has_predC; apply: hasP. Qed. Lemma allss s : all [in s] s. Proof. exact/allP. Qed. Lemma mem_filter a x s : (x \in filter a s) = a x && (x \in s). Proof. rewrite andbC; elim: s => //= y s IHs. rewrite (fun_if (fun s' : seq T => x \in s')) !in_cons {}IHs. by case: eqP => [->|_]; case (a y); rewrite /= ?andbF. Qed. Variables (a : pred T) (s : seq T) (A : T -> Prop). Hypothesis aP : forall x, reflect (A x) (a x). Lemma hasPP : reflect (exists2 x, x \in s & A x) (has a s). Proof. by apply: (iffP hasP) => -[x ? /aP]; exists x. Qed. Lemma allPP : reflect {in s, forall x, A x} (all a s). Proof. by apply: (iffP allP) => a_s x /a_s/aP. Qed. End Filters. Section EqIn. Variables a1 a2 : pred T. Lemma eq_in_filter s : {in s, a1 =1 a2} -> filter a1 s = filter a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_find s : {in s, a1 =1 a2} -> find a1 s = find a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_count s : {in s, a1 =1 a2} -> count a1 s = count a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite -!size_filter eq_a12. Qed. Lemma eq_in_all s : {in s, a1 =1 a2} -> all a1 s = all a2 s. Proof. by move=> eq_a12; rewrite !all_count eq_in_count. Qed. Lemma eq_in_has s : {in s, a1 =1 a2} -> has a1 s = has a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite !has_filter eq_a12. Qed. End EqIn. Lemma eq_has_r s1 s2 : s1 =i s2 -> has^~ s1 =1 has^~ s2. Proof. by move=> Es a; apply/hasP/hasP=> -[x sx ax]; exists x; rewrite ?Es in sx *. Qed. Lemma eq_all_r s1 s2 : s1 =i s2 -> all^~ s1 =1 all^~ s2. Proof. by move=> Es a; apply/negb_inj; rewrite -!has_predC (eq_has_r Es). Qed. Lemma has_sym s1 s2 : has [in s1] s2 = has [in s2] s1. Proof. by apply/hasP/hasP=> -[x]; exists x. Qed. Lemma has_pred1 x s : has (pred1 x) s = (x \in s). Proof. by rewrite -(eq_has (mem_seq1^~ x)) (has_sym [:: x]) /= orbF. Qed. Lemma mem_rev s : rev s =i s. Proof. by move=> a; rewrite -!has_pred1 has_rev. Qed. (* Constant sequences, i.e., the image of nseq. *) Definition constant s := if s is x :: s' then all (pred1 x) s' else true. Lemma all_pred1P x s : reflect (s = nseq (size s) x) (all (pred1 x) s). Proof. elim: s => [|y s IHs] /=; first by left. case: eqP => [->{y} | ne_xy]; last by right=> [] [? _]; case ne_xy. by apply: (iffP IHs) => [<- //| []]. Qed. Lemma all_pred1_constant x s : all (pred1 x) s -> constant s. Proof. by case: s => //= y s /andP[/eqP->]. Qed. Lemma all_pred1_nseq x n : all (pred1 x) (nseq n x). Proof. by rewrite all_nseq /= eqxx orbT. Qed. Lemma mem_nseq n x y : (y \in nseq n x) = (0 < n) && (y == x). Proof. by rewrite -has_pred1 has_nseq eq_sym. Qed. Lemma nseqP n x y : reflect (y = x /\ n > 0) (y \in nseq n x). Proof. by rewrite mem_nseq andbC; apply: (iffP andP) => -[/eqP]. Qed. Lemma constant_nseq n x : constant (nseq n x). Proof. exact: all_pred1_constant (all_pred1_nseq x n). Qed. (* Uses x0 *) Lemma constantP s : reflect (exists x, s = nseq (size s) x) (constant s). Proof. apply: (iffP idP) => [| [x ->]]; last exact: constant_nseq. case: s => [|x s] /=; first by exists x0. by move/all_pred1P=> def_s; exists x; rewrite -def_s. Qed. (* Duplicate-freenes. *) Fixpoint uniq s := if s is x :: s' then (x \notin s') && uniq s' else true. Lemma cons_uniq x s : uniq (x :: s) = (x \notin s) && uniq s. Proof. by []. Qed. Lemma cat_uniq s1 s2 : uniq (s1 ++ s2) = [&& uniq s1, ~~ has [in s1] s2 & uniq s2]. Proof. elim: s1 => [|x s1 IHs]; first by rewrite /= has_pred0. by rewrite has_sym /= mem_cat !negb_or has_sym IHs -!andbA; do !bool_congr. Qed. Lemma uniq_catC s1 s2 : uniq (s1 ++ s2) = uniq (s2 ++ s1). Proof. by rewrite !cat_uniq has_sym andbCA andbA andbC. Qed. Lemma uniq_catCA s1 s2 s3 : uniq (s1 ++ s2 ++ s3) = uniq (s2 ++ s1 ++ s3). Proof. by rewrite !catA -!(uniq_catC s3) !(cat_uniq s3) uniq_catC !has_cat orbC. Qed. Lemma rcons_uniq s x : uniq (rcons s x) = (x \notin s) && uniq s. Proof. by rewrite -cats1 uniq_catC. Qed. Lemma filter_uniq s a : uniq s -> uniq (filter a s). Proof. elim: s => //= x s IHs /andP[s'x]; case: ifP => //= a_x /IHs->. by rewrite mem_filter a_x s'x. Qed. Lemma rot_uniq s : uniq (rot n0 s) = uniq s. Proof. by rewrite /rot uniq_catC cat_take_drop. Qed. Lemma rev_uniq s : uniq (rev s) = uniq s. Proof. elim: s => // x s IHs. by rewrite rev_cons -cats1 cat_uniq /= andbT andbC mem_rev orbF IHs. Qed. Lemma count_memPn x s : reflect (count_mem x s = 0) (x \notin s). Proof. by rewrite -has_pred1 has_count -eqn0Ngt; apply: eqP. Qed. Lemma count_uniq_mem s x : uniq s -> count_mem x s = (x \in s). Proof. elim: s => //= y s IHs /andP[/negbTE s'y /IHs-> {IHs}]. by rewrite in_cons; case: (eqVneq y x) => // <-; rewrite s'y. Qed. Lemma leq_uniq_countP x s1 s2 : uniq s1 -> reflect (x \in s1 -> x \in s2) (count_mem x s1 <= count_mem x s2). Proof. move/count_uniq_mem->; case: (boolP (_ \in _)) => //= _; last by constructor. by rewrite -has_pred1 has_count; apply: (iffP idP) => //; apply. Qed. Lemma leq_uniq_count s1 s2 : uniq s1 -> {subset s1 <= s2} -> (forall x, count_mem x s1 <= count_mem x s2). Proof. by move=> s1_uniq s1_s2 x; apply/leq_uniq_countP/s1_s2. Qed. Lemma filter_pred1_uniq s x : uniq s -> x \in s -> filter (pred1 x) s = [:: x]. Proof. move=> uniq_s s_x; rewrite (all_pred1P _ _ (filter_all _ _)). by rewrite size_filter count_uniq_mem ?s_x. Qed. (* Removing duplicates *) Fixpoint undup s := if s is x :: s' then if x \in s' then undup s' else x :: undup s' else [::]. Lemma size_undup s : size (undup s) <= size s. Proof. by elim: s => //= x s IHs; case: (x \in s) => //=; apply: ltnW. Qed. Lemma mem_undup s : undup s =i s. Proof. move=> x; elim: s => //= y s IHs. by case s_y: (y \in s); rewrite !inE IHs //; case: eqP => [->|]. Qed. Lemma undup_uniq s : uniq (undup s). Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= mem_undup s_x. Qed. Lemma undup_id s : uniq s -> undup s = s. Proof. by elim: s => //= x s IHs /andP[/negbTE-> /IHs->]. Qed. Lemma ltn_size_undup s : (size (undup s) < size s) = ~~ uniq s. Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= ltnS size_undup. Qed. Lemma filter_undup p s : filter p (undup s) = undup (filter p s). Proof. elim: s => //= x s IHs; rewrite (fun_if undup) [_ = _]fun_if /= mem_filter /=. by rewrite (fun_if (filter p)) /= IHs; case: ifP => -> //=; apply: if_same. Qed. Lemma undup_nil s : undup s = [::] -> s = [::]. Proof. by case: s => //= x s; rewrite -mem_undup; case: ifP; case: undup. Qed. Lemma undup_cat s t : undup (s ++ t) = [seq x <- undup s | x \notin t] ++ undup t. Proof. by elim: s => //= x s ->; rewrite mem_cat; do 2 case: in_mem => //=. Qed. Lemma undup_rcons s x : undup (rcons s x) = rcons [seq y <- undup s | y != x] x. Proof. by rewrite -!cats1 undup_cat; congr cat; apply: eq_filter => y; rewrite inE. Qed. Lemma count_undup s p : count p (undup s) <= count p s. Proof. by rewrite -!size_filter filter_undup size_undup. Qed. Lemma has_undup p s : has p (undup s) = has p s. Proof. by apply: eq_has_r => x; rewrite mem_undup. Qed. Lemma all_undup p s : all p (undup s) = all p s. Proof. by apply: eq_all_r => x; rewrite mem_undup. Qed. (* Lookup *) Definition index x := find (pred1 x). Lemma index_size x s : index x s <= size s. Proof. by rewrite /index find_size. Qed. Lemma index_mem x s : (index x s < size s) = (x \in s). Proof. by rewrite -has_pred1 has_find. Qed. Lemma memNindex x s : x \notin s -> index x s = size s. Proof. by rewrite -has_pred1 => /hasNfind. Qed. Lemma nth_index x s : x \in s -> nth s (index x s) = x. Proof. by rewrite -has_pred1 => /(nth_find x0)/eqP. Qed. Lemma index_inj s : {in s &, injective (index ^~ s)}. Proof. by move=> x y x_s y_s eidx; rewrite -(nth_index x_s) eidx nth_index. Qed. Lemma index_cat x s1 s2 : index x (s1 ++ s2) = if x \in s1 then index x s1 else size s1 + index x s2. Proof. by rewrite /index find_cat has_pred1. Qed. Lemma index_ltn x s i : x \in take i s -> index x s < i. Proof. by rewrite -has_pred1; apply: find_ltn. Qed. Lemma in_take x s i : x \in s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take. Qed. Lemma in_take_leq x s i : i <= size s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take_leq. Qed. Lemma index_nth i s : i < size s -> index (nth s i) s <= i. Proof. move=> lti; rewrite -ltnS index_ltn// -(@nth_take i.+1)// mem_nth // size_take. by case: ifP. Qed. Lemma nthK s: uniq s -> {in gtn (size s), cancel (nth s) (index^~ s)}. Proof. elim: s => //= x s IHs /andP[s'x Us] i; rewrite inE ltnS eq_sym -if_neg. by case: i => /= [_|i lt_i_s]; rewrite ?eqxx ?IHs ?(memPn s'x) ?mem_nth. Qed. Lemma index_uniq i s : i < size s -> uniq s -> index (nth s i) s = i. Proof. by move/nthK. Qed. Lemma index_head x s : index x (x :: s) = 0. Proof. by rewrite /= eqxx. Qed. Lemma index_last x s : uniq (x :: s) -> index (last x s) (x :: s) = size s. Proof. rewrite lastI rcons_uniq -cats1 index_cat size_belast. by case: ifP => //=; rewrite eqxx addn0. Qed. Lemma nth_uniq s i j : i < size s -> j < size s -> uniq s -> (nth s i == nth s j) = (i == j). Proof. by move=> lti ltj /nthK/can_in_eq->. Qed. Lemma uniqPn s : reflect (exists i j, [/\ i < j, j < size s & nth s i = nth s j]) (~~ uniq s). Proof. apply: (iffP idP) => [|[i [j [ltij ltjs]]]]; last first. by apply: contra_eqN => Us; rewrite nth_uniq ?ltn_eqF // (ltn_trans ltij). elim: s => // x s IHs /nandP[/negbNE | /IHs[i [j]]]; last by exists i.+1, j.+1. by exists 0, (index x s).+1; rewrite !ltnS index_mem /= nth_index. Qed. Lemma uniqP s : reflect {in gtn (size s) &, injective (nth s)} (uniq s). Proof. apply: (iffP idP) => [/nthK/can_in_inj// | nth_inj]. apply/uniqPn => -[i [j [ltij ltjs /nth_inj/eqP/idPn]]]. by rewrite !inE (ltn_trans ltij ltjs) ltn_eqF //=; case. Qed. Lemma mem_rot s : rot n0 s =i s. Proof. by move=> x; rewrite -[s in RHS](cat_take_drop n0) !mem_cat /= orbC. Qed. Lemma eqseq_rot s1 s2 : (rot n0 s1 == rot n0 s2) = (s1 == s2). Proof. exact/inj_eq/rot_inj. Qed. Lemma drop_index s (n := index x0 s) : x0 \in s -> drop n s = x0 :: drop n.+1 s. Proof. by move=> xs; rewrite (drop_nth x0) ?index_mem ?nth_index. Qed. (* lemmas about the pivot pattern [_ ++ _ :: _] *) Lemma index_pivot x s1 s2 (s := s1 ++ x :: s2) : x \notin s1 -> index x s = size s1. Proof. by rewrite index_cat/= eqxx addn0; case: ifPn. Qed. Lemma take_pivot x s2 s1 (s := s1 ++ x :: s2) : x \notin s1 -> take (index x s) s = s1. Proof. by move=> /index_pivot->; rewrite take_size_cat. Qed. Lemma rev_pivot x s1 s2 : rev (s1 ++ x :: s2) = rev s2 ++ x :: rev s1. Proof. by rewrite rev_cat rev_cons cat_rcons. Qed. Lemma eqseq_pivot2l x s1 s2 s3 s4 : x \notin s1 -> x \notin s3 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs3; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. suff S : size s1 = size s3 by rewrite eqseq_cat// eqseq_cons eqxx in E. by rewrite -(index_pivot s2 xNs1) (eqP E) index_pivot. Qed. Lemma eqseq_pivot2r x s1 s2 s3 s4 : x \notin s2 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs2 xNs4; rewrite -(can_eq revK) !rev_pivot. by rewrite eqseq_pivot2l ?mem_rev // !(can_eq revK) andbC. Qed. Lemma eqseq_pivotl x s1 s2 s3 s4 : x \notin s1 -> x \notin s2 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs2; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. rewrite -(@eqseq_pivot2l x)//; have /eqP/(congr1 (count_mem x)) := E. rewrite !count_cat/= eqxx !addnS (count_memPn _ _ xNs1) (count_memPn _ _ xNs2). by move=> -[/esym/eqP]; rewrite addn_eq0 => /andP[/eqP/count_memPn]. Qed. Lemma eqseq_pivotr x s1 s2 s3 s4 : x \notin s3 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> *; rewrite eq_sym eqseq_pivotl//; case: eqVneq => /=. Qed. Lemma uniq_eqseq_pivotl x s1 s2 s3 s4 : uniq (s1 ++ x :: s2) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by rewrite uniq_catC/= mem_cat => /andP[/norP[? ?] _]; rewrite eqseq_pivotl. Qed. Lemma uniq_eqseq_pivotr x s1 s2 s3 s4 : uniq (s3 ++ x :: s4) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> ?; rewrite eq_sym uniq_eqseq_pivotl//; case: eqVneq => /=. Qed. End EqSeq. Arguments eqseq : simpl nomatch. Notation "'has_ view" := (hasPP _ (fun _ => view)) (at level 4, right associativity, format "''has_' view"). Notation "'all_ view" := (allPP _ (fun _ => view)) (at level 4, right associativity, format "''all_' view"). Section RotIndex. Variables (T : eqType). Implicit Types x y z : T. Lemma rot_index s x (i := index x s) : x \in s -> rot i s = x :: (drop i.+1 s ++ take i s). Proof. by move=> x_s; rewrite /rot drop_index. Qed. Variant rot_to_spec s x := RotToSpec i s' of rot i s = x :: s'. Lemma rot_to s x : x \in s -> rot_to_spec s x. Proof. by move=> /rot_index /RotToSpec. Qed. End RotIndex. Definition inE := (mem_seq1, in_cons, inE). Prenex Implicits mem_seq1 constant uniq undup index. Arguments eqseq {T} !_ !_. Arguments pred_of_seq {T} s x /. Arguments eqseqP {T x y}. Arguments hasP {T a s}. Arguments hasPn {T a s}. Arguments allP {T a s}. Arguments allPn {T a s}. Arguments nseqP {T n x y}. Arguments count_memPn {T x s}. Arguments uniqPn {T} x0 {s}. Arguments uniqP {T} x0 {s}. Arguments forall_cons {T P a s}. Arguments exists_cons {T P a s}. (* Since both `all [in s] s`, `all (mem s) s`, and `all (pred_of_seq s) s` *) (* may appear in goals, the following hint has to be declared using the *) (* `Hint Extern` command. Additionally, `mem` and `pred_of_seq` in the above *) (* terms do not reduce to each other; thus, stating `allss` in the form of *) (* one of them makes `apply: allss` fail for the other case. Since both `mem` *) (* and `pred_of_seq` reduce to `mem_seq`, the following explicit type *) (* annotation for `allss` makes it work for both cases. *) #[export] Hint Extern 0 (is_true (all _ _)) => apply: (allss : forall T s, all (mem_seq s) s) : core. Section NthTheory. Lemma nthP (T : eqType) (s : seq T) x x0 : reflect (exists2 i, i < size s & nth x0 s i = x) (x \in s). Proof. apply: (iffP idP) => [|[n Hn <-]]; last exact: mem_nth. by exists (index x s); [rewrite index_mem | apply nth_index]. Qed. Variable T : Type. Implicit Types (a : pred T) (x : T). Lemma has_nthP a s x0 : reflect (exists2 i, i < size s & a (nth x0 s i)) (has a s). Proof. elim: s => [|x s IHs] /=; first by right; case. case nax: (a x); first by left; exists 0. by apply: (iffP IHs) => [[i]|[[|i]]]; [exists i.+1 | rewrite nax | exists i]. Qed. Lemma all_nthP a s x0 : reflect (forall i, i < size s -> a (nth x0 s i)) (all a s). Proof. rewrite -(eq_all (fun x => negbK (a x))) all_predC. case: (has_nthP _ _ x0) => [na_s | a_s]; [right=> a_s | left=> i lti]. by case: na_s => i lti; rewrite a_s. by apply/idPn=> na_si; case: a_s; exists i. Qed. Lemma set_nthE s x0 n x : set_nth x0 s n x = if n < size s then take n s ++ x :: drop n.+1 s else s ++ ncons (n - size s) x0 [:: x]. Proof. elim: s n => [|a s IH] n /=; first by rewrite subn0 set_nth_nil. case: n => [|n]; first by rewrite drop0. by rewrite ltnS /=; case: ltnP (IH n) => _ ->. Qed. Lemma count_set_nth a s x0 n x : count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n) * (n < size s) + (a x0) * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. rewrite -cat_nseq !count_cat count_nseq /=. by rewrite muln0 addn0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in count a s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !count_cat/= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma count_set_nth_ltn a s x0 n x : n < size s -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> nlts; rewrite count_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma count_set_nthF a s x0 n x : ~~ a x0 -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> /negbTE ax0; rewrite count_set_nth ax0 mul0n addn0. case: ltnP => [_|nges]; first by rewrite muln1. by rewrite nth_default// ax0 subn0. Qed. End NthTheory. Lemma set_nth_default T s (y0 x0 : T) n : n < size s -> nth x0 s n = nth y0 s n. Proof. by elim: s n => [|y s' IHs] [|n] //= /IHs. Qed. Lemma headI T s (x : T) : rcons s x = head x s :: behead (rcons s x). Proof. by case: s. Qed. Arguments nthP {T s x}. Arguments has_nthP {T a s}. Arguments all_nthP {T a s}. Definition bitseq := seq bool. #[hnf] HB.instance Definition _ := Equality.on bitseq. Canonical bitseq_predType := Eval hnf in [predType of bitseq]. (* Generalizations of splitP (from path.v): split_find_nth and split_find *) Section FindNth. Variables (T : Type). Implicit Types (x : T) (p : pred T) (s : seq T). Variant split_find_nth_spec p : seq T -> seq T -> seq T -> T -> Type := FindNth x s1 s2 of p x & ~~ has p s1 : split_find_nth_spec p (rcons s1 x ++ s2) s1 s2 x. Lemma split_find_nth x0 p s (i := find p s) : has p s -> split_find_nth_spec p s (take i s) (drop i.+1 s) (nth x0 s i). Proof. move=> p_s; rewrite -[X in split_find_nth_spec _ X](cat_take_drop i s). rewrite (drop_nth x0 _) -?has_find// -cat_rcons. by constructor; [apply: nth_find | rewrite has_take -?leqNgt]. Qed. Variant split_find_spec p : seq T -> seq T -> seq T -> Type := FindSplit x s1 s2 of p x & ~~ has p s1 : split_find_spec p (rcons s1 x ++ s2) s1 s2. Lemma split_find p s (i := find p s) : has p s -> split_find_spec p s (take i s) (drop i.+1 s). Proof. by case: s => // x ? in i * => ?; case: split_find_nth => //; constructor. Qed. Lemma nth_rcons_cat_find x0 p s1 s2 x (s := rcons s1 x ++ s2) : p x -> ~~ has p s1 -> nth x0 s (find p s) = x. Proof. move=> pz pNs1; rewrite /s cat_rcons find_cat (negPf pNs1). by rewrite nth_cat/= pz addn0 subnn ltnn. Qed. End FindNth. (* Incrementing the ith nat in a seq nat, padding with 0's if needed. This *) (* allows us to use nat seqs as bags of nats. *) Fixpoint incr_nth v i {struct i} := if v is n :: v' then if i is i'.+1 then n :: incr_nth v' i' else n.+1 :: v' else ncons i 0 [:: 1]. Arguments incr_nth : simpl nomatch. Lemma nth_incr_nth v i j : nth 0 (incr_nth v i) j = (i == j) + nth 0 v j. Proof. elim: v i j => [|n v IHv] [|i] [|j] //=; rewrite ?eqSS ?addn0 //; try by case j. elim: i j => [|i IHv] [|j] //=; rewrite ?eqSS //; by case j. Qed. Lemma size_incr_nth v i : size (incr_nth v i) = if i < size v then size v else i.+1. Proof. elim: v i => [|n v IHv] [|i] //=; first by rewrite size_ncons /= addn1. by rewrite IHv; apply: fun_if. Qed. Lemma incr_nth_inj v : injective (incr_nth v). Proof. move=> i j /(congr1 (nth 0 ^~ i)); apply: contra_eq => neq_ij. by rewrite !nth_incr_nth eqn_add2r eqxx /nat_of_bool ifN_eqC. Qed. Lemma incr_nthC v i j : incr_nth (incr_nth v i) j = incr_nth (incr_nth v j) i. Proof. apply: (@eq_from_nth _ 0) => [|k _]; last by rewrite !nth_incr_nth addnCA. by do !rewrite size_incr_nth leqNgt if_neg -/(maxn _ _); apply: maxnAC. Qed. (* Equality up to permutation *) Section PermSeq. Variable T : eqType. Implicit Type s : seq T. Definition perm_eq s1 s2 := all [pred x | count_mem x s1 == count_mem x s2] (s1 ++ s2). Lemma permP s1 s2 : reflect (count^~ s1 =1 count^~ s2) (perm_eq s1 s2). Proof. apply: (iffP allP) => /= [eq_cnt1 a | eq_cnt x _]; last exact/eqP. have [n le_an] := ubnP (count a (s1 ++ s2)); elim: n => // n IHn in a le_an *. have [/eqP|] := posnP (count a (s1 ++ s2)). by rewrite count_cat addn_eq0; do 2!case: eqP => // ->. rewrite -has_count => /hasP[x s12x a_x]; pose a' := predD1 a x. have cnt_a' s: count a s = count_mem x s + count a' s. rewrite -count_predUI -[LHS]addn0 -(count_pred0 s). by congr (_ + _); apply: eq_count => y /=; case: eqP => // ->. rewrite !cnt_a' (eqnP (eq_cnt1 _ s12x)) (IHn a') // -ltnS. apply: leq_trans le_an. by rewrite ltnS cnt_a' -add1n leq_add2r -has_count has_pred1. Qed. Lemma perm_refl s : perm_eq s s. Proof. exact/permP. Qed. Hint Resolve perm_refl : core. Lemma perm_sym : symmetric perm_eq. Proof. by move=> s1 s2; apply/permP/permP=> eq_s12 a. Qed. Lemma perm_trans : transitive perm_eq. Proof. by move=> s2 s1 s3 /permP-eq12 /permP/(ftrans eq12)/permP. Qed. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Lemma permEl s1 s2 : perm_eql s1 s2 -> perm_eq s1 s2. Proof. by move->. Qed. Lemma permPl s1 s2 : reflect (perm_eql s1 s2) (perm_eq s1 s2). Proof. apply: (iffP idP) => [eq12 s3 | -> //]; apply/idP/idP; last exact: perm_trans. by rewrite -!(perm_sym s3) => /perm_trans; apply. Qed. Lemma permPr s1 s2 : reflect (perm_eqr s1 s2) (perm_eq s1 s2). Proof. by apply/(iffP idP) => [/permPl eq12 s3| <- //]; rewrite !(perm_sym s3) eq12. Qed. Lemma perm_catC s1 s2 : perm_eql (s1 ++ s2) (s2 ++ s1). Proof. by apply/permPl/permP=> a; rewrite !count_cat addnC. Qed. Lemma perm_cat2l s1 s2 s3 : perm_eq (s1 ++ s2) (s1 ++ s3) = perm_eq s2 s3. Proof. apply/permP/permP=> eq23 a; apply/eqP; by move/(_ a)/eqP: eq23; rewrite !count_cat eqn_add2l. Qed. Lemma perm_catl s t1 t2 : perm_eq t1 t2 -> perm_eql (s ++ t1) (s ++ t2). Proof. by move=> eq_t12; apply/permPl; rewrite perm_cat2l. Qed. Lemma perm_cons x s1 s2 : perm_eq (x :: s1) (x :: s2) = perm_eq s1 s2. Proof. exact: (perm_cat2l [::x]). Qed. Lemma perm_cat2r s1 s2 s3 : perm_eq (s2 ++ s1) (s3 ++ s1) = perm_eq s2 s3. Proof. by do 2!rewrite perm_sym perm_catC; apply: perm_cat2l. Qed. Lemma perm_catr s1 s2 t : perm_eq s1 s2 -> perm_eql (s1 ++ t) (s2 ++ t). Proof. by move=> eq_s12; apply/permPl; rewrite perm_cat2r. Qed. Lemma perm_cat s1 s2 t1 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq (s1 ++ t1) (s2 ++ t2). Proof. by move=> /perm_catr-> /perm_catl->. Qed. Lemma perm_catAC s1 s2 s3 : perm_eql ((s1 ++ s2) ++ s3) ((s1 ++ s3) ++ s2). Proof. by apply/permPl; rewrite -!catA perm_cat2l perm_catC. Qed. Lemma perm_catCA s1 s2 s3 : perm_eql (s1 ++ s2 ++ s3) (s2 ++ s1 ++ s3). Proof. by apply/permPl; rewrite !catA perm_cat2r perm_catC. Qed. Lemma perm_catACA s1 s2 s3 s4 : perm_eql ((s1 ++ s2) ++ (s3 ++ s4)) ((s1 ++ s3) ++ (s2 ++ s4)). Proof. by apply/permPl; rewrite perm_catAC !catA perm_catAC. Qed. Lemma perm_rcons x s : perm_eql (rcons s x) (x :: s). Proof. by move=> /= s2; rewrite -cats1 perm_catC. Qed. Lemma perm_rot n s : perm_eql (rot n s) s. Proof. by move=> /= s2; rewrite perm_catC cat_take_drop. Qed. Lemma perm_rotr n s : perm_eql (rotr n s) s. Proof. exact: perm_rot. Qed. Lemma perm_rev s : perm_eql (rev s) s. Proof. by apply/permPl/permP=> i; rewrite count_rev. Qed. Lemma perm_filter s1 s2 a : perm_eq s1 s2 -> perm_eq (filter a s1) (filter a s2). Proof. by move/permP=> s12_count; apply/permP=> Q; rewrite !count_filter. Qed. Lemma perm_filterC a s : perm_eql (filter a s ++ filter (predC a) s) s. Proof. apply/permPl; elim: s => //= x s IHs. by case: (a x); last rewrite /= -cat1s perm_catCA; rewrite perm_cons. Qed. Lemma perm_size s1 s2 : perm_eq s1 s2 -> size s1 = size s2. Proof. by move/permP=> eq12; rewrite -!count_predT eq12. Qed. Lemma perm_mem s1 s2 : perm_eq s1 s2 -> s1 =i s2. Proof. by move/permP=> eq12 x; rewrite -!has_pred1 !has_count eq12. Qed. Lemma perm_nilP s : reflect (s = [::]) (perm_eq s [::]). Proof. by apply: (iffP idP) => [/perm_size/eqP/nilP | ->]. Qed. Lemma perm_consP x s t : reflect (exists i u, rot i t = x :: u /\ perm_eq u s) (perm_eq t (x :: s)). Proof. apply: (iffP idP) => [eq_txs | [i [u [Dt eq_us]]]]. have /rot_to[i u Dt]: x \in t by rewrite (perm_mem eq_txs) mem_head. by exists i, u; rewrite -(perm_cons x) -Dt perm_rot. by rewrite -(perm_rot i) Dt perm_cons. Qed. Lemma perm_has s1 s2 a : perm_eq s1 s2 -> has a s1 = has a s2. Proof. by move/perm_mem/eq_has_r. Qed. Lemma perm_all s1 s2 a : perm_eq s1 s2 -> all a s1 = all a s2. Proof. by move/perm_mem/eq_all_r. Qed. Lemma perm_small_eq s1 s2 : size s2 <= 1 -> perm_eq s1 s2 -> s1 = s2. Proof. move=> s2_le1 eqs12; move/perm_size: eqs12 s2_le1 (perm_mem eqs12). by case: s2 s1 => [|x []] // [|y []] // _ _ /(_ x) /[!(inE, eqxx)] /eqP->. Qed. Lemma uniq_leq_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s1 <= size s2. Proof. elim: s1 s2 => //= x s1 IHs s2 /andP[not_s1x Us1] /forall_cons[s2x ss12]. have [i s3 def_s2] := rot_to s2x; rewrite -(size_rot i s2) def_s2. apply: IHs => // y s1y; have:= ss12 y s1y. by rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). Qed. Lemma leq_size_uniq s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> uniq s2. Proof. elim: s1 s2 => [[] | x s1 IHs s2] // Us1x; have /andP[not_s1x Us1] := Us1x. case/forall_cons => /rot_to[i s3 def_s2] ss12 le_s21. rewrite -(rot_uniq i) -(size_rot i) def_s2 /= in le_s21 *. have ss13 y (s1y : y \in s1): y \in s3. by have:= ss12 y s1y; rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). rewrite IHs // andbT; apply: contraL _ le_s21 => s3x; rewrite -leqNgt. by apply/(uniq_leq_size Us1x)/allP; rewrite /= s3x; apply/allP. Qed. Lemma uniq_size_uniq s1 s2 : uniq s1 -> s1 =i s2 -> uniq s2 = (size s2 == size s1). Proof. move=> Us1 eqs12; apply/idP/idP=> [Us2 | /eqP eq_sz12]. by rewrite eqn_leq !uniq_leq_size // => y; rewrite eqs12. by apply: (leq_size_uniq Us1) => [y|]; rewrite (eqs12, eq_sz12). Qed. Lemma uniq_min_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> (size s1 = size s2) * (s1 =i s2). Proof. move=> Us1 ss12 le_s21; have Us2: uniq s2 := leq_size_uniq Us1 ss12 le_s21. suffices: s1 =i s2 by split; first by apply/eqP; rewrite -uniq_size_uniq. move=> x; apply/idP/idP=> [/ss12// | s2x]; apply: contraLR le_s21 => not_s1x. rewrite -ltnNge (@uniq_leq_size (x :: s1)) /= ?not_s1x //. by apply/allP; rewrite /= s2x; apply/allP. Qed. Lemma eq_uniq s1 s2 : size s1 = size s2 -> s1 =i s2 -> uniq s1 = uniq s2. Proof. move=> eq_sz12 eq_s12. by apply/idP/idP=> Us; rewrite (uniq_size_uniq Us) ?eq_sz12 ?eqxx. Qed. Lemma perm_uniq s1 s2 : perm_eq s1 s2 -> uniq s1 = uniq s2. Proof. by move=> eq_s12; apply/eq_uniq; [apply/perm_size | apply/perm_mem]. Qed. Lemma uniq_perm s1 s2 : uniq s1 -> uniq s2 -> s1 =i s2 -> perm_eq s1 s2. Proof. move=> Us1 Us2 eq12; apply/allP=> x _; apply/eqP. by rewrite !count_uniq_mem ?eq12. Qed. Lemma perm_undup s1 s2 : s1 =i s2 -> perm_eq (undup s1) (undup s2). Proof. by move=> Es12; rewrite uniq_perm ?undup_uniq // => s; rewrite !mem_undup. Qed. Lemma count_mem_uniq s : (forall x, count_mem x s = (x \in s)) -> uniq s. Proof. move=> count1_s; have Uus := undup_uniq s. suffices: perm_eq s (undup s) by move/perm_uniq->. by apply/allP=> x _; apply/eqP; rewrite (count_uniq_mem x Uus) mem_undup. Qed. Lemma eq_count_undup a s1 s2 : {in a, s1 =i s2} -> count a (undup s1) = count a (undup s2). Proof. move=> s1_eq_s2; rewrite -!size_filter !filter_undup. apply/perm_size/perm_undup => x. by rewrite !mem_filter; case: (boolP (a x)) => //= /s1_eq_s2. Qed. Lemma catCA_perm_ind P : (forall s1 s2 s3, P (s1 ++ s2 ++ s3) -> P (s2 ++ s1 ++ s3)) -> (forall s1 s2, perm_eq s1 s2 -> P s1 -> P s2). Proof. move=> PcatCA s1 s2 eq_s12; rewrite -[s1]cats0 -[s2]cats0. elim: s2 nil => [|x s2 IHs] s3 in s1 eq_s12 *. by case: s1 {eq_s12}(perm_size eq_s12). have /rot_to[i s' def_s1]: x \in s1 by rewrite (perm_mem eq_s12) mem_head. rewrite -(cat_take_drop i s1) -catA => /PcatCA. rewrite catA -/(rot i s1) def_s1 /= -cat1s => /PcatCA/IHs/PcatCA; apply. by rewrite -(perm_cons x) -def_s1 perm_rot. Qed. Lemma catCA_perm_subst R F : (forall s1 s2 s3, F (s1 ++ s2 ++ s3) = F (s2 ++ s1 ++ s3) :> R) -> (forall s1 s2, perm_eq s1 s2 -> F s1 = F s2). Proof. move=> FcatCA s1 s2 /catCA_perm_ind => ind_s12. by apply: (ind_s12 (eq _ \o F)) => //= *; rewrite FcatCA. Qed. End PermSeq. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Arguments permP {T s1 s2}. Arguments permPl {T s1 s2}. Arguments permPr {T s1 s2}. Prenex Implicits perm_eq. #[global] Hint Resolve perm_refl : core. Section RotrLemmas. Variables (n0 : nat) (T : Type) (T' : eqType). Implicit Types (x : T) (s : seq T). Lemma size_rotr s : size (rotr n0 s) = size s. Proof. by rewrite size_rot. Qed. Lemma mem_rotr (s : seq T') : rotr n0 s =i s. Proof. by move=> x; rewrite mem_rot. Qed. Lemma rotr_size_cat s1 s2 : rotr (size s2) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rotr size_cat addnK rot_size_cat. Qed. Lemma rotr1_rcons x s : rotr 1 (rcons s x) = x :: s. Proof. by rewrite -rot1_cons rotK. Qed. Lemma has_rotr a s : has a (rotr n0 s) = has a s. Proof. by rewrite has_rot. Qed. Lemma rotr_uniq (s : seq T') : uniq (rotr n0 s) = uniq s. Proof. by rewrite rot_uniq. Qed. Lemma rotrK : cancel (@rotr T n0) (rot n0). Proof. move=> s; have [lt_n0s | ge_n0s] := ltnP n0 (size s). by rewrite -{1}(subKn (ltnW lt_n0s)) -{1}[size s]size_rotr; apply: rotK. by rewrite -[in RHS](rot_oversize ge_n0s) /rotr (eqnP ge_n0s) rot0. Qed. Lemma rotr_inj : injective (@rotr T n0). Proof. exact (can_inj rotrK). Qed. Lemma take_rev s : take n0 (rev s) = rev (drop (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat take_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?subnn take0 cats0. Qed. Lemma rev_take s : rev (take n0 s) = drop (size s - n0) (rev s). Proof. by rewrite -[s in take _ s]revK take_rev revK size_rev. Qed. Lemma drop_rev s : drop n0 (rev s) = rev (take (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat drop_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?take0 // subnn drop0. Qed. Lemma rev_drop s : rev (drop n0 s) = take (size s - n0) (rev s). Proof. by rewrite -[s in drop _ s]revK drop_rev revK size_rev. Qed. Lemma rev_rotr s : rev (rotr n0 s) = rot n0 (rev s). Proof. by rewrite rev_cat -take_rev -drop_rev. Qed. Lemma rev_rot s : rev (rot n0 s) = rotr n0 (rev s). Proof. by apply: canLR revK _; rewrite rev_rotr revK. Qed. End RotrLemmas. Arguments rotrK n0 {T} s : rename. Arguments rotr_inj {n0 T} [s1 s2] eq_rotr_s12 : rename. Section RotCompLemmas. Variable T : Type. Implicit Type s : seq T. Lemma rotD m n s : m + n <= size s -> rot (m + n) s = rot m (rot n s). Proof. move=> sz_s; rewrite [LHS]/rot -[take _ s](cat_take_drop n). rewrite 5!(catA, =^~ rot_size_cat) !cat_take_drop. by rewrite size_drop !size_takel ?leq_addl ?addnK. Qed. Lemma rotS n s : n < size s -> rot n.+1 s = rot 1 (rot n s). Proof. exact: (@rotD 1). Qed. Lemma rot_add_mod m n s : n <= size s -> m <= size s -> rot m (rot n s) = rot (if m + n <= size s then m + n else m + n - size s) s. Proof. move=> Hn Hm; case: leqP => [/rotD // | /ltnW Hmn]; symmetry. by rewrite -{2}(rotK n s) /rotr -rotD size_rot addnBA ?subnK ?addnK. Qed. Lemma rot_minn n s : rot n s = rot (minn n (size s)) s. Proof. by case: (leqP n (size s)) => // /leqW ?; rewrite rot_size rot_oversize. Qed. Definition rot_add s n m (k := size s) (p := minn m k + minn n k) := locked (if p <= k then p else p - k). Lemma leq_rot_add n m s : rot_add s n m <= size s. Proof. by unlock rot_add; case: ifP; rewrite // leq_subLR leq_add // geq_minr. Qed. Lemma rot_addC n m s : rot_add s n m = rot_add s m n. Proof. by unlock rot_add; rewrite ![minn n _ + _]addnC. Qed. Lemma rot_rot_add n m s : rot m (rot n s) = rot (rot_add s n m) s. Proof. unlock rot_add. by rewrite (rot_minn n) (rot_minn m) rot_add_mod ?size_rot ?geq_minr. Qed. Lemma rot_rot m n s : rot m (rot n s) = rot n (rot m s). Proof. by rewrite rot_rot_add rot_addC -rot_rot_add. Qed. Lemma rot_rotr m n s : rot m (rotr n s) = rotr n (rot m s). Proof. by rewrite [RHS]/rotr size_rot rot_rot. Qed. Lemma rotr_rotr m n s : rotr m (rotr n s) = rotr n (rotr m s). Proof. by rewrite /rotr !size_rot rot_rot. Qed. End RotCompLemmas. Section Mask. Variables (n0 : nat) (T : Type). Implicit Types (m : bitseq) (s : seq T). Fixpoint mask m s {struct m} := match m, s with | b :: m', x :: s' => if b then x :: mask m' s' else mask m' s' | _, _ => [::] end. Lemma mask_false s n : mask (nseq n false) s = [::]. Proof. by elim: s n => [|x s IHs] [|n] /=. Qed. Lemma mask_true s n : size s <= n -> mask (nseq n true) s = s. Proof. by elim: s n => [|x s IHs] [|n] //= Hn; congr (_ :: _); apply: IHs. Qed. Lemma mask0 m : mask m [::] = [::]. Proof. by case: m. Qed. Lemma mask0s s : mask [::] s = [::]. Proof. by []. Qed. Lemma mask1 b x : mask [:: b] [:: x] = nseq b x. Proof. by case: b. Qed. Lemma mask_cons b m x s : mask (b :: m) (x :: s) = nseq b x ++ mask m s. Proof. by case: b. Qed. Lemma size_mask m s : size m = size s -> size (mask m s) = count id m. Proof. by move: m s; apply: seq_ind2 => // -[] x m s /= _ ->. Qed. Lemma mask_cat m1 m2 s1 s2 : size m1 = size s1 -> mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2. Proof. by move: m1 s1; apply: seq_ind2 => // -[] m1 x1 s1 /= _ ->. Qed. Lemma mask_rcons b m x s : size m = size s -> mask (rcons m b) (rcons s x) = mask m s ++ nseq b x. Proof. by move=> ms; rewrite -!cats1 mask_cat//; case: b. Qed. Lemma all_mask a m s : all a s -> all a (mask m s). Proof. by elim: s m => [|x s IHs] [|[] m]//= /andP[ax /IHs->]; rewrite ?ax. Qed. Lemma has_mask_cons a b m x s : has a (mask (b :: m) (x :: s)) = b && a x || has a (mask m s). Proof. by case: b. Qed. Lemma has_mask a m s : has a (mask m s) -> has a s. Proof. by apply/contraTT; rewrite -!all_predC; apply: all_mask. Qed. Lemma rev_mask m s : size m = size s -> rev (mask m s) = mask (rev m) (rev s). Proof. move: m s; apply: seq_ind2 => //= b x m s eq_size_sm IH. by case: b; rewrite !rev_cons mask_rcons ?IH ?size_rev// (cats1, cats0). Qed. Lemma mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) = rot (count id (take n0 m)) (mask m s). Proof. move=> Ems; rewrite mask_cat ?size_drop ?Ems // -rot_size_cat. by rewrite size_mask -?mask_cat ?size_take ?Ems // !cat_take_drop. Qed. Lemma resize_mask m s : {m1 | size m1 = size s & mask m s = mask m1 s}. Proof. exists (take (size s) m ++ nseq (size s - size m) false). by elim: s m => [|x s IHs] [|b m] //=; rewrite (size_nseq, IHs). by elim: s m => [|x s IHs] [|b m] //=; rewrite (mask_false, IHs). Qed. Lemma takeEmask i s : take i s = mask (nseq i true) s. Proof. by elim: i s => [s|i IHi []// ? ?]; rewrite ?take0 //= IHi. Qed. Lemma dropEmask i s : drop i s = mask (nseq i false ++ nseq (size s - i) true) s. Proof. by elim: i s => [s|? ? []//]; rewrite drop0/= mask_true// subn0. Qed. End Mask. Arguments mask _ !_ !_. Section EqMask. Variables (n0 : nat) (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mem_mask_cons x b m y s : (x \in mask (b :: m) (y :: s)) = b && (x == y) || (x \in mask m s). Proof. by case: b. Qed. Lemma mem_mask x m s : x \in mask m s -> x \in s. Proof. by rewrite -!has_pred1 => /has_mask. Qed. Lemma in_mask x m s : uniq s -> x \in mask m s = (x \in s) && nth false m (index x s). Proof. elim: s m => [|y s IHs] [|[] m]//= /andP[yNs ?]; rewrite ?in_cons ?IHs //=; by have [->|neq_xy] //= := eqVneq; rewrite ?andbF // (negPf yNs). Qed. Lemma mask_uniq s : uniq s -> forall m, uniq (mask m s). Proof. elim: s => [|x s IHs] Uxs [|b m] //=. case: b Uxs => //= /andP[s'x Us]; rewrite {}IHs // andbT. by apply: contra s'x; apply: mem_mask. Qed. Lemma mem_mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) =i mask m s. Proof. by move=> Ems x; rewrite mask_rot // mem_rot. Qed. End EqMask. Section Subseq. Variable T : eqType. Implicit Type s : seq T. Fixpoint subseq s1 s2 := if s2 is y :: s2' then if s1 is x :: s1' then subseq (if x == y then s1' else s1) s2' else true else s1 == [::]. Lemma sub0seq s : subseq [::] s. Proof. by case: s. Qed. Lemma subseq0 s : subseq s [::] = (s == [::]). Proof. by []. Qed. Lemma subseq_refl s : subseq s s. Proof. by elim: s => //= x s IHs; rewrite eqxx. Qed. Hint Resolve subseq_refl : core. Lemma subseqP s1 s2 : reflect (exists2 m, size m = size s2 & s1 = mask m s2) (subseq s1 s2). Proof. elim: s2 s1 => [|y s2 IHs2] [|x s1]. - by left; exists [::]. - by right=> -[m /eqP/nilP->]. - by left; exists (nseq (size s2).+1 false); rewrite ?size_nseq //= mask_false. apply: {IHs2}(iffP (IHs2 _)) => [] [m sz_m def_s1]. by exists ((x == y) :: m); rewrite /= ?sz_m // -def_s1; case: eqP => // ->. case: eqP => [_ | ne_xy]; last first. by case: m def_s1 sz_m => [|[] m] //; [case | move=> -> [<-]; exists m]. pose i := index true m; have def_m_i: take i m = nseq (size (take i m)) false. apply/all_pred1P; apply/(all_nthP true) => j. rewrite size_take ltnNge geq_min negb_or -ltnNge => /andP[lt_j_i _]. rewrite nth_take //= -negb_add addbF -addbT -negb_eqb. by rewrite [_ == _](before_find _ lt_j_i). have lt_i_m: i < size m. rewrite ltnNge; apply/negP=> le_m_i; rewrite take_oversize // in def_m_i. by rewrite def_m_i mask_false in def_s1. rewrite size_take lt_i_m in def_m_i. exists (take i m ++ drop i.+1 m). rewrite size_cat size_take size_drop lt_i_m. by rewrite sz_m in lt_i_m *; rewrite subnKC. rewrite {s1 def_s1}[s1](congr1 behead def_s1). rewrite -[s2](cat_take_drop i) -[m in LHS](cat_take_drop i) {}def_m_i -cat_cons. have sz_i_s2: size (take i s2) = i by apply: size_takel; rewrite sz_m in lt_i_m. rewrite lastI cat_rcons !mask_cat ?size_nseq ?size_belast ?mask_false //=. by rewrite (drop_nth true) // nth_index -?index_mem. Qed. Lemma mask_subseq m s : subseq (mask m s) s. Proof. by apply/subseqP; have [m1] := resize_mask m s; exists m1. Qed. Lemma subseq_trans : transitive subseq. Proof. move=> _ _ s /subseqP[m2 _ ->] /subseqP[m1 _ ->]. elim: s => [|x s IHs] in m2 m1 *; first by rewrite !mask0. case: m1 => [|[] m1]; first by rewrite mask0. case: m2 => [|[] m2] //; first by rewrite /= eqxx IHs. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. Qed. Lemma cat_subseq s1 s2 s3 s4 : subseq s1 s3 -> subseq s2 s4 -> subseq (s1 ++ s2) (s3 ++ s4). Proof. case/subseqP=> m1 sz_m1 -> /subseqP [m2 sz_m2 ->]; apply/subseqP. by exists (m1 ++ m2); rewrite ?size_cat ?mask_cat ?sz_m1 ?sz_m2. Qed. Lemma prefix_subseq s1 s2 : subseq s1 (s1 ++ s2). Proof. by rewrite -[s1 in subseq s1]cats0 cat_subseq ?sub0seq. Qed. Lemma suffix_subseq s1 s2 : subseq s2 (s1 ++ s2). Proof. exact: cat_subseq (sub0seq s1) _. Qed. Lemma take_subseq s i : subseq (take i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) prefix_subseq. Qed. Lemma drop_subseq s i : subseq (drop i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) suffix_subseq. Qed. Lemma mem_subseq s1 s2 : subseq s1 s2 -> {subset s1 <= s2}. Proof. by case/subseqP=> m _ -> x; apply: mem_mask. Qed. Lemma sub1seq x s : subseq [:: x] s = (x \in s). Proof. by elim: s => //= y s /[1!inE]; case: ifP; rewrite ?sub0seq. Qed. Lemma size_subseq s1 s2 : subseq s1 s2 -> size s1 <= size s2. Proof. by case/subseqP=> m sz_m ->; rewrite size_mask -sz_m ?count_size. Qed. Lemma size_subseq_leqif s1 s2 : subseq s1 s2 -> size s1 <= size s2 ?= iff (s1 == s2). Proof. move=> sub12; split; first exact: size_subseq. apply/idP/eqP=> [|-> //]; case/subseqP: sub12 => m sz_m ->{s1}. rewrite size_mask -sz_m // -all_count -(eq_all eqb_id). by move/(@all_pred1P _ true)->; rewrite sz_m mask_true. Qed. Lemma subseq_anti : antisymmetric subseq. Proof. move=> s1 s2 /andP[] /size_subseq_leqif /leqifP. by case: eqP => [//|_] + /size_subseq; rewrite ltnNge => /negP. Qed. Lemma subseq_cons s x : subseq s (x :: s). Proof. exact: suffix_subseq [:: x] s. Qed. Lemma cons_subseq s1 s2 x : subseq (x :: s1) s2 -> subseq s1 s2. Proof. exact/subseq_trans/subseq_cons. Qed. Lemma subseq_rcons s x : subseq s (rcons s x). Proof. by rewrite -cats1 prefix_subseq. Qed. Lemma subseq_uniq s1 s2 : subseq s1 s2 -> uniq s2 -> uniq s1. Proof. by case/subseqP=> m _ -> Us2; apply: mask_uniq. Qed. Lemma take_uniq s n : uniq s -> uniq (take n s). Proof. exact/subseq_uniq/take_subseq. Qed. Lemma drop_uniq s n : uniq s -> uniq (drop n s). Proof. exact/subseq_uniq/drop_subseq. Qed. Lemma undup_subseq s : subseq (undup s) s. Proof. elim: s => //= x s; case: (_ \in _); last by rewrite eqxx. by case: (undup s) => //= y u; case: (_ == _) => //=; apply: cons_subseq. Qed. Lemma subseq_rev s1 s2 : subseq (rev s1) (rev s2) = subseq s1 s2. Proof. wlog suff W : s1 s2 / subseq s1 s2 -> subseq (rev s1) (rev s2). by apply/idP/idP => /W //; rewrite !revK. by case/subseqP => m size_m ->; rewrite rev_mask // mask_subseq. Qed. Lemma subseq_cat2l s s1 s2 : subseq (s ++ s1) (s ++ s2) = subseq s1 s2. Proof. by elim: s => // x s IHs; rewrite !cat_cons /= eqxx. Qed. Lemma subseq_cat2r s s1 s2 : subseq (s1 ++ s) (s2 ++ s) = subseq s1 s2. Proof. by rewrite -subseq_rev !rev_cat subseq_cat2l subseq_rev. Qed. Lemma subseq_rot p s n : subseq p s -> exists2 k, k <= n & subseq (rot k p) (rot n s). Proof. move=> /subseqP[m size_m ->]. exists (count id (take n m)); last by rewrite -mask_rot // mask_subseq. by rewrite (leq_trans (count_size _ _))// size_take_min geq_minl. Qed. End Subseq. Prenex Implicits subseq. Arguments subseqP {T s1 s2}. #[global] Hint Resolve subseq_refl : core. Section Rem. Variables (T : eqType) (x : T). Fixpoint rem s := if s is y :: t then (if y == x then t else y :: rem t) else s. Lemma rem_cons y s : rem (y :: s) = if y == x then s else y :: rem s. Proof. by []. Qed. Lemma remE s : rem s = take (index x s) s ++ drop (index x s).+1 s. Proof. by elim: s => //= y s ->; case: eqVneq; rewrite ?drop0. Qed. Lemma rem_id s : x \notin s -> rem s = s. Proof. by elim: s => //= y s IHs /norP[neq_yx /IHs->]; case: eqVneq neq_yx. Qed. Lemma perm_to_rem s : x \in s -> perm_eq s (x :: rem s). Proof. move=> xs; rewrite remE -[X in perm_eq X](cat_take_drop (index x s)). by rewrite drop_index// -cat1s perm_catCA cat1s. Qed. Lemma size_rem s : x \in s -> size (rem s) = (size s).-1. Proof. by move/perm_to_rem/perm_size->. Qed. Lemma rem_subseq s : subseq (rem s) s. Proof. elim: s => //= y s IHs; rewrite eq_sym. by case: ifP => _; [apply: subseq_cons | rewrite eqxx]. Qed. Lemma rem_uniq s : uniq s -> uniq (rem s). Proof. by apply: subseq_uniq; apply: rem_subseq. Qed. Lemma mem_rem s : {subset rem s <= s}. Proof. exact: mem_subseq (rem_subseq s). Qed. Lemma rem_mem y s : y != x -> y \in s -> y \in rem s. Proof. move=> yx; elim: s => [//|z s IHs] /=. rewrite inE => /orP[/eqP<-|ys]; first by rewrite (negbTE yx) inE eqxx. by case: ifP => _ //; rewrite inE IHs ?orbT. Qed. Lemma rem_filter s : uniq s -> rem s = filter (predC1 x) s. Proof. elim: s => //= y s IHs /andP[not_s_y /IHs->]. by case: eqP => //= <-; apply/esym/all_filterP; rewrite all_predC has_pred1. Qed. Lemma mem_rem_uniq s : uniq s -> rem s =i [predD1 s & x]. Proof. by move/rem_filter=> -> y; rewrite mem_filter. Qed. Lemma mem_rem_uniqF s : uniq s -> x \in rem s = false. Proof. by move/mem_rem_uniq->; rewrite inE eqxx. Qed. Lemma count_rem P s : count P (rem s) = count P s - (x \in s) && P x. Proof. have [/perm_to_rem/permP->|xNs]/= := boolP (x \in s); first by rewrite addKn. by rewrite subn0 rem_id. Qed. Lemma count_mem_rem y s : count_mem y (rem s) = count_mem y s - (x == y). Proof. rewrite count_rem; have []//= := boolP (x \in s). by case: eqP => // <- /count_memPn->. Qed. End Rem. Section Map. Variables (n0 : nat) (T1 : Type) (x1 : T1). Variables (T2 : Type) (x2 : T2) (f : T1 -> T2). Fixpoint map s := if s is x :: s' then f x :: map s' else [::]. Lemma map_cons x s : map (x :: s) = f x :: map s. Proof. by []. Qed. Lemma map_nseq x : map (nseq n0 x) = nseq n0 (f x). Proof. by elim: n0 => // *; congr (_ :: _). Qed. Lemma map_cat s1 s2 : map (s1 ++ s2) = map s1 ++ map s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs. Qed. Lemma size_map s : size (map s) = size s. Proof. by elim: s => //= x s ->. Qed. Lemma behead_map s : behead (map s) = map (behead s). Proof. by case: s. Qed. Lemma nth_map n s : n < size s -> nth x2 (map s) n = f (nth x1 s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma map_rcons s x : map (rcons s x) = rcons (map s) (f x). Proof. by rewrite -!cats1 map_cat. Qed. Lemma last_map s x : last (f x) (map s) = f (last x s). Proof. by elim: s x => /=. Qed. Lemma belast_map s x : belast (f x) (map s) = map (belast x s). Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma filter_map a s : filter a (map s) = map (filter (preim f a) s). Proof. by elim: s => //= x s IHs; rewrite (fun_if map) /= IHs. Qed. Lemma find_map a s : find a (map s) = find (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma has_map a s : has a (map s) = has (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_map a s : all a (map s) = all (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_mapT (a : pred T2) s : (forall x, a (f x)) -> all a (map s). Proof. by rewrite all_map => /allT->. Qed. Lemma count_map a s : count a (map s) = count (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma map_take s : map (take n0 s) = take n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_drop s : map (drop n0 s) = drop n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_rot s : map (rot n0 s) = rot n0 (map s). Proof. by rewrite /rot map_cat map_take map_drop. Qed. Lemma map_rotr s : map (rotr n0 s) = rotr n0 (map s). Proof. by apply: canRL (rotK n0) _; rewrite -map_rot rotrK. Qed. Lemma map_rev s : map (rev s) = rev (map s). Proof. by elim: s => //= x s IHs; rewrite !rev_cons -!cats1 map_cat IHs. Qed. Lemma map_mask m s : map (mask m s) = mask m (map s). Proof. by elim: m s => [|[|] m IHm] [|x p] //=; rewrite IHm. Qed. Lemma inj_map : injective f -> injective map. Proof. by move=> injf; elim=> [|x s IHs] [|y t] //= [/injf-> /IHs->]. Qed. Lemma inj_in_map (A : {pred T1}) : {in A &, injective f} -> {in [pred s | all [in A] s] &, injective map}. Proof. move=> injf; elim=> [|x s IHs] [|y t] //= /andP[Ax As] /andP[Ay At]. by case=> /injf-> // /IHs->. Qed. End Map. (* Sequence indexing with error. *) Section onth. Variable T : Type. Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint onth s n {struct n} : option T := if s isn't x :: s then None else if n isn't n.+1 then Some x else onth s n. Lemma odflt_onth x0 s n : odflt x0 (onth s n) = nth x0 s n. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthE s : onth s =1 nth None (map Some s). Proof. by move=> n; elim: n s => [|? ?] []. Qed. Lemma onth_nth x0 x t n : onth t n = Some x -> nth x0 t n = x. Proof. by move=> tn; rewrite -odflt_onth tn. Qed. Lemma onth0n n : onth [::] n = None. Proof. by case: n. Qed. Lemma onth1P x y n : onth [:: x] n = Some y <-> n = 0 /\ x = y. Proof. by case: n => [|[]]; split=> // -[] // _ ->. Qed. Lemma onthTE s n : onth s n = (n < size s) :> bool. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthNE s n: ~~ onth s n = (size s <= n). Proof. by rewrite onthTE -leqNgt. Qed. Lemma onth_default n s : size s <= n -> onth s n = None. Proof. by rewrite -onthNE; case: onth. Qed. Lemma onth_cat s1 s2 n : onth (s1 ++ s2) n = if n < size s1 then onth s1 n else onth s2 (n - size s1). Proof. by elim: n s1 => [|? ?] []. Qed. Lemma onth_nseq x n m : onth (nseq n x) m = if m < n then Some x else None. Proof. by rewrite onthE/= -nth_nseq map_nseq. Qed. Lemma eq_onthP {s1 s2} : [<-> s1 = s2; forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i; forall i : nat, onth s1 i = onth s2 i]. Proof. tfae=> [->//|eqs12 i|eqs12]. have := eqs12 i; case: ltnP => [_ ->//|]. by rewrite geq_max => /andP[is1 is2] _; rewrite !onth_default. have /eqP eq_size_12 : size s1 == size s2. by rewrite eqn_leq -!onthNE eqs12 onthNE -eqs12 onthNE !leqnn. apply/(inj_map Some_inj)/(@eq_from_nth _ None); rewrite !size_map//. by move=> i _; rewrite -!onthE eqs12. Qed. Lemma eq_from_onth [s1 s2 : seq T] : (forall i : nat, onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 2). Qed. Lemma eq_from_onth_le [s1 s2 : seq T] : (forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 1). Qed. End onth. Lemma onth_map {T S} n (s : seq T) (f : T -> S) : onth (map f s) n = omap f (onth s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma inj_onth_map {T S} n (s : seq T) (f : T -> S) x : injective f -> onth (map f s) n = Some (f x) -> onth s n = Some x. Proof. by rewrite onth_map => /inj_omap + fs; apply. Qed. Section onthEqType. Variables T : eqType. Implicit Types x y z : T. Implicit Types i m n : nat. Implicit Type s : seq T. Lemma onthP s x : reflect (exists i, onth s i = Some x) (x \in s). Proof. elim: s => [|y s IHs]; first by constructor=> -[] []. rewrite in_cons; case: eqVneq => [->|/= Nxy]; first by constructor; exists 0. apply: (iffP idP) => [/IHs[i <-]|[[|i]//=]]; first by exists i.+1. by move=> [eq_xy]; rewrite eq_xy eqxx in Nxy. by move=> six; apply/IHs; exists i. Qed. Lemma onthPn s x : reflect (forall i, onth s i != Some x) (x \notin s). Proof. apply: (iffP idP); first by move=> /onthP + i; apply: contra_not_neq; exists i. by move=> nsix; apply/onthP => -[n /eqP/negPn]; rewrite nsix. Qed. Lemma onth_inj s n m : uniq s -> minn m n < size s -> onth s n = onth s m -> n = m. Proof. elim: s m n => [|x s IHs]//= [|m] [|n]//=; rewrite ?minnSS !ltnS. - by move=> /andP[+ _] _ /eqP => /onthPn/(_ _)/negPf->. - by move=> /andP[+ _] _ /esym /eqP => /onthPn/(_ _)/negPf->. by move=> /andP[xNs /IHs]/[apply]/[apply]->. Qed. End onthEqType. Arguments onthP {T s x}. Arguments onthPn {T s x}. Arguments onth_nth {T}. Arguments onth_inj {T}. Notation "[ 'seq' E | i <- s ]" := (map (fun i => E) s) (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s ] ']'") : seq_scope. Notation "[ 'seq' E | i <- s & C ]" := [seq E | i <- [seq i <- s | C]] (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s '/ ' & C ] ']'") : seq_scope. Notation "[ 'seq' E : R | i <- s ]" := (@map _ R (fun i => E) s) (i binder, only parsing) : seq_scope. Notation "[ 'seq' E : R | i <- s & C ]" := [seq E : R | i <- [seq i <- s | C]] (i binder, only parsing) : seq_scope. Lemma filter_mask T a (s : seq T) : filter a s = mask (map a s) s. Proof. by elim: s => //= x s <-; case: (a x). Qed. Lemma all_sigP T a (s : seq T) : all a s -> {s' : seq (sig a) | s = map sval s'}. Proof. elim: s => /= [_|x s ihs /andP [ax /ihs [s' ->]]]; first by exists [::]. by exists (exist a x ax :: s'). Qed. Section MiscMask. Lemma leq_count_mask T (P : {pred T}) m s : count P (mask m s) <= count P s. Proof. by elim: s m => [|x s IHs] [|[] m]//=; rewrite ?leq_add2l (leq_trans (IHs _)) ?leq_addl. Qed. Variable (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mask_filter s m : uniq s -> mask m s = [seq i <- s | i \in mask m s]. Proof. elim: m s => [|[] m IH] [|x s /= /andP[/negP xS uS]]; rewrite ?filter_pred0 //. rewrite inE eqxx /=; congr cons; rewrite [LHS]IH//. by apply/eq_in_filter => ? /[1!inE]; case: eqP => [->|]. by case: ifP => [/mem_mask //|_]; apply: IH. Qed. Lemma leq_count_subseq P s1 s2 : subseq s1 s2 -> count P s1 <= count P s2. Proof. by move=> /subseqP[m _ ->]; rewrite leq_count_mask. Qed. Lemma count_maskP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 m : bitseq, size m = size s2 & perm_eq s1 (mask m s2). Proof. split=> [s1_le|[m _ /permP s1ms2 x]]; last by rewrite s1ms2 leq_count_mask. suff [m mP]: exists m, perm_eq s1 (mask m s2). by have [m' sm' eqm] := resize_mask m s2; exists m'; rewrite -?eqm. elim: s2 => [|x s2 IHs]//= in s1 s1_le *. by exists [::]; apply/allP => x _/=; rewrite eqn_leq s1_le. have [y|m s1s2] := IHs (rem x s1); first by rewrite count_mem_rem leq_subLR. exists ((x \in s1) :: m); have [|/rem_id<-//] := boolP (x \in s1). by move/perm_to_rem/permPl->; rewrite perm_cons. Qed. Lemma count_subseqP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 s, subseq s s2 & perm_eq s1 s. Proof. split=> [/count_maskP[m _]|]; first by exists (mask m s2); rewrite ?mask_subseq. by move=> -[_/subseqP[m sm ->] ?]; apply/count_maskP; exists m. Qed. End MiscMask. Section FilterSubseq. Variable T : eqType. Implicit Types (s : seq T) (a : pred T). Lemma filter_subseq a s : subseq (filter a s) s. Proof. by apply/subseqP; exists (map a s); rewrite ?size_map ?filter_mask. Qed. Lemma subseq_filter s1 s2 a : subseq s1 (filter a s2) = all a s1 && subseq s1 s2. Proof. elim: s2 s1 => [|x s2 IHs] [|y s1] //=; rewrite ?andbF ?sub0seq //. by case a_x: (a x); rewrite /= !IHs /=; case: eqP => // ->; rewrite a_x. Qed. Lemma subseq_uniqP s1 s2 : uniq s2 -> reflect (s1 = filter [in s1] s2) (subseq s1 s2). Proof. move=> uniq_s2; apply: (iffP idP) => [ss12 | ->]; last exact: filter_subseq. apply/eqP; rewrite -size_subseq_leqif ?subseq_filter ?(introT allP) //. apply/eqP/esym/perm_size. rewrite uniq_perm ?filter_uniq ?(subseq_uniq ss12) // => x. by rewrite mem_filter; apply: andb_idr; apply: (mem_subseq ss12). Qed. Lemma uniq_subseq_pivot x (s1 s2 s3 s4 : seq T) (s := s3 ++ x :: s4) : uniq s -> subseq (s1 ++ x :: s2) s = (subseq s1 s3 && subseq s2 s4). Proof. move=> uniq_s; apply/idP/idP => [sub_s'_s|/andP[? ?]]; last first. by rewrite cat_subseq //= eqxx. have uniq_s' := subseq_uniq sub_s'_s uniq_s. have/eqP {sub_s'_s uniq_s} := subseq_uniqP _ uniq_s sub_s'_s. rewrite !filter_cat /= mem_cat inE eqxx orbT /=. rewrite uniq_eqseq_pivotl // => /andP [/eqP -> /eqP ->]. by rewrite !filter_subseq. Qed. Lemma perm_to_subseq s1 s2 : subseq s1 s2 -> {s3 | perm_eq s2 (s1 ++ s3)}. Proof. elim Ds2: s2 s1 => [|y s2' IHs] [|x s1] //=; try by exists s2; rewrite Ds2. case: eqP => [-> | _] /IHs[s3 perm_s2] {IHs}. by exists s3; rewrite perm_cons. by exists (rcons s3 y); rewrite -cat_cons -perm_rcons -!cats1 catA perm_cat2r. Qed. Lemma subseq_rem x : {homo rem x : s1 s2 / @subseq T s1 s2}. Proof. move=> s1 s2; elim: s2 s1 => [|x2 s2 IHs2] [|x1 s1]; rewrite ?sub0seq //=. have [->|_] := eqVneq x1 x2; first by case: eqP => //= _ /IHs2; rewrite eqxx. move=> /IHs2/subseq_trans->//. by have [->|_] := eqVneq x x2; [apply: rem_subseq|apply: subseq_cons]. Qed. End FilterSubseq. Arguments subseq_uniqP [T s1 s2]. Section EqMap. Variables (n0 : nat) (T1 : eqType) (x1 : T1). Variables (T2 : eqType) (x2 : T2) (f : T1 -> T2). Implicit Type s : seq T1. Lemma map_f s x : x \in s -> f x \in map f s. Proof. by elim: s => //= y s IHs /predU1P[->|/IHs]; [apply: predU1l | apply: predU1r]. Qed. Lemma mapP s y : reflect (exists2 x, x \in s & y = f x) (y \in map f s). Proof. elim: s => [|x s IHs]; [by right; case|rewrite /= inE]. exact: equivP (orPP eqP IHs) (iff_sym exists_cons). Qed. Lemma subset_mapP (s : seq T1) (s' : seq T2) : {subset s' <= map f s} <-> exists2 t, all (mem s) t & s' = map f t. Proof. split => [|[r /allP/= rE ->] _ /mapP[x xr ->]]; last by rewrite map_f ?rE. elim: s' => [|x s' IHs'] subss'; first by exists [::]. have /mapP[y ys ->] := subss' _ (mem_head _ _). have [x' x's'|t st ->] := IHs'; first by rewrite subss'// inE x's' orbT. by exists (y :: t); rewrite //= ys st. Qed. Lemma map_uniq s : uniq (map f s) -> uniq s. Proof. elim: s => //= x s IHs /andP[not_sfx /IHs->]; rewrite andbT. by apply: contra not_sfx => sx; apply/mapP; exists x. Qed. Lemma map_inj_in_uniq s : {in s &, injective f} -> uniq (map f s) = uniq s. Proof. elim: s => //= x s IHs //= injf; congr (~~ _ && _). apply/mapP/idP=> [[y sy /injf] | ]; last by exists x. by rewrite mem_head mem_behead // => ->. by apply: IHs => y z sy sz; apply: injf => //; apply: predU1r. Qed. Lemma map_subseq s1 s2 : subseq s1 s2 -> subseq (map f s1) (map f s2). Proof. case/subseqP=> m sz_m ->; apply/subseqP. by exists m; rewrite ?size_map ?map_mask. Qed. Lemma nth_index_map s x0 x : {in s &, injective f} -> x \in s -> nth x0 s (index (f x) (map f s)) = x. Proof. elim: s => //= y s IHs inj_f s_x; rewrite (inj_in_eq inj_f) ?mem_head //. move: s_x; rewrite inE; have [-> // | _] := eqVneq; apply: IHs. by apply: sub_in2 inj_f => z; apply: predU1r. Qed. Lemma perm_map s t : perm_eq s t -> perm_eq (map f s) (map f t). Proof. by move/permP=> Est; apply/permP=> a; rewrite !count_map Est. Qed. Lemma sub_map s1 s2 : {subset s1 <= s2} -> {subset map f s1 <= map f s2}. Proof. by move=> sub_s ? /mapP[x x_s ->]; rewrite map_f ?sub_s. Qed. Lemma eq_mem_map s1 s2 : s1 =i s2 -> map f s1 =i map f s2. Proof. by move=> Es x; apply/idP/idP; apply: sub_map => ?; rewrite Es. Qed. Hypothesis Hf : injective f. Lemma mem_map s x : (f x \in map f s) = (x \in s). Proof. by apply/mapP/idP=> [[y Hy /Hf->] //|]; exists x. Qed. Lemma index_map s x : index (f x) (map f s) = index x s. Proof. by rewrite /index; elim: s => //= y s IHs; rewrite (inj_eq Hf) IHs. Qed. Lemma map_inj_uniq s : uniq (map f s) = uniq s. Proof. by apply: map_inj_in_uniq; apply: in2W. Qed. Lemma undup_map_inj s : undup (map f s) = map f (undup s). Proof. by elim: s => //= s0 s ->; rewrite mem_map //; case: (_ \in _). Qed. Lemma perm_map_inj s t : perm_eq (map f s) (map f t) -> perm_eq s t. Proof. move/permP=> Est; apply/allP=> x _ /=. have Dx: pred1 x =1 preim f (pred1 (f x)) by move=> y /=; rewrite inj_eq. by rewrite !(eq_count Dx) -!count_map Est. Qed. End EqMap. Arguments mapP {T1 T2 f s y}. Arguments subset_mapP {T1 T2}. Lemma map_of_seq (T1 : eqType) T2 (s : seq T1) (fs : seq T2) (y0 : T2) : {f | uniq s -> size fs = size s -> map f s = fs}. Proof. exists (fun x => nth y0 fs (index x s)) => uAs eq_sz. apply/esym/(@eq_from_nth _ y0); rewrite ?size_map eq_sz // => i ltis. by have x0 : T1 by [case: (s) ltis]; rewrite (nth_map x0) // index_uniq. Qed. Section MapComp. Variable S T U : Type. Lemma map_id (s : seq T) : map id s = s. Proof. by elim: s => //= x s ->. Qed. Lemma eq_map (f g : S -> T) : f =1 g -> map f =1 map g. Proof. by move=> Ef; elim=> //= x s ->; rewrite Ef. Qed. Lemma map_comp (f : T -> U) (g : S -> T) s : map (f \o g) s = map f (map g s). Proof. by elim: s => //= x s ->. Qed. Lemma mapK (f : S -> T) (g : T -> S) : cancel f g -> cancel (map f) (map g). Proof. by move=> fK; elim=> //= x s ->; rewrite fK. Qed. Lemma mapK_in (A : {pred S}) (f : S -> T) (g : T -> S) : {in A, cancel f g} -> {in [pred s | all [in A] s], cancel (map f) (map g)}. Proof. by move=> fK; elim=> //= x s IHs /andP[/fK-> /IHs->]. Qed. End MapComp. Lemma eq_in_map (S : eqType) T (f g : S -> T) (s : seq S) : {in s, f =1 g} <-> map f s = map g s. Proof. elim: s => //= x s IHs; split=> [/forall_cons[-> ?]|]; first by rewrite IHs.1. by move=> -[? ?]; apply/forall_cons; split=> [//|]; apply: IHs.2. Qed. Lemma map_id_in (T : eqType) f (s : seq T) : {in s, f =1 id} -> map f s = s. Proof. by move/eq_in_map->; apply: map_id. Qed. (* Map a partial function *) Section Pmap. Variables (aT rT : Type) (f : aT -> option rT) (g : rT -> aT). Fixpoint pmap s := if s is x :: s' then let r := pmap s' in oapp (cons^~ r) r (f x) else [::]. Lemma map_pK : pcancel g f -> cancel (map g) pmap. Proof. by move=> gK; elim=> //= x s ->; rewrite gK. Qed. Lemma size_pmap s : size (pmap s) = count [eta f] s. Proof. by elim: s => //= x s <-; case: (f _). Qed. Lemma pmapS_filter s : map some (pmap s) = map f (filter [eta f] s). Proof. by elim: s => //= x s; case fx: (f x) => //= [u] <-; congr (_ :: _). Qed. Hypothesis fK : ocancel f g. Lemma pmap_filter s : map g (pmap s) = filter [eta f] s. Proof. by elim: s => //= x s <-; rewrite -{3}(fK x); case: (f _). Qed. Lemma pmap_cat s t : pmap (s ++ t) = pmap s ++ pmap t. Proof. by elim: s => //= x s ->; case/f: x. Qed. Lemma all_pmap (p : pred rT) s : all p (pmap s) = all [pred i | oapp p true (f i)] s. Proof. by elim: s => //= x s <-; case: f. Qed. End Pmap. Lemma eq_in_pmap (aT : eqType) rT (f1 f2 : aT -> option rT) s : {in s, f1 =1 f2} -> pmap f1 s = pmap f2 s. Proof. by elim: s => //= a s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_pmap aT rT (f1 f2 : aT -> option rT) : f1 =1 f2 -> pmap f1 =1 pmap f2. Proof. by move=> Ef; elim => //= a s ->; rewrite Ef. Qed. Section EqPmap. Variables (aT rT : eqType) (f : aT -> option rT) (g : rT -> aT). Lemma mem_pmap s u : (u \in pmap f s) = (Some u \in map f s). Proof. by elim: s => //= x s IHs; rewrite in_cons -IHs; case: (f x). Qed. Hypothesis fK : ocancel f g. Lemma can2_mem_pmap : pcancel g f -> forall s u, (u \in pmap f s) = (g u \in s). Proof. by move=> gK s u; rewrite -(mem_map (pcan_inj gK)) pmap_filter // mem_filter gK. Qed. Lemma pmap_uniq s : uniq s -> uniq (pmap f s). Proof. move/(filter_uniq f); rewrite -(pmap_filter fK); exact: map_uniq. Qed. Lemma perm_pmap s t : perm_eq s t -> perm_eq (pmap f s) (pmap f t). Proof. move=> eq_st; apply/(perm_map_inj Some_inj); rewrite !pmapS_filter. exact/perm_map/perm_filter. Qed. End EqPmap. Section PmapSub. Variables (T : Type) (p : pred T) (sT : subType p). Lemma size_pmap_sub s : size (pmap (insub : T -> option sT) s) = count p s. Proof. by rewrite size_pmap (eq_count (isSome_insub _)). Qed. End PmapSub. Section EqPmapSub. Variables (T : eqType) (p : pred T) (sT : subEqType p). Let insT : T -> option sT := insub. Lemma mem_pmap_sub s u : (u \in pmap insT s) = (val u \in s). Proof. exact/(can2_mem_pmap (insubK _))/valK. Qed. Lemma pmap_sub_uniq s : uniq s -> uniq (pmap insT s). Proof. exact: (pmap_uniq (insubK _)). Qed. End EqPmapSub. (* Index sequence *) Fixpoint iota m n := if n is n'.+1 then m :: iota m.+1 n' else [::]. Lemma size_iota m n : size (iota m n) = n. Proof. by elim: n m => //= n IHn m; rewrite IHn. Qed. Lemma iotaD m n1 n2 : iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2. Proof. by elim: n1 m => [|n1 IHn1] m; rewrite ?addn0 // -addSnnS /= -IHn1. Qed. Lemma iotaDl m1 m2 n : iota (m1 + m2) n = map (addn m1) (iota m2 n). Proof. by elim: n m2 => //= n IHn m2; rewrite -addnS IHn. Qed. Lemma nth_iota p m n i : i < n -> nth p (iota m n) i = m + i. Proof. by move/subnKC <-; rewrite addSnnS iotaD nth_cat size_iota ltnn subnn. Qed. Lemma mem_iota m n i : (i \in iota m n) = (m <= i < m + n). Proof. elim: n m => [|n IHn] /= m; first by rewrite addn0 ltnNge andbN. by rewrite in_cons IHn addnS ltnS; case: ltngtP => // ->; rewrite leq_addr. Qed. Lemma iota_uniq m n : uniq (iota m n). Proof. by elim: n m => //= n IHn m; rewrite mem_iota ltnn /=. Qed. Lemma take_iota k m n : take k (iota m n) = iota m (minn k n). Proof. have [lt_k_n|le_n_k] := ltnP. by elim: k n lt_k_n m => [|k IHk] [|n] //= H m; rewrite IHk. by apply: take_oversize; rewrite size_iota. Qed. Lemma drop_iota k m n : drop k (iota m n) = iota (m + k) (n - k). Proof. by elim: k m n => [|k IHk] m [|n] //=; rewrite ?addn0 // IHk addnS subSS. Qed. Lemma filter_iota_ltn m n j : j <= n -> [seq i <- iota m n | i < m + j] = iota m j. Proof. elim: n m j => [m j|n IHn m [|j] jlen]; first by rewrite leqn0 => /eqP ->. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 ltnNge mem_iota => /andP[->]. by rewrite /= addnS leq_addr -addSn IHn. Qed. Lemma filter_iota_leq n m j : j < n -> [seq i <- iota m n | i <= m + j] = iota m j.+1. Proof. elim: n m j => [//|n IHn] m [|j] jlen /=; rewrite leq_addr. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 leqNgt mem_iota => /andP[->]. by rewrite addnS -addSn IHn -1?ltnS. Qed. (* Making a sequence of a specific length, using indexes to compute items. *) Section MakeSeq. Variables (T : Type) (x0 : T). Definition mkseq f n : seq T := map f (iota 0 n). Lemma size_mkseq f n : size (mkseq f n) = n. Proof. by rewrite size_map size_iota. Qed. Lemma mkseqS f n : mkseq f n.+1 = rcons (mkseq f n) (f n). Proof. by rewrite /mkseq -addn1 iotaD add0n map_cat cats1. Qed. Lemma eq_mkseq f g : f =1 g -> mkseq f =1 mkseq g. Proof. by move=> Efg n; apply: eq_map Efg _. Qed. Lemma nth_mkseq f n i : i < n -> nth x0 (mkseq f n) i = f i. Proof. by move=> Hi; rewrite (nth_map 0) ?nth_iota ?size_iota. Qed. Lemma mkseq_nth s : mkseq (nth x0 s) (size s) = s. Proof. by apply: (@eq_from_nth _ x0); rewrite size_mkseq // => i Hi; rewrite nth_mkseq. Qed. Variant mkseq_spec s : seq T -> Type := | MapIota n f : s = mkseq f n -> mkseq_spec s (mkseq f n). Lemma mkseqP s : mkseq_spec s s. Proof. by rewrite -[s]mkseq_nth; constructor. Qed. Lemma map_nth_iota0 s i : i <= size s -> [seq nth x0 s j | j <- iota 0 i] = take i s. Proof. by move=> ile; rewrite -[s in RHS]mkseq_nth -map_take take_iota (minn_idPl _). Qed. Lemma map_nth_iota s i j : j <= size s - i -> [seq nth x0 s k | k <- iota i j] = take j (drop i s). Proof. elim: i => [|i IH] in s j *; first by rewrite subn0 drop0 => /map_nth_iota0->. case: s => [|x s /IH<-]; first by rewrite leqn0 => /eqP->. by rewrite -add1n iotaDl -map_comp. Qed. End MakeSeq. Section MakeEqSeq. Variable T : eqType. Lemma mkseq_uniqP (f : nat -> T) n : reflect {in gtn n &, injective f} (uniq (mkseq f n)). Proof. apply: (equivP (uniqP (f 0))); rewrite size_mkseq. by split=> injf i j lti ltj; have:= injf i j lti ltj; rewrite !nth_mkseq. Qed. Lemma mkseq_uniq (f : nat -> T) n : injective f -> uniq (mkseq f n). Proof. by move/map_inj_uniq->; apply: iota_uniq. Qed. Lemma perm_iotaP {s t : seq T} x0 (It := iota 0 (size t)) : reflect (exists2 Is, perm_eq Is It & s = map (nth x0 t) Is) (perm_eq s t). Proof. apply: (iffP idP) => [Est | [Is eqIst ->]]; last first. by rewrite -{2}[t](mkseq_nth x0) perm_map. elim: t => [|x t IHt] in s It Est *. by rewrite (perm_small_eq _ Est) //; exists [::]. have /rot_to[k s1 Ds]: x \in s by rewrite (perm_mem Est) mem_head. have [|Is1 eqIst1 Ds1] := IHt s1; first by rewrite -(perm_cons x) -Ds perm_rot. exists (rotr k (0 :: map succn Is1)). by rewrite perm_rot /It /= perm_cons (iotaDl 1) perm_map. by rewrite map_rotr /= -map_comp -(@eq_map _ _ (nth x0 t)) // -Ds1 -Ds rotK. Qed. End MakeEqSeq. Arguments perm_iotaP {T s t}. Section FoldRight. Variables (T : Type) (R : Type) (f : T -> R -> R) (z0 : R). Fixpoint foldr s := if s is x :: s' then f x (foldr s') else z0. End FoldRight. Section FoldRightComp. Variables (T1 T2 : Type) (h : T1 -> T2). Variables (R : Type) (f : T2 -> R -> R) (z0 : R). Lemma foldr_cat s1 s2 : foldr f z0 (s1 ++ s2) = foldr f (foldr f z0 s2) s1. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma foldr_rcons s x : foldr f z0 (rcons s x) = foldr f (f x z0) s. Proof. by rewrite -cats1 foldr_cat. Qed. Lemma foldr_map s : foldr f z0 (map h s) = foldr (fun x z => f (h x) z) z0 s. Proof. by elim: s => //= x s ->. Qed. End FoldRightComp. (* Quick characterization of the null sequence. *) Definition sumn := foldr addn 0. Lemma sumn_ncons x n s : sumn (ncons n x s) = x * n + sumn s. Proof. by rewrite mulnC; elim: n => //= n ->; rewrite addnA. Qed. Lemma sumn_nseq x n : sumn (nseq n x) = x * n. Proof. by rewrite sumn_ncons addn0. Qed. Lemma sumn_cat s1 s2 : sumn (s1 ++ s2) = sumn s1 + sumn s2. Proof. by elim: s1 => //= x s1 ->; rewrite addnA. Qed. Lemma sumn_count T (a : pred T) s : sumn [seq a i : nat | i <- s] = count a s. Proof. by elim: s => //= s0 s /= ->. Qed. Lemma sumn_rcons s n : sumn (rcons s n) = sumn s + n. Proof. by rewrite -cats1 sumn_cat /= addn0. Qed. Lemma perm_sumn s1 s2 : perm_eq s1 s2 -> sumn s1 = sumn s2. Proof. by apply/catCA_perm_subst: s1 s2 => s1 s2 s3; rewrite !sumn_cat addnCA. Qed. Lemma sumn_rot s n : sumn (rot n s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rot. Qed. Lemma sumn_rev s : sumn (rev s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rev. Qed. Lemma natnseq0P s : reflect (s = nseq (size s) 0) (sumn s == 0). Proof. apply: (iffP idP) => [|->]; last by rewrite sumn_nseq. by elim: s => //= x s IHs; rewrite addn_eq0 => /andP[/eqP-> /IHs <-]. Qed. Lemma sumn_set_nth s x0 n x : sumn (set_nth x0 s n x) = sumn s + x - (nth x0 s n) * (n < size s) + x0 * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. by rewrite sumn_cat sumn_ncons /= addn0 muln0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in sumn s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !sumn_cat /= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma sumn_set_nth_ltn s x0 n x : n < size s -> sumn (set_nth x0 s n x) = sumn s + x - nth x0 s n. Proof. move=> nlts; rewrite sumn_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma sumn_set_nth0 s n x : sumn (set_nth 0 s n x) = sumn s + x - nth 0 s n. Proof. rewrite sumn_set_nth mul0n addn0. by case: ltnP => [_|nges]; rewrite ?muln1// nth_default. Qed. Section FoldLeft. Variables (T R : Type) (f : R -> T -> R). Fixpoint foldl z s := if s is x :: s' then foldl (f z x) s' else z. Lemma foldl_rev z s : foldl z (rev s) = foldr (fun x z => f z x) z s. Proof. by elim/last_ind: s z => // s x IHs z; rewrite rev_rcons -cats1 foldr_cat -IHs. Qed. Lemma foldl_cat z s1 s2 : foldl z (s1 ++ s2) = foldl (foldl z s1) s2. Proof. by rewrite -(revK (s1 ++ s2)) foldl_rev rev_cat foldr_cat -!foldl_rev !revK. Qed. Lemma foldl_rcons z s x : foldl z (rcons s x) = f (foldl z s) x. Proof. by rewrite -cats1 foldl_cat. Qed. End FoldLeft. Section Folds. Variables (T : Type) (f : T -> T -> T). Hypotheses (fA : associative f) (fC : commutative f). Lemma foldl_foldr x0 l : foldl f x0 l = foldr f x0 l. Proof. elim: l x0 => [//|x1 l IHl] x0 /=; rewrite {}IHl. by elim: l x0 x1 => [//|x2 l IHl] x0 x1 /=; rewrite IHl !fA [f x2 x1]fC. Qed. End Folds. Section Scan. Variables (T1 : Type) (x1 : T1) (T2 : Type) (x2 : T2). Variables (f : T1 -> T1 -> T2) (g : T1 -> T2 -> T1). Fixpoint pairmap x s := if s is y :: s' then f x y :: pairmap y s' else [::]. Lemma size_pairmap x s : size (pairmap x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma pairmap_cat x s1 s2 : pairmap x (s1 ++ s2) = pairmap x s1 ++ pairmap (last x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma nth_pairmap s n : n < size s -> forall x, nth x2 (pairmap x s) n = f (nth x1 (x :: s) n) (nth x1 s n). Proof. by elim: s n => [|y s IHs] [|n] //= Hn x; apply: IHs. Qed. Fixpoint scanl x s := if s is y :: s' then let x' := g x y in x' :: scanl x' s' else [::]. Lemma size_scanl x s : size (scanl x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma scanl_cat x s1 s2 : scanl x (s1 ++ s2) = scanl x s1 ++ scanl (foldl g x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma scanl_rcons x s1 y : scanl x (rcons s1 y) = rcons (scanl x s1) (foldl g x (rcons s1 y)). Proof. by rewrite -!cats1 scanl_cat foldl_cat. Qed. Lemma nth_cons_scanl s n : n <= size s -> forall x, nth x1 (x :: scanl x s) n = foldl g x (take n s). Proof. by elim: s n => [|y s IHs] [|n] Hn x //=; rewrite IHs. Qed. Lemma nth_scanl s n : n < size s -> forall x, nth x1 (scanl x s) n = foldl g x (take n.+1 s). Proof. by move=> n_lt x; rewrite -nth_cons_scanl. Qed. Lemma scanlK : (forall x, cancel (g x) (f x)) -> forall x, cancel (scanl x) (pairmap x). Proof. by move=> Hfg x s; elim: s x => //= y s IHs x; rewrite Hfg IHs. Qed. Lemma pairmapK : (forall x, cancel (f x) (g x)) -> forall x, cancel (pairmap x) (scanl x). Proof. by move=> Hgf x s; elim: s x => //= y s IHs x; rewrite Hgf IHs. Qed. End Scan. Prenex Implicits mask map pmap foldr foldl scanl pairmap. Section Zip. Variables (S T : Type) (r : S -> T -> bool). Fixpoint zip (s : seq S) (t : seq T) {struct t} := match s, t with | x :: s', y :: t' => (x, y) :: zip s' t' | _, _ => [::] end. Definition unzip1 := map (@fst S T). Definition unzip2 := map (@snd S T). Fixpoint all2 s t := match s, t with | [::], [::] => true | x :: s, y :: t => r x y && all2 s t | _, _ => false end. Lemma zip_unzip s : zip (unzip1 s) (unzip2 s) = s. Proof. by elim: s => [|[x y] s /= ->]. Qed. Lemma unzip1_zip s t : size s <= size t -> unzip1 (zip s t) = s. Proof. by elim: s t => [|x s IHs] [|y t] //= le_s_t; rewrite IHs. Qed. Lemma unzip2_zip s t : size t <= size s -> unzip2 (zip s t) = t. Proof. by elim: s t => [|x s IHs] [|y t] //= le_t_s; rewrite IHs. Qed. Lemma size1_zip s t : size s <= size t -> size (zip s t) = size s. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size2_zip s t : size t <= size s -> size (zip s t) = size t. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size_zip s t : size (zip s t) = minn (size s) (size t). Proof. by elim: s t => [|x s IHs] [|t2 t] //=; rewrite IHs minnSS. Qed. Lemma zip_cat s1 s2 t1 t2 : size s1 = size t1 -> zip (s1 ++ s2) (t1 ++ t2) = zip s1 t1 ++ zip s2 t2. Proof. by move: s1 t1; apply: seq_ind2 => //= x y s1 t1 _ ->. Qed. Lemma nth_zip x y s t i : size s = size t -> nth (x, y) (zip s t) i = (nth x s i, nth y t i). Proof. by elim: i s t => [|i IHi] [|y1 s1] [|y2 t] //= [/IHi->]. Qed. Lemma nth_zip_cond p s t i : nth p (zip s t) i = (if i < size (zip s t) then (nth p.1 s i, nth p.2 t i) else p). Proof. rewrite size_zip ltnNge geq_min. by elim: s t i => [|x s IHs] [|y t] [|i] //=; rewrite ?orbT -?IHs. Qed. Lemma zip_rcons s t x y : size s = size t -> zip (rcons s x) (rcons t y) = rcons (zip s t) (x, y). Proof. by move=> eq_sz; rewrite -!cats1 zip_cat //= eq_sz. Qed. Lemma rev_zip s t : size s = size t -> rev (zip s t) = zip (rev s) (rev t). Proof. move: s t; apply: seq_ind2 => //= x y s t eq_sz IHs. by rewrite !rev_cons IHs zip_rcons ?size_rev. Qed. Lemma all2E s t : all2 s t = (size s == size t) && all [pred xy | r xy.1 xy.2] (zip s t). Proof. by elim: s t => [|x s IHs] [|y t] //=; rewrite IHs andbCA. Qed. Lemma zip_map I f g (s : seq I) : zip (map f s) (map g s) = [seq (f i, g i) | i <- s]. Proof. by elim: s => //= i s ->. Qed. Lemma unzip1_map_nth_zip x y s t l : size s = size t -> unzip1 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth x s i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. Lemma unzip2_map_nth_zip x y s t l : size s = size t -> unzip2 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth y t i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. End Zip. Lemma zip_uniql (S T : eqType) (s : seq S) (t : seq T) : uniq s -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[n _]. by apply/(uniqPn s0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minl. Qed. Lemma zip_uniqr (S T : eqType) (s : seq S) (t : seq T) : uniq t -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[_ n]. by apply/(uniqPn t0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minr. Qed. Lemma perm_zip_sym (S T : eqType) (s1 s2 : seq S) (t1 t2 : seq T) : perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq (zip t1 s1) (zip t2 s2). Proof. have swap t s : zip t s = map (fun u => (u.2, u.1)) (zip s t). by elim: s t => [|x s +] [|y t]//= => ->. by rewrite [zip t1 s1]swap [zip t2 s2]swap; apply: perm_map. Qed. Lemma perm_zip1 {S T : eqType} (t1 t2 : seq T) (s1 s2 : seq S): size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq s1 s2. Proof. wlog [x y] : s1 s2 t1 t2 / (S * T)%type => [hwlog|]. case: s2 t2 => [|x s2] [|y t2] //; last exact: hwlog. by case: s1 t1 => [|u s1] [|v t1]//= _ _ /perm_nilP. move=> eq1 eq2 /(perm_iotaP (x, y))[ns nsP /(congr1 (@unzip1 _ _))]. rewrite unzip1_zip ?unzip1_map_nth_zip -?eq1// => ->. by apply/(perm_iotaP x); exists ns; rewrite // size_zip -eq2 minnn in nsP. Qed. Lemma perm_zip2 {S T : eqType} (s1 s2 : seq S) (t1 t2 : seq T) : size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq t1 t2. Proof. by move=> ? ? ?; rewrite (@perm_zip1 _ _ s1 s2) 1?perm_zip_sym. Qed. Prenex Implicits zip unzip1 unzip2 all2. Lemma eqseq_all (T : eqType) (s t : seq T) : (s == t) = all2 eq_op s t. Proof. by elim: s t => [|x s +] [|y t]//= => <-. Qed. Lemma eq_map_all I (T : eqType) (f g : I -> T) (s : seq I) : (map f s == map g s) = all [pred xy | xy.1 == xy.2] [seq (f i, g i) | i <- s]. Proof. by rewrite eqseq_all all2E !size_map eqxx zip_map. Qed. Section Flatten. Variable T : Type. Implicit Types (s : seq T) (ss : seq (seq T)). Definition flatten := foldr cat (Nil T). Definition shape := map (@size T). Fixpoint reshape sh s := if sh is n :: sh' then take n s :: reshape sh' (drop n s) else [::]. Definition flatten_index sh r c := sumn (take r sh) + c. Definition reshape_index sh i := find (pred1 0) (scanl subn i.+1 sh). Definition reshape_offset sh i := i - sumn (take (reshape_index sh i) sh). Lemma size_flatten ss : size (flatten ss) = sumn (shape ss). Proof. by elim: ss => //= s ss <-; rewrite size_cat. Qed. Lemma flatten_cat ss1 ss2 : flatten (ss1 ++ ss2) = flatten ss1 ++ flatten ss2. Proof. by elim: ss1 => //= s ss1 ->; rewrite catA. Qed. Lemma size_reshape sh s : size (reshape sh s) = size sh. Proof. by elim: sh s => //= s0 sh IHsh s; rewrite IHsh. Qed. Lemma nth_reshape (sh : seq nat) l n : nth [::] (reshape sh l) n = take (nth 0 sh n) (drop (sumn (take n sh)) l). Proof. elim: n sh l => [| n IHn] [| sh0 sh] l; rewrite ?take0 ?drop0 //=. by rewrite addnC -drop_drop; apply: IHn. Qed. Lemma flattenK ss : reshape (shape ss) (flatten ss) = ss. Proof. by elim: ss => //= s ss IHss; rewrite take_size_cat ?drop_size_cat ?IHss. Qed. Lemma reshapeKr sh s : size s <= sumn sh -> flatten (reshape sh s) = s. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s; rewrite IHsh ?cat_take_drop //. by rewrite size_drop leq_subLR. Qed. Lemma reshapeKl sh s : size s >= sumn sh -> shape (reshape sh s) = sh. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s. rewrite size_takel; last exact: leq_trans (leq_addr _ _) sz_s. by rewrite IHsh // -(leq_add2l n) size_drop -maxnE leq_max sz_s orbT. Qed. Lemma flatten_rcons ss s : flatten (rcons ss s) = flatten ss ++ s. Proof. by rewrite -cats1 flatten_cat /= cats0. Qed. Lemma flatten_seq1 s : flatten [seq [:: x] | x <- s] = s. Proof. by elim: s => //= s0 s ->. Qed. Lemma count_flatten ss P : count P (flatten ss) = sumn [seq count P x | x <- ss]. Proof. by elim: ss => //= s ss IHss; rewrite count_cat IHss. Qed. Lemma filter_flatten ss (P : pred T) : filter P (flatten ss) = flatten [seq filter P i | i <- ss]. Proof. by elim: ss => // s ss /= <-; apply: filter_cat. Qed. Lemma rev_flatten ss : rev (flatten ss) = flatten (rev (map rev ss)). Proof. by elim: ss => //= s ss IHss; rewrite rev_cons flatten_rcons -IHss rev_cat. Qed. Lemma nth_shape ss i : nth 0 (shape ss) i = size (nth [::] ss i). Proof. rewrite /shape; case: (ltnP i (size ss)) => Hi; first exact: nth_map. by rewrite !nth_default // size_map. Qed. Lemma shape_rev ss : shape (rev ss) = rev (shape ss). Proof. exact: map_rev. Qed. Lemma eq_from_flatten_shape ss1 ss2 : flatten ss1 = flatten ss2 -> shape ss1 = shape ss2 -> ss1 = ss2. Proof. by move=> Eflat Esh; rewrite -[LHS]flattenK Eflat Esh flattenK. Qed. Lemma rev_reshape sh s : size s = sumn sh -> rev (reshape sh s) = map rev (reshape (rev sh) (rev s)). Proof. move=> sz_s; apply/(canLR revK)/eq_from_flatten_shape. rewrite reshapeKr ?sz_s // -rev_flatten reshapeKr ?revK //. by rewrite size_rev sumn_rev sz_s. transitivity (rev (shape (reshape (rev sh) (rev s)))). by rewrite !reshapeKl ?revK ?size_rev ?sz_s ?sumn_rev. rewrite shape_rev; congr (rev _); rewrite -[RHS]map_comp. by under eq_map do rewrite /= size_rev. Qed. Lemma reshape_rcons s sh n (m := sumn sh) : m + n = size s -> reshape (rcons sh n) s = rcons (reshape sh (take m s)) (drop m s). Proof. move=> Dmn; apply/(can_inj revK); rewrite rev_reshape ?rev_rcons ?sumn_rcons //. rewrite /= take_rev drop_rev -Dmn addnK revK -rev_reshape //. by rewrite size_takel // -Dmn leq_addr. Qed. Lemma flatten_indexP sh r c : c < nth 0 sh r -> flatten_index sh r c < sumn sh. Proof. move=> lt_c_sh; rewrite -[sh in sumn sh](cat_take_drop r) sumn_cat ltn_add2l. suffices lt_r_sh: r < size sh by rewrite (drop_nth 0 lt_r_sh) ltn_addr. by case: ltnP => // le_sh_r; rewrite nth_default in lt_c_sh. Qed. Lemma reshape_indexP sh i : i < sumn sh -> reshape_index sh i < size sh. Proof. rewrite /reshape_index; elim: sh => //= n sh IHsh in i *; rewrite subn_eq0. by have [// | le_n_i] := ltnP i n; rewrite -leq_subLR subSn // => /IHsh. Qed. Lemma reshape_offsetP sh i : i < sumn sh -> reshape_offset sh i < nth 0 sh (reshape_index sh i). Proof. rewrite /reshape_offset /reshape_index; elim: sh => //= n sh IHsh in i *. rewrite subn_eq0; have [| le_n_i] := ltnP i n; first by rewrite subn0. by rewrite -leq_subLR /= subnDA subSn // => /IHsh. Qed. Lemma reshape_indexK sh i : flatten_index sh (reshape_index sh i) (reshape_offset sh i) = i. Proof. rewrite /reshape_offset /reshape_index /flatten_index -subSKn. elim: sh => //= n sh IHsh in i *; rewrite subn_eq0; have [//|le_n_i] := ltnP. by rewrite /= subnDA subSn // -addnA IHsh subnKC. Qed. Lemma flatten_indexKl sh r c : c < nth 0 sh r -> reshape_index sh (flatten_index sh r c) = r. Proof. rewrite /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT. by rewrite -addnA -addnS addKn IHsh. Qed. Lemma flatten_indexKr sh r c : c < nth 0 sh r -> reshape_offset sh (flatten_index sh r c) = c. Proof. rewrite /reshape_offset /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT ?subn0. by rewrite -addnA -addnS addKn /= subnDl IHsh. Qed. Lemma nth_flatten x0 ss i (r := reshape_index (shape ss) i) : nth x0 (flatten ss) i = nth x0 (nth [::] ss r) (reshape_offset (shape ss) i). Proof. rewrite /reshape_offset -subSKn {}/r /reshape_index. elim: ss => //= s ss IHss in i *; rewrite subn_eq0 nth_cat. by have [//|le_s_i] := ltnP; rewrite subnDA subSn /=. Qed. Lemma reshape_leq sh i1 i2 (r1 := reshape_index sh i1) (c1 := reshape_offset sh i1) (r2 := reshape_index sh i2) (c2 := reshape_offset sh i2) : (i1 <= i2) = ((r1 < r2) || ((r1 == r2) && (c1 <= c2))). Proof. rewrite {}/r1 {}/c1 {}/r2 {}/c2 /reshape_offset /reshape_index. elim: sh => [|s0 s IHs] /= in i1 i2 *; rewrite ?subn0 ?subn_eq0 //. have [[] i1s0 [] i2s0] := (ltnP i1 s0, ltnP i2 s0); first by rewrite !subn0. - by apply: leq_trans i2s0; apply/ltnW. - by apply/negP => /(leq_trans i1s0); rewrite leqNgt i2s0. by rewrite !subSn // !eqSS !ltnS !subnDA -IHs leq_subLR subnKC. Qed. End Flatten. Prenex Implicits flatten shape reshape. Lemma map_flatten S T (f : T -> S) ss : map f (flatten ss) = flatten (map (map f) ss). Proof. by elim: ss => // s ss /= <-; apply: map_cat. Qed. Lemma flatten_map1 (S T : Type) (f : S -> T) s : flatten [seq [:: f x] | x <- s] = map f s. Proof. by elim: s => //= s0 s ->. Qed. Lemma undup_flatten_nseq n (T : eqType) (s : seq T) : 0 < n -> undup (flatten (nseq n s)) = undup s. Proof. elim: n => [|[|n]/= IHn]//= _; rewrite ?cats0// undup_cat {}IHn//. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => x. by rewrite mem_undup mem_cat => ->. Qed. Lemma sumn_flatten (ss : seq (seq nat)) : sumn (flatten ss) = sumn (map sumn ss). Proof. by elim: ss => // s ss /= <-; apply: sumn_cat. Qed. Lemma map_reshape T S (f : T -> S) sh s : map (map f) (reshape sh s) = reshape sh (map f s). Proof. by elim: sh s => //= sh0 sh IHsh s; rewrite map_take IHsh map_drop. Qed. Section EqFlatten. Variables S T : eqType. Lemma flattenP (A : seq (seq T)) x : reflect (exists2 s, s \in A & x \in s) (x \in flatten A). Proof. elim: A => /= [|s A IH_A]; [by right; case | rewrite mem_cat]. by apply: equivP (iff_sym exists_cons); apply: (orPP idP IH_A). Qed. Arguments flattenP {A x}. Lemma flatten_mapP (A : S -> seq T) s y : reflect (exists2 x, x \in s & y \in A x) (y \in flatten (map A s)). Proof. apply: (iffP flattenP) => [[_ /mapP[x sx ->]] | [x sx]] Axy; first by exists x. by exists (A x); rewrite ?map_f. Qed. Lemma perm_flatten (ss1 ss2 : seq (seq T)) : perm_eq ss1 ss2 -> perm_eq (flatten ss1) (flatten ss2). Proof. move=> eq_ss; apply/permP=> a; apply/catCA_perm_subst: ss1 ss2 eq_ss. by move=> ss1 ss2 ss3; rewrite !flatten_cat !count_cat addnCA. Qed. End EqFlatten. Arguments flattenP {T A x}. Arguments flatten_mapP {S T A s y}. Notation "[ 'seq' E | x <- s , y <- t ]" := (flatten [seq [seq E | y <- t] | x <- s]) (x binder, y binder, format "[ '[hv' 'seq' E '/ ' | x <- s , '/ ' y <- t ] ']'") : seq_scope. Notation "[ 'seq' E : R | x <- s , y <- t ]" := (flatten [seq [seq E : R | y <- t] | x <- s]) (x binder, y binder, only parsing) : seq_scope. Section PrefixSuffixInfix. Variables T : eqType. Implicit Type s : seq T. Fixpoint prefix s1 s2 {struct s2} := if s1 isn't x :: s1' then true else if s2 isn't y :: s2' then false else (x == y) && prefix s1' s2'. Lemma prefixE s1 s2 : prefix s1 s2 = (take (size s1) s2 == s1). Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => ->; rewrite eq_sym. Qed. Lemma prefix_refl s : prefix s s. Proof. by rewrite prefixE take_size. Qed. Lemma prefixs0 s : prefix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma prefix0s s : prefix [::] s. Proof. by case: s. Qed. Lemma prefix_cons s1 s2 x y : prefix (x :: s1) (y :: s2) = (x == y) && prefix s1 s2. Proof. by []. Qed. Lemma prefix_catr s1 s2 s1' s3 : size s1 = size s1' -> prefix (s1 ++ s2) (s1' ++ s3) = (s1 == s1') && prefix s2 s3. Proof. elim: s1 s1' => [|x s1 IHs1] [|y s1']//= [eqs1]. by rewrite IHs1// eqseq_cons andbA. Qed. Lemma prefix_prefix s1 s2 : prefix s1 (s1 ++ s2). Proof. by rewrite prefixE take_cat ltnn subnn take0 cats0. Qed. Hint Resolve prefix_prefix : core. Lemma prefixP {s1 s2} : reflect (exists s2' : seq T, s2 = s1 ++ s2') (prefix s1 s2). Proof. apply: (iffP idP) => [|[{}s2 ->]]; last exact: prefix_prefix. by rewrite prefixE => /eqP<-; exists (drop (size s1) s2); rewrite cat_take_drop. Qed. Lemma prefix_trans : transitive prefix. Proof. by move=> _ s2 _ /prefixP[s1 ->] /prefixP[s3 ->]; rewrite -catA. Qed. Lemma prefixs1 s x : prefix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by case: s => //= y s; rewrite prefixs0 eqseq_cons. Qed. Lemma catl_prefix s1 s2 s3 : prefix (s1 ++ s3) s2 -> prefix s1 s2. Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_catl s1 s2 s3 : prefix s1 s2 -> prefix s1 (s2 ++ s3). Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_rcons s x : prefix s (rcons s x). Proof. by rewrite -cats1 prefix_prefix. Qed. Definition suffix s1 s2 := prefix (rev s1) (rev s2). Lemma suffixE s1 s2 : suffix s1 s2 = (drop (size s2 - size s1) s2 == s1). Proof. by rewrite /suffix prefixE take_rev (can_eq revK) size_rev. Qed. Lemma suffix_refl s : suffix s s. Proof. exact: prefix_refl. Qed. Lemma suffixs0 s : suffix s [::] = (s == [::]). Proof. by rewrite /suffix prefixs0 -!nilpE rev_nilp. Qed. Lemma suffix0s s : suffix [::] s. Proof. exact: prefix0s. Qed. Lemma prefix_rev s1 s2 : prefix (rev s1) (rev s2) = suffix s1 s2. Proof. by []. Qed. Lemma prefix_revLR s1 s2 : prefix (rev s1) s2 = suffix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_rev s1 s2 : suffix (rev s1) (rev s2) = prefix s1 s2. Proof. by rewrite -prefix_rev !revK. Qed. Lemma suffix_revLR s1 s2 : suffix (rev s1) s2 = prefix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_suffix s1 s2 : suffix s2 (s1 ++ s2). Proof. by rewrite /suffix rev_cat prefix_prefix. Qed. Hint Resolve suffix_suffix : core. Lemma suffixP {s1 s2} : reflect (exists s2' : seq T, s2 = s2' ++ s1) (suffix s1 s2). Proof. apply: (iffP prefixP) => [[s2' rev_s2]|[s2' ->]]; exists (rev s2'); last first. by rewrite rev_cat. by rewrite -[s2]revK rev_s2 rev_cat revK. Qed. Lemma suffix_trans : transitive suffix. Proof. by move=> _ s2 _ /suffixP[s1 ->] /suffixP[s3 ->]; rewrite catA. Qed. Lemma suffix_rcons s1 s2 x y : suffix (rcons s1 x) (rcons s2 y) = (x == y) && suffix s1 s2. Proof. by rewrite /suffix 2!rev_rcons prefix_cons. Qed. Lemma suffix_catl s1 s2 s3 s3' : size s3 = size s3' -> suffix (s1 ++ s3) (s2 ++ s3') = (s3 == s3') && suffix s1 s2. Proof. by move=> eqs3; rewrite /suffix !rev_cat prefix_catr ?size_rev// (can_eq revK). Qed. Lemma suffix_catr s1 s2 s3 : suffix s1 s2 -> suffix s1 (s3 ++ s2). Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma catl_suffix s s1 s2 : suffix (s ++ s1) s2 -> suffix s1 s2. Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma suffix_cons s x : suffix s (x :: s). Proof. by rewrite /suffix rev_cons prefix_rcons. Qed. Fixpoint infix s1 s2 := if s2 is y :: s2' then prefix s1 s2 || infix s1 s2' else s1 == [::]. Fixpoint infix_index s1 s2 := if prefix s1 s2 then 0 else if s2 is y :: s2' then (infix_index s1 s2').+1 else 1. Lemma infix0s s : infix [::] s. Proof. by case: s. Qed. Lemma infixs0 s : infix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma infix_consl s1 y s2 : infix s1 (y :: s2) = prefix s1 (y :: s2) || infix s1 s2. Proof. by []. Qed. Lemma infix_indexss s : infix_index s s = 0. Proof. by case: s => //= x s; rewrite eqxx prefix_refl. Qed. Lemma infix_index_le s1 s2 : infix_index s1 s2 <= (size s2).+1. Proof. by elim: s2 => [|x s2'] /=; case: ifP. Qed. Lemma infixTindex s1 s2 : (infix_index s1 s2 <= size s2) = infix s1 s2. Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => <-; case: ifP. Qed. Lemma infixPn s1 s2 : reflect (infix_index s1 s2 = (size s2).+1) (~~ infix s1 s2). Proof. rewrite -infixTindex -ltnNge; apply: (iffP idP) => [s2lt|->//]. by apply/eqP; rewrite eqn_leq s2lt infix_index_le. Qed. Lemma infix_index0s s : infix_index [::] s = 0. Proof. by case: s. Qed. Lemma infix_indexs0 s : infix_index s [::] = (s != [::]). Proof. by case: s. Qed. Lemma infixE s1 s2 : infix s1 s2 = (take (size s1) (drop (infix_index s1 s2) s2) == s1). Proof. elim: s2 s1 => [|y s2 +] [|x s1]//= => -> /=. by case: ifP => // /andP[/eqP-> ps1s2/=]; rewrite eqseq_cons -prefixE eqxx. Qed. Lemma infix_refl s : infix s s. Proof. by rewrite infixE infix_indexss// drop0 take_size. Qed. Lemma prefixW s1 s2 : prefix s1 s2 -> infix s1 s2. Proof. by elim: s2 s1 => [|y s2 IHs2] [|x s1]//=->. Qed. Lemma prefix_infix s1 s2 : infix s1 (s1 ++ s2). Proof. exact: prefixW. Qed. Hint Resolve prefix_infix : core. Lemma infix_infix s1 s2 s3 : infix s2 (s1 ++ s2 ++ s3). Proof. by elim: s1 => //= x s1 ->; rewrite orbT. Qed. Hint Resolve infix_infix : core. Lemma suffix_infix s1 s2 : infix s2 (s1 ++ s2). Proof. by rewrite -[X in s1 ++ X]cats0. Qed. Hint Resolve suffix_infix : core. Lemma infixP {s1 s2} : reflect (exists s s' : seq T, s2 = s ++ s1 ++ s') (infix s1 s2). Proof. apply: (iffP idP) => [|[p [s {s2}->]]]//=; rewrite infixE => /eqP<-. set k := infix_index _ _; exists (take k s2), (drop (size s1 + k) s2). by rewrite -drop_drop !cat_take_drop. Qed. Lemma infix_rev s1 s2 : infix (rev s1) (rev s2) = infix s1 s2. Proof. gen have sr : s1 s2 / infix s1 s2 -> infix (rev s1) (rev s2); last first. by apply/idP/idP => /sr; rewrite ?revK. by move=> /infixP[s [p ->]]; rewrite !rev_cat -catA. Qed. Lemma suffixW s1 s2 : suffix s1 s2 -> infix s1 s2. Proof. by rewrite -infix_rev; apply: prefixW. Qed. Lemma infix_trans : transitive infix. Proof. move=> s s1 s2 /infixP[s1p [s1s def_s]] /infixP[sp [ss def_s2]]. by apply/infixP; exists (sp ++ s1p),(s1s ++ ss); rewrite def_s2 def_s -!catA. Qed. Lemma infix_revLR s1 s2 : infix (rev s1) s2 = infix s1 (rev s2). Proof. by rewrite -infix_rev revK. Qed. Lemma infix_rconsl s1 s2 y : infix s1 (rcons s2 y) = suffix s1 (rcons s2 y) || infix s1 s2. Proof. rewrite -infix_rev rev_rcons infix_consl. by rewrite -rev_rcons prefix_rev infix_rev. Qed. Lemma infix_cons s x : infix s (x :: s). Proof. by rewrite -cat1s suffix_infix. Qed. Lemma infixs1 s x : infix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by rewrite infix_consl prefixs1 orbC orbA orbb. Qed. Lemma catl_infix s s1 s2 : infix (s ++ s1) s2 -> infix s1 s2. Proof. apply: infix_trans; exact/suffixW/suffix_suffix. Qed. Lemma catr_infix s s1 s2 : infix (s1 ++ s) s2 -> infix s1 s2. Proof. by rewrite -infix_rev rev_cat => /catl_infix; rewrite infix_rev. Qed. Lemma cons2_infix s1 s2 x : infix (x :: s1) (x :: s2) -> infix s1 s2. Proof. by rewrite /= eqxx /= -cat1s => /orP[/prefixW//|]; exact: catl_infix. Qed. Lemma rcons2_infix s1 s2 x : infix (rcons s1 x) (rcons s2 x) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_rcons => /cons2_infix; rewrite infix_rev. Qed. Lemma catr2_infix s s1 s2 : infix (s ++ s1) (s ++ s2) -> infix s1 s2. Proof. by elim: s => //= x s IHs /cons2_infix. Qed. Lemma catl2_infix s s1 s2 : infix (s1 ++ s) (s2 ++ s) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_cat => /catr2_infix; rewrite infix_rev. Qed. Lemma infix_catl s1 s2 s3 : infix s1 s2 -> infix s1 (s3 ++ s2). Proof. by move=> is12; apply: infix_trans is12 (suffix_infix _ _). Qed. Lemma infix_catr s1 s2 s3 : infix s1 s2 -> infix s1 (s2 ++ s3). Proof. case: s3 => [|x s /infixP [p [sf]] ->]; first by rewrite cats0. by rewrite -catA; apply: infix_catl; rewrite -catA prefix_infix. Qed. Lemma prefix_infix_trans s2 s1 s3 : prefix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW/infix_trans; apply. Qed. Lemma suffix_infix_trans s2 s1 s3 : suffix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW/infix_trans; apply. Qed. Lemma infix_prefix_trans s2 s1 s3 : infix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> + /prefixW; apply: infix_trans. Qed. Lemma infix_suffix_trans s2 s1 s3 : infix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> + /suffixW; apply: infix_trans. Qed. Lemma prefix_suffix_trans s2 s1 s3 : prefix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW + /suffixW +; apply: infix_trans. Qed. Lemma suffix_prefix_trans s2 s1 s3 : suffix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW + /prefixW +; apply: infix_trans. Qed. Lemma infixW s1 s2 : infix s1 s2 -> subseq s1 s2. Proof. move=> /infixP[sp [ss ->]]. exact: subseq_trans (prefix_subseq _ _) (suffix_subseq _ _). Qed. Lemma mem_infix s1 s2 : infix s1 s2 -> {subset s1 <= s2}. Proof. by move=> /infixW subH; apply: mem_subseq. Qed. Lemma infix1s s x : infix [:: x] s = (x \in s). Proof. by elim: s => // x' s /= ->; rewrite in_cons prefix0s andbT. Qed. Lemma prefix1s s x : prefix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /prefixW. Qed. Lemma suffix1s s x : suffix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /suffixW. Qed. Lemma infix_rcons s x : infix s (rcons s x). Proof. by rewrite -cats1 prefix_infix. Qed. Lemma infix_uniq s1 s2 : infix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /infixW /subseq_uniq subH. Qed. Lemma prefix_uniq s1 s2 : prefix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /prefixW /infix_uniq preH. Qed. Lemma suffix_uniq s1 s2 : suffix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /suffixW /infix_uniq preH. Qed. Lemma prefix_take s i : prefix (take i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma suffix_drop s i : suffix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma infix_take s i : infix (take i s) s. Proof. by rewrite prefixW // prefix_take. Qed. Lemma prefix_drop_gt0 s i : ~~ prefix (drop i s) s -> i > 0. Proof. by case: i => //=; rewrite drop0 ltnn prefix_refl. Qed. Lemma infix_drop s i : infix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma consr_infix s1 s2 x : infix (x :: s1) s2 -> infix [:: x] s2. Proof. by rewrite -cat1s => /catr_infix. Qed. Lemma consl_infix s1 s2 x : infix (x :: s1) s2 -> infix s1 s2. Proof. by rewrite -cat1s => /catl_infix. Qed. Lemma prefix_index s1 s2 : prefix s1 s2 -> infix_index s1 s2 = 0. Proof. by case: s1 s2 => [|x s1] [|y s2] //= ->. Qed. Lemma size_infix s1 s2 : infix s1 s2 -> size s1 <= size s2. Proof. by move=> /infixW; apply: size_subseq. Qed. Lemma size_prefix s1 s2 : prefix s1 s2 -> size s1 <= size s2. Proof. by move=> /prefixW; apply: size_infix. Qed. Lemma size_suffix s1 s2 : suffix s1 s2 -> size s1 <= size s2. Proof. by move=> /suffixW; apply: size_infix. Qed. End PrefixSuffixInfix. Section AllPairsDep. Variables (S S' : Type) (T T' : S -> Type) (R : Type). Implicit Type f : forall x, T x -> R. Definition allpairs_dep f s t := [seq f x y | x <- s, y <- t x]. Lemma size_allpairs_dep f s t : size [seq f x y | x <- s, y <- t x] = sumn [seq size (t x) | x <- s]. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. Lemma allpairs0l f t : [seq f x y | x <- [::], y <- t x] = [::]. Proof. by []. Qed. Lemma allpairs0r f s : [seq f x y | x <- s, y <- [::]] = [::]. Proof. by elim: s. Qed. Lemma allpairs1l f x t : [seq f x y | x <- [:: x], y <- t x] = [seq f x y | y <- t x]. Proof. exact: cats0. Qed. Lemma allpairs1r f s y : [seq f x y | x <- s, y <- [:: y x]] = [seq f x (y x) | x <- s]. Proof. exact: flatten_map1. Qed. Lemma allpairs_cons f x s t : [seq f x y | x <- x :: s, y <- t x] = [seq f x y | y <- t x] ++ [seq f x y | x <- s, y <- t x]. Proof. by []. Qed. Lemma eq_allpairs (f1 f2 : forall x, T x -> R) s t : (forall x, f1 x =1 f2 x) -> [seq f1 x y | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. by move=> eq_f; under eq_map do under eq_map do rewrite eq_f. Qed. Lemma eq_allpairsr (f : forall x, T x -> R) s t1 t2 : (forall x, t1 x = t2 x) -> [seq f x y | x <- s, y <- t1 x] = [seq f x y | x <- s, y <- t2 x]. Proof. by move=> eq_t; under eq_map do rewrite eq_t. Qed. Lemma allpairs_cat f s1 s2 t : [seq f x y | x <- s1 ++ s2, y <- t x] = [seq f x y | x <- s1, y <- t x] ++ [seq f x y | x <- s2, y <- t x]. Proof. by rewrite map_cat flatten_cat. Qed. Lemma allpairs_rcons f x s t : [seq f x y | x <- rcons s x, y <- t x] = [seq f x y | x <- s, y <- t x] ++ [seq f x y | y <- t x]. Proof. by rewrite -cats1 allpairs_cat allpairs1l. Qed. Lemma allpairs_mapl f (g : S' -> S) s t : [seq f x y | x <- map g s, y <- t x] = [seq f (g x) y | x <- s, y <- t (g x)]. Proof. by rewrite -map_comp. Qed. Lemma allpairs_mapr f (g : forall x, T' x -> T x) s t : [seq f x y | x <- s, y <- map (g x) (t x)] = [seq f x (g x y) | x <- s, y <- t x]. Proof. by under eq_map do rewrite -map_comp. Qed. End AllPairsDep. Arguments allpairs_dep {S T R} f s t /. Lemma map_allpairs S T R R' (g : R' -> R) f s t : map g [seq f x y | x : S <- s, y : T x <- t x] = [seq g (f x y) | x <- s, y <- t x]. Proof. by rewrite map_flatten allpairs_mapl allpairs_mapr. Qed. Section AllPairsNonDep. Variables (S T R : Type) (f : S -> T -> R). Implicit Types (s : seq S) (t : seq T). Definition allpairs s t := [seq f x y | x <- s, y <- t]. Lemma size_allpairs s t : size [seq f x y | x <- s, y <- t] = size s * size t. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. End AllPairsNonDep. Arguments allpairs {S T R} f s t /. Section EqAllPairsDep. Variables (S : eqType) (T : S -> eqType). Implicit Types (R : eqType) (s : seq S) (t : forall x, seq (T x)). Lemma allpairsPdep R (f : forall x, T x -> R) s t (z : R) : reflect (exists x y, [/\ x \in s, y \in t x & z = f x y]) (z \in [seq f x y | x <- s, y <- t x]). Proof. apply: (iffP flatten_mapP); first by case=> x sx /mapP[y ty ->]; exists x, y. by case=> x [y [sx ty ->]]; exists x; last apply: map_f. Qed. Variable R : eqType. Implicit Type f : forall x, T x -> R. Lemma allpairs_f_dep f s t x y : x \in s -> y \in t x -> f x y \in [seq f x y | x <- s, y <- t x]. Proof. by move=> sx ty; apply/allpairsPdep; exists x, y. Qed. Lemma eq_in_allpairs_dep f1 f2 s t : {in s, forall x, {in t x, f1 x =1 f2 x}} <-> [seq f1 x y : R | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. split=> [eq_f | eq_fst x s_x]. by congr flatten; apply/eq_in_map=> x s_x; apply/eq_in_map/eq_f. apply/eq_in_map; apply/eq_in_map: x s_x; apply/eq_from_flatten_shape => //. by rewrite /shape -!map_comp; apply/eq_map=> x /=; rewrite !size_map. Qed. Lemma perm_allpairs_dep f s1 t1 s2 t2 : perm_eq s1 s2 -> {in s1, forall x, perm_eq (t1 x) (t2 x)} -> perm_eq [seq f x y | x <- s1, y <- t1 x] [seq f x y | x <- s2, y <- t2 x]. Proof. elim: s1 s2 t1 t2 => [s2 t1 t2 |a s1 IH s2 t1 t2 perm_s2 perm_t1]. by rewrite perm_sym => /perm_nilP->. have mem_a : a \in s2 by rewrite -(perm_mem perm_s2) inE eqxx. rewrite -[s2](cat_take_drop (index a s2)). rewrite allpairs_cat (drop_nth a) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC -catA perm_cat //; last first. rewrite perm_catC -allpairs_cat. rewrite -remE perm_sym IH // => [|x xI]; last first. by apply: perm_t1; rewrite inE xI orbT. by rewrite -(perm_cons a) (perm_trans perm_s2 (perm_to_rem _)). have /perm_t1 : a \in a :: s1 by rewrite inE eqxx. rewrite perm_sym; elim: (t2 a) (t1 a) => /= [s4|b s3 IH1 s4 perm_s4]. by rewrite perm_sym => /perm_nilP->. have mem_b : b \in s4 by rewrite -(perm_mem perm_s4) inE eqxx. rewrite -[s4](cat_take_drop (index b s4)). rewrite map_cat /= (drop_nth b) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC /= perm_cons // perm_catC -map_cat. rewrite -remE perm_sym IH1 // -(perm_cons b). by apply: perm_trans perm_s4 (perm_to_rem _). Qed. Lemma mem_allpairs_dep f s1 t1 s2 t2 : s1 =i s2 -> {in s1, forall x, t1 x =i t2 x} -> [seq f x y | x <- s1, y <- t1 x] =i [seq f x y | x <- s2, y <- t2 x]. Proof. move=> eq_s eq_t z; apply/allpairsPdep/allpairsPdep=> -[x [y [sx ty ->]]]; by exists x, y; rewrite -eq_s in sx *; rewrite eq_t in ty *. Qed. Lemma allpairs_uniq_dep f s t (st := [seq Tagged T y | x <- s, y <- t x]) : let g (p : {x : S & T x}) : R := f (tag p) (tagged p) in uniq s -> {in s, forall x, uniq (t x)} -> {in st &, injective g} -> uniq [seq f x y | x <- s, y <- t x]. Proof. move=> g Us Ut; rewrite -(map_allpairs g (existT T)) => /map_inj_in_uniq->{f g}. elim: s Us => //= x s IHs /andP[s'x Us] in st Ut *; rewrite {st}cat_uniq. rewrite {}IHs {Us}// ?andbT => [|x1 s_s1]; last exact/Ut/mem_behead. have injT: injective (existT T x) by move=> y z /eqP; rewrite eq_Tagged => /eqP. rewrite (map_inj_in_uniq (in2W injT)) {injT}Ut ?mem_head // has_sym has_map. by apply: contra s'x => /hasP[y _ /allpairsPdep[z [_ [? _ /(congr1 tag)/=->]]]]. Qed. End EqAllPairsDep. Arguments allpairsPdep {S T R f s t z}. Section MemAllPairs. Variables (S : Type) (T : S -> Type) (R : eqType). Implicit Types (f : forall x, T x -> R) (s : seq S). Lemma perm_allpairs_catr f s t1 t2 : perm_eql [seq f x y | x <- s, y <- t1 x ++ t2 x] ([seq f x y | x <- s, y <- t1 x] ++ [seq f x y | x <- s, y <- t2 x]). Proof. apply/permPl; rewrite perm_sym; elim: s => //= x s ihs. by rewrite perm_catACA perm_cat ?map_cat. Qed. Lemma mem_allpairs_catr f s y0 t : [seq f x y | x <- s, y <- y0 x ++ t x] =i [seq f x y | x <- s, y <- y0 x] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_catr. Qed. Lemma perm_allpairs_consr f s y0 t : perm_eql [seq f x y | x <- s, y <- y0 x :: t x] ([seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]). Proof. by apply/permPl; rewrite (perm_allpairs_catr _ _ (fun=> [:: _])) allpairs1r. Qed. Lemma mem_allpairs_consr f s t y0 : [seq f x y | x <- s, y <- y0 x :: t x] =i [seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_consr. Qed. Lemma allpairs_rconsr f s y0 t : perm_eql [seq f x y | x <- s, y <- rcons (t x) (y0 x)] ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. apply/permPl; rewrite -(eq_allpairsr _ _ (fun=> cats1 _ _)). by rewrite perm_allpairs_catr allpairs1r. Qed. Lemma mem_allpairs_rconsr f s t y0 : [seq f x y | x <- s, y <- rcons (t x) (y0 x)] =i ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. exact/perm_mem/permPl/allpairs_rconsr. Qed. End MemAllPairs. Lemma all_allpairsP (S : eqType) (T : S -> eqType) (R : Type) (p : pred R) (f : forall x : S, T x -> R) (s : seq S) (t : forall x : S, seq (T x)) : reflect (forall (x : S) (y : T x), x \in s -> y \in t x -> p (f x y)) (all p [seq f x y | x <- s, y <- t x]). Proof. elim: s => [|x s IHs]; first by constructor. rewrite /= all_cat all_map /preim. apply/(iffP andP)=> [[/allP /= ? ? x' y x'_in_xs]|p_xs_t]. by move: x'_in_xs y => /[1!inE] /predU1P [-> //|? ?]; exact: IHs. split; first by apply/allP => ?; exact/p_xs_t/mem_head. by apply/IHs => x' y x'_in_s; apply: p_xs_t; rewrite inE x'_in_s orbT. Qed. Arguments all_allpairsP {S T R p f s t}. Section EqAllPairs. Variables S T R : eqType. Implicit Types (f : S -> T -> R) (s : seq S) (t : seq T). Lemma allpairsP f s t (z : R) : reflect (exists p, [/\ p.1 \in s, p.2 \in t & z = f p.1 p.2]) (z \in [seq f x y | x <- s, y <- t]). Proof. by apply: (iffP allpairsPdep) => [[x[y]]|[[x y]]]; [exists (x, y)|exists x, y]. Qed. Lemma allpairs_f f s t x y : x \in s -> y \in t -> f x y \in [seq f x y | x <- s, y <- t]. Proof. exact: allpairs_f_dep. Qed. Lemma eq_in_allpairs f1 f2 s t : {in s & t, f1 =2 f2} <-> [seq f1 x y : R | x <- s, y <- t] = [seq f2 x y | x <- s, y <- t]. Proof. split=> [eq_f | /eq_in_allpairs_dep-eq_f x y /eq_f/(_ y)//]. by apply/eq_in_allpairs_dep=> x /eq_f. Qed. Lemma perm_allpairs f s1 t1 s2 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq [seq f x y | x <- s1, y <- t1] [seq f x y | x <- s2, y <- t2]. Proof. by move=> perm_s perm_t; apply: perm_allpairs_dep. Qed. Lemma mem_allpairs f s1 t1 s2 t2 : s1 =i s2 -> t1 =i t2 -> [seq f x y | x <- s1, y <- t1] =i [seq f x y | x <- s2, y <- t2]. Proof. by move=> eq_s eq_t; apply: mem_allpairs_dep. Qed. Lemma allpairs_uniq f s t (st := [seq (x, y) | x <- s, y <- t]) : uniq s -> uniq t -> {in st &, injective (uncurry f)} -> uniq [seq f x y | x <- s, y <- t]. Proof. move=> Us Ut inj_f; rewrite -(map_allpairs (uncurry f) (@pair S T)) -/st. rewrite map_inj_in_uniq // allpairs_uniq_dep {Us Ut st inj_f}//. by apply: in2W => -[x1 y1] [x2 y2] /= [-> ->]. Qed. End EqAllPairs. Arguments allpairsP {S T R f s t z}. Arguments perm_nilP {T s}. Arguments perm_consP {T x s t}. Section AllRel. Variables (T S : Type) (r : T -> S -> bool). Implicit Types (x : T) (y : S) (xs : seq T) (ys : seq S). Definition allrel xs ys := all [pred x | all (r x) ys] xs. Lemma allrel0l ys : allrel [::] ys. Proof. by []. Qed. Lemma allrel0r xs : allrel xs [::]. Proof. by elim: xs. Qed. Lemma allrel_consl x xs ys : allrel (x :: xs) ys = all (r x) ys && allrel xs ys. Proof. by []. Qed. Lemma allrel_consr xs y ys : allrel xs (y :: ys) = all (r^~ y) xs && allrel xs ys. Proof. exact: all_predI. Qed. Lemma allrel_cons2 x y xs ys : allrel (x :: xs) (y :: ys) = [&& r x y, all (r x) ys, all (r^~ y) xs & allrel xs ys]. Proof. by rewrite /= allrel_consr -andbA. Qed. Lemma allrel1l x ys : allrel [:: x] ys = all (r x) ys. Proof. exact: andbT. Qed. Lemma allrel1r xs y : allrel xs [:: y] = all (r^~ y) xs. Proof. by rewrite allrel_consr allrel0r andbT. Qed. Lemma allrel_catl xs xs' ys : allrel (xs ++ xs') ys = allrel xs ys && allrel xs' ys. Proof. exact: all_cat. Qed. Lemma allrel_catr xs ys ys' : allrel xs (ys ++ ys') = allrel xs ys && allrel xs ys'. Proof. elim: ys => /= [|y ys ihys]; first by rewrite allrel0r. by rewrite !allrel_consr ihys andbA. Qed. Lemma allrel_maskl m xs ys : allrel xs ys -> allrel (mask m xs) ys. Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [xys /IHm->]; rewrite ?xys. Qed. Lemma allrel_maskr m xs ys : allrel xs ys -> allrel xs (mask m ys). Proof. by elim: xs => //= x xs IHxs /andP [/all_mask->]. Qed. Lemma allrel_filterl a xs ys : allrel xs ys -> allrel (filter a xs) ys. Proof. by rewrite filter_mask; apply: allrel_maskl. Qed. Lemma allrel_filterr a xs ys : allrel xs ys -> allrel xs (filter a ys). Proof. by rewrite filter_mask; apply: allrel_maskr. Qed. Lemma allrel_allpairsE xs ys : allrel xs ys = all id [seq r x y | x <- xs, y <- ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat all_map. Qed. End AllRel. Arguments allrel {T S} r xs ys : simpl never. Arguments allrel0l {T S} r ys. Arguments allrel0r {T S} r xs. Arguments allrel_consl {T S} r x xs ys. Arguments allrel_consr {T S} r xs y ys. Arguments allrel1l {T S} r x ys. Arguments allrel1r {T S} r xs y. Arguments allrel_catl {T S} r xs xs' ys. Arguments allrel_catr {T S} r xs ys ys'. Arguments allrel_maskl {T S} r m xs ys. Arguments allrel_maskr {T S} r m xs ys. Arguments allrel_filterl {T S} r a xs ys. Arguments allrel_filterr {T S} r a xs ys. Arguments allrel_allpairsE {T S} r xs ys. Notation all2rel r xs := (allrel r xs xs). Lemma sub_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) (r r' : T -> S -> bool) : {in P & Q, forall x y, r x y -> r' x y} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys -> allrel r' xs ys. Proof. move=> rr' + ys; elim=> //= x xs IHxs /andP [Px Pxs] Qys. rewrite !allrel_consl => /andP [+ {}/IHxs-> //]; rewrite andbT. by elim: ys Qys => //= y ys IHys /andP [Qy Qys] /andP [/rr'-> // /IHys->]. Qed. Lemma sub_allrel {T S : Type} (r r' : T -> S -> bool) : (forall x y, r x y -> r' x y) -> forall xs ys, allrel r xs ys -> allrel r' xs ys. Proof. by move=> rr' xs ys; apply/sub_in_allrel/all_predT/all_predT; apply: in2W. Qed. Lemma eq_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) r r' : {in P & Q, r =2 r'} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys = allrel r' xs ys. Proof. move=> rr' xs ys Pxs Qys. by apply/idP/idP; apply/sub_in_allrel/Qys/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_allrel {T S : Type} (r r' : T -> S -> bool) : r =2 r' -> allrel r =2 allrel r'. Proof. by move=> rr' xs ys; apply/eq_in_allrel/all_predT/all_predT. Qed. Lemma allrelC {T S : Type} (r : T -> S -> bool) xs ys : allrel r xs ys = allrel (fun y => r^~ y) ys xs. Proof. by elim: xs => [|x xs ih]; [elim: ys | rewrite allrel_consr -ih]. Qed. Lemma allrel_mapl {T T' S : Type} (f : T' -> T) (r : T -> S -> bool) xs ys : allrel r (map f xs) ys = allrel (fun x => r (f x)) xs ys. Proof. exact: all_map. Qed. Lemma allrel_mapr {T S S' : Type} (f : S' -> S) (r : T -> S -> bool) xs ys : allrel r xs (map f ys) = allrel (fun x y => r x (f y)) xs ys. Proof. by rewrite allrelC allrel_mapl allrelC. Qed. Lemma allrelP {T S : eqType} {r : T -> S -> bool} {xs ys} : reflect {in xs & ys, forall x y, r x y} (allrel r xs ys). Proof. by rewrite allrel_allpairsE; exact: all_allpairsP. Qed. Lemma allrelT {T S : Type} (xs : seq T) (ys : seq S) : allrel (fun _ _ => true) xs ys = true. Proof. by elim: xs => //= ? ?; rewrite allrel_consl all_predT. Qed. Lemma allrel_relI {T S : Type} (r r' : T -> S -> bool) xs ys : allrel (fun x y => r x y && r' x y) xs ys = allrel r xs ys && allrel r' xs ys. Proof. by rewrite -all_predI; apply: eq_all => ?; rewrite /= -all_predI. Qed. Lemma allrel_revl {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) s2 = allrel r s1 s2. Proof. exact: all_rev. Qed. Lemma allrel_revr {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r s1 (rev s2) = allrel r s1 s2. Proof. by rewrite allrelC allrel_revl allrelC. Qed. Lemma allrel_rev2 {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) (rev s2) = allrel r s1 s2. Proof. by rewrite allrel_revr allrel_revl. Qed. Lemma eq_allrel_meml {T : eqType} {S} (r : T -> S -> bool) (s1 s1' : seq T) s2 : s1 =i s1' -> allrel r s1 s2 = allrel r s1' s2. Proof. by move=> eqs1; apply: eq_all_r. Qed. Lemma eq_allrel_memr {T} {S : eqType} (r : T -> S -> bool) s1 (s2 s2' : seq S) : s2 =i s2' -> allrel r s1 s2 = allrel r s1 s2'. Proof. by rewrite ![allrel _ s1 _]allrelC; apply: eq_allrel_meml. Qed. Lemma eq_allrel_mem2 {T S : eqType} (r : T -> S -> bool) (s1 s1' : seq T) (s2 s2' : seq S) : s1 =i s1' -> s2 =i s2' -> allrel r s1 s2 = allrel r s1' s2'. Proof. by move=> /eq_allrel_meml -> /eq_allrel_memr ->. Qed. Section All2Rel. Variable (T : nonPropType) (r : rel T). Implicit Types (x y z : T) (xs : seq T). Hypothesis (rsym : symmetric r). Lemma all2rel1 x : all2rel r [:: x] = r x x. Proof. by rewrite /allrel /= !andbT. Qed. Lemma all2rel2 x y : all2rel r [:: x; y] = r x x && r y y && r x y. Proof. by rewrite /allrel /= rsym; do 3 case: r. Qed. Lemma all2rel_cons x xs : all2rel r (x :: xs) = [&& r x x, all (r x) xs & all2rel r xs]. Proof. rewrite allrel_cons2; congr andb; rewrite andbA -all_predI; congr andb. by elim: xs => //= y xs ->; rewrite rsym andbb. Qed. End All2Rel. Section Pairwise. Variables (T : Type) (r : T -> T -> bool). Implicit Types (x y : T) (xs ys : seq T). Fixpoint pairwise xs : bool := if xs is x :: xs then all (r x) xs && pairwise xs else true. Lemma pairwise_cons x xs : pairwise (x :: xs) = all (r x) xs && pairwise xs. Proof. by []. Qed. Lemma pairwise_cat xs ys : pairwise (xs ++ ys) = [&& allrel r xs ys, pairwise xs & pairwise ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat -!andbA; bool_congr. Qed. Lemma pairwise_rcons xs x : pairwise (rcons xs x) = all (r^~ x) xs && pairwise xs. Proof. by rewrite -cats1 pairwise_cat allrel1r andbT. Qed. Lemma pairwise2 x y : pairwise [:: x; y] = r x y. Proof. by rewrite /= !andbT. Qed. Lemma pairwise_mask m xs : pairwise xs -> pairwise (mask m xs). Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [? ?]; rewrite ?IHm // all_mask. Qed. Lemma pairwise_filter a xs : pairwise xs -> pairwise (filter a xs). Proof. by rewrite filter_mask; apply: pairwise_mask. Qed. Lemma pairwiseP x0 xs : reflect {in gtn (size xs) &, {homo nth x0 xs : i j / i < j >-> r i j}} (pairwise xs). Proof. elim: xs => /= [|x xs IHxs]; first exact: (iffP idP). apply: (iffP andP) => [[r_x_xs pxs] i j|Hnth]; rewrite -?topredE /= ?ltnS. by case: i j => [|i] [|j] //= gti gtj ij; [exact/all_nthP | exact/IHxs]. split; last by apply/IHxs => // i j; apply/(Hnth i.+1 j.+1). by apply/(all_nthP x0) => i gti; apply/(Hnth 0 i.+1). Qed. Lemma pairwise_all2rel : reflexive r -> symmetric r -> forall xs, pairwise xs = all2rel r xs. Proof. by move=> r_refl r_sym; elim => //= x xs ->; rewrite all2rel_cons // r_refl. Qed. End Pairwise. Arguments pairwise {T} r xs. Arguments pairwise_cons {T} r x xs. Arguments pairwise_cat {T} r xs ys. Arguments pairwise_rcons {T} r xs x. Arguments pairwise2 {T} r x y. Arguments pairwise_mask {T r} m {xs}. Arguments pairwise_filter {T r} a {xs}. Arguments pairwiseP {T r} x0 {xs}. Arguments pairwise_all2rel {T r} r_refl r_sym xs. Lemma sub_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, subrel r r'} -> forall xs, all P xs -> pairwise r xs -> pairwise r' xs. Proof. move=> rr'; elim=> //= x xs IHxs /andP [Px Pxs] /andP [+ {}/IHxs->] //. rewrite andbT; elim: xs Pxs => //= x' xs IHxs /andP [? ?] /andP [+ /IHxs->] //. by rewrite andbT; apply: rr'. Qed. Lemma sub_pairwise {T : Type} (r r' : rel T) xs : subrel r r' -> pairwise r xs -> pairwise r' xs. Proof. by move=> rr'; apply/sub_in_pairwise/all_predT; apply: in2W. Qed. Lemma eq_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, r =2 r'} -> forall xs, all P xs -> pairwise r xs = pairwise r' xs. Proof. move=> rr' xs Pxs. by apply/idP/idP; apply/sub_in_pairwise/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_pairwise {T : Type} (r r' : rel T) : r =2 r' -> pairwise r =i pairwise r'. Proof. by move=> rr' xs; apply/eq_in_pairwise/all_predT. Qed. Lemma pairwise_map {T T' : Type} (f : T' -> T) (r : rel T) xs : pairwise r (map f xs) = pairwise (relpre f r) xs. Proof. by elim: xs => //= x xs ->; rewrite all_map. Qed. Lemma pairwise_relI {T : Type} (r r' : rel T) (s : seq T) : pairwise [rel x y | r x y && r' x y] s = pairwise r s && pairwise r' s. Proof. by elim: s => //= x s ->; rewrite andbACA all_predI. Qed. Section EqPairwise. Variables (T : eqType) (r : T -> T -> bool). Implicit Types (xs ys : seq T). Lemma subseq_pairwise xs ys : subseq xs ys -> pairwise r ys -> pairwise r xs. Proof. by case/subseqP => m _ ->; apply: pairwise_mask. Qed. Lemma uniq_pairwise xs : uniq xs = pairwise [rel x y | x != y] xs. Proof. elim: xs => //= x xs ->; congr andb; rewrite -has_pred1 -all_predC. by elim: xs => //= x' xs ->; case: eqVneq. Qed. Lemma pairwise_uniq xs : irreflexive r -> pairwise r xs -> uniq xs. Proof. move=> r_irr; rewrite uniq_pairwise; apply/sub_pairwise => x y. by apply: contraTneq => ->; rewrite r_irr. Qed. Lemma pairwise_eq : antisymmetric r -> forall xs ys, pairwise r xs -> pairwise r ys -> perm_eq xs ys -> xs = ys. Proof. move=> r_asym; elim=> [|x xs IHxs] [|y ys] //=; try by move=> ? ? /perm_size. move=> /andP [r_x_xs pxs] /andP [r_y_ys pys] eq_xs_ys. move: (mem_head y ys) (mem_head x xs). rewrite -(perm_mem eq_xs_ys) [x \in _](perm_mem eq_xs_ys) !inE. case: eqVneq eq_xs_ys => /= [->|ne_xy] eq_xs_ys ys_x xs_y. by rewrite (IHxs ys) // -(perm_cons x). by case/eqP: ne_xy; apply: r_asym; rewrite (allP r_x_xs) ?(allP r_y_ys). Qed. Lemma pairwise_trans s : antisymmetric r -> pairwise r s -> {in s & &, transitive r}. Proof. move=> /(_ _ _ _)/eqP r_anti + y x z => /pairwiseP-/(_ y) ltP ys xs zs. have [-> //|neqxy] := eqVneq x y; have [-> //|neqzy] := eqVneq z y. move=> lxy lyz; move: ys xs zs lxy neqxy lyz neqzy. move=> /(nthP y)[j jlt <-] /(nthP y)[i ilt <-] /(nthP y)[k klt <-]. have [ltij|ltji|->] := ltngtP i j; last 2 first. - by move=> leij; rewrite r_anti// leij ltP. - by move=> lejj; rewrite r_anti// lejj. move=> _ _; have [ltjk|ltkj|->] := ltngtP j k; last 2 first. - by move=> lejk; rewrite r_anti// lejk ltP. - by move=> lekk; rewrite r_anti// lekk. by move=> _ _; apply: (ltP) => //; apply: ltn_trans ltjk. Qed. End EqPairwise. Arguments subseq_pairwise {T r xs ys}. Arguments uniq_pairwise {T} xs. Arguments pairwise_uniq {T r xs}. Arguments pairwise_eq {T r} r_asym {xs ys}. Section Permutations. Variable T : eqType. Implicit Types (x : T) (s t : seq T) (bs : seq (T * nat)) (acc : seq (seq T)). Fixpoint incr_tally bs x := if bs isn't b :: bs then [:: (x, 1)] else if x == b.1 then (x, b.2.+1) :: bs else b :: incr_tally bs x. Definition tally s := foldl incr_tally [::] s. Definition wf_tally := [qualify a bs : seq (T * nat) | uniq (unzip1 bs) && (0 \notin unzip2 bs)]. Definition tally_seq bs := flatten [seq nseq b.2 b.1 | b <- bs]. Local Notation tseq := tally_seq. Lemma size_tally_seq bs : size (tally_seq bs) = sumn (unzip2 bs). Proof. by rewrite size_flatten /shape -map_comp; under eq_map do rewrite /= size_nseq. Qed. Lemma tally_seqK : {in wf_tally, cancel tally_seq tally}. Proof. move=> bs /andP[]; elim: bs => [|[x [|n]] bs IHbs] //= /andP[bs'x Ubs] bs'0. rewrite inE /tseq /tally /= -[n.+1]addn1 in bs'0 *. elim: n 1 => /= [|n IHn] m; last by rewrite eqxx IHn addnS. rewrite -{}[in RHS]IHbs {Ubs bs'0}// /tally /tally_seq add0n. elim: bs bs'x [::] => [|[y n] bs IHbs] //= /[1!inE] /norP[y'x bs'x]. by elim: n => [|n IHn] bs1 /=; [rewrite IHbs | rewrite eq_sym ifN // IHn]. Qed. Lemma incr_tallyP x : {homo incr_tally^~ x : bs / bs \in wf_tally}. Proof. move=> bs /andP[]; rewrite unfold_in. elim: bs => [|[y [|n]] bs IHbs] //= /andP[bs'y Ubs] /[1!inE] /= bs'0. have [<- | y'x] /= := eqVneq y; first by rewrite bs'y Ubs. rewrite -andbA {}IHbs {Ubs bs'0}// andbT. elim: bs bs'y => [|b bs IHbs] /=; rewrite inE ?y'x // => /norP[b'y bs'y]. by case: ifP => _; rewrite /= inE negb_or ?y'x // b'y IHbs. Qed. Lemma tallyP s : tally s \is a wf_tally. Proof. rewrite /tally; set bs := [::]; have: bs \in wf_tally by []. by elim: s bs => //= x s IHs bs /(incr_tallyP x)/IHs. Qed. Lemma tallyK s : perm_eq (tally_seq (tally s)) s. Proof. rewrite -[s in perm_eq _ s]cats0 -[nil]/(tseq [::]) /tally. elim: s [::] => //= x s IHs bs; rewrite {IHs}(permPl (IHs _)). rewrite perm_sym -cat1s perm_catCA {s}perm_cat2l. elim: bs => //= b bs IHbs; case: eqP => [-> | _] //=. by rewrite -cat1s perm_catCA perm_cat2l. Qed. Lemma tallyEl s : perm_eq (unzip1 (tally s)) (undup s). Proof. have /andP[Ubs bs'0] := tallyP s; set bs := tally s in Ubs bs'0 *. rewrite uniq_perm ?undup_uniq {Ubs}// => x. rewrite mem_undup -(perm_mem (tallyK s)) -/bs. elim: bs => [|[y [|m]] bs IHbs] //= in bs'0 *. by rewrite inE IHbs // mem_cat mem_nseq. Qed. Lemma tallyE s : perm_eq (tally s) [seq (x, count_mem x s) | x <- undup s]. Proof. have /andP[Ubs _] := tallyP s; pose b := [fun s x => (x, count_mem x (tseq s))]. suffices /permPl->: perm_eq (tally s) (map (b (tally s)) (unzip1 (tally s))). congr perm_eq: (perm_map (b (tally s)) (tallyEl s)). by under eq_map do rewrite /= (permP (tallyK s)). elim: (tally s) Ubs => [|[x m] bs IH] //= /andP[bs'x /IH-IHbs {IH}]. rewrite /tseq /= -/(tseq _) count_cat count_nseq /= eqxx mul1n. rewrite (count_memPn _) ?addn0 ?perm_cons; last first. apply: contra bs'x; elim: {b IHbs}bs => //= b bs IHbs. by rewrite mem_cat mem_nseq inE andbC; case: (_ == _). congr perm_eq: IHbs; apply/eq_in_map=> y bs_y; congr (y, _). by rewrite count_cat count_nseq /= (negPf (memPnC bs'x y bs_y)). Qed. Lemma perm_tally s1 s2 : perm_eq s1 s2 -> perm_eq (tally s1) (tally s2). Proof. move=> eq_s12; apply: (@perm_trans _ [seq (x, count_mem x s2) | x <- undup s1]). by congr perm_eq: (tallyE s1); under eq_map do rewrite (permP eq_s12). by rewrite (permPr (tallyE s2)); apply/perm_map/perm_undup/(perm_mem eq_s12). Qed. Lemma perm_tally_seq bs1 bs2 : perm_eq bs1 bs2 -> perm_eq (tally_seq bs1) (tally_seq bs2). Proof. by move=> Ebs12; rewrite perm_flatten ?perm_map. Qed. Local Notation perm_tseq := perm_tally_seq. Lemma perm_count_undup s : perm_eq (flatten [seq nseq (count_mem x s) x | x <- undup s]) s. Proof. by rewrite -(permPr (tallyK s)) (permPr (perm_tseq (tallyE s))) /tseq -map_comp. Qed. Local Fixpoint cons_perms_ perms_rec (s : seq T) bs bs2 acc := if bs isn't b :: bs1 then acc else if b isn't (x, m.+1) then cons_perms_ perms_rec s bs1 bs2 acc else let acc_xs := perms_rec (x :: s) ((x, m) :: bs1 ++ bs2) acc in cons_perms_ perms_rec s bs1 (b :: bs2) acc_xs. Local Fixpoint perms_rec n s bs acc := if n isn't n.+1 then s :: acc else cons_perms_ (perms_rec n) s bs [::] acc. Local Notation cons_perms n := (cons_perms_ (perms_rec n) [::]). Definition permutations s := perms_rec (size s) [::] (tally s) [::]. Let permsP s : exists n bs, [/\ permutations s = perms_rec n [::] bs [::], size (tseq bs) == n, perm_eq (tseq bs) s & uniq (unzip1 bs)]. Proof. have /andP[Ubs _] := tallyP s; exists (size s), (tally s). by rewrite (perm_size (tallyK s)) tallyK. Qed. Local Notation bsCA := (permEl (perm_catCA _ [:: _] _)). Let cons_permsE : forall n x bs bs1 bs2, let cp := cons_perms n bs bs2 in let perms s := perms_rec n s bs1 [::] in cp (perms [:: x]) = cp [::] ++ [seq rcons t x | t <- perms [::]]. Proof. pose is_acc f := forall acc, f acc = f [::] ++ acc. (* f is accumulating. *) have cpE: forall f & forall s bs, is_acc (f s bs), is_acc (cons_perms_ f _ _ _). move=> s bs bs2 f fE acc; elim: bs => [|[x [|m]] bs IHbs] //= in s bs2 acc *. by rewrite fE IHbs catA -IHbs. have prE: is_acc (perms_rec _ _ _) by elim=> //= n IHn s bs; apply: cpE. pose has_suffix f := forall s : seq T, f s = [seq t ++ s | t <- f [::]]. suffices prEs n bs: has_suffix (fun s => perms_rec n s bs [::]). move=> n x bs bs1 bs2 /=; rewrite cpE // prEs. by under eq_map do rewrite cats1. elim: n bs => //= n IHn bs s; elim: bs [::] => [|[x [|m]] bs IHbs] //= bs1. rewrite cpE // IHbs IHn [in RHS]cpE // [in RHS]IHn map_cat -map_comp. by congr (_ ++ _); apply: eq_map => t /=; rewrite -catA. Qed. Lemma mem_permutations s t : (t \in permutations s) = perm_eq t s. Proof. have{s} [n [bs [-> Dn /permPr<- _]]] := permsP s. elim: n => [|n IHn] /= in t bs Dn *. by rewrite inE (nilP Dn); apply/eqP/perm_nilP. rewrite -[bs in tseq bs]cats0 in Dn *; have x0 : T by case: (tseq _) Dn. rewrite -[RHS](@andb_idl (last x0 t \in tseq bs)); last first. case/lastP: t {IHn} => [|t x] Dt; first by rewrite -(perm_size Dt) in Dn. by rewrite -[bs]cats0 -(perm_mem Dt) last_rcons mem_rcons mem_head. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn *. rewrite cons_permsE -!cat_cons !mem_cat (mem_nseq m.+1) orbC andb_orl. rewrite {}IHbs ?(perm_size (perm_tseq bsCA)) //= (permPr (perm_tseq bsCA)). congr (_ || _); apply/mapP/andP=> [[t1 Dt1 ->] | [/eqP]]. by rewrite last_rcons perm_rcons perm_cons IHn in Dt1 *. case/lastP: t => [_ /perm_size//|t y]; rewrite last_rcons perm_rcons => ->. by rewrite perm_cons; exists t; rewrite ?IHn. Qed. Lemma permutations_uniq s : uniq (permutations s). Proof. have{s} [n [bs [-> Dn _ Ubs]]] := permsP s. elim: n => //= n IHn in bs Dn Ubs *; rewrite -[bs]cats0 /unzip1 in Dn Ubs. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn Ubs *. by case/andP: Ubs => _ /IHbs->. rewrite /= cons_permsE cat_uniq has_sym andbCA andbC. rewrite {}IHbs; first 1 last; first by rewrite (perm_size (perm_tseq bsCA)). by rewrite (perm_uniq (perm_map _ bsCA)). rewrite (map_inj_uniq (rcons_injl x)) {}IHn {Dn}//=. have: x \notin unzip1 bs by apply: contraL Ubs; rewrite map_cat mem_cat => ->. move: {bs2 m Ubs}(perms_rec n _ _ _) (_ :: bs2) => ts. elim: bs => [|[y [|m]] bs IHbs] //= /[1!inE] bs2 /norP[x'y /IHbs//]. rewrite cons_permsE has_cat negb_or has_map => ->. by apply/hasPn=> t _; apply: contra x'y => /mapP[t1 _ /rcons_inj[_ ->]]. Qed. Notation perms := permutations. Lemma permutationsE s : 0 < size s -> perm_eq (perms s) [seq x :: t | x <- undup s, t <- perms (rem x s)]. Proof. move=> nt_s; apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|x _|]; rewrite ?undup_uniq ?permutations_uniq //. by case=> [_ _] [x t] _ _ [-> ->]. rewrite mem_permutations; apply/idP/allpairsPdep=> [Dt | [x [t1 []]]]. rewrite -(perm_size Dt) in nt_s; case: t nt_s => // x t _ in Dt *. have s_x: x \in s by rewrite -(perm_mem Dt) mem_head. exists x, t; rewrite mem_undup mem_permutations; split=> //. by rewrite -(perm_cons x) (permPl Dt) perm_to_rem. rewrite mem_undup mem_permutations -(perm_cons x) => s_x Dt1 ->. by rewrite (permPl Dt1) perm_sym perm_to_rem. Qed. Lemma permutationsErot x s (le_x := fun t => iota 0 (index x t + 1)) : perm_eq (perms (x :: s)) [seq rot i (x :: t) | t <- perms s, i <- le_x t]. Proof. have take'x t i: i <= index x t -> i <= size t /\ x \notin take i t. move=> le_i_x; have le_i_t: i <= size t := leq_trans le_i_x (index_size x t). case: (nthP x) => // -[j lt_j_i /eqP]; rewrite size_takel // in lt_j_i. by rewrite nth_take // [_ == _](before_find x (leq_trans lt_j_i le_i_x)). pose xrot t i := rot i (x :: t); pose xrotV t := index x (rev (rot 1 t)). have xrotK t: {in le_x t, cancel (xrot t) xrotV}. move=> i; rewrite mem_iota addn1 /xrotV => /take'x[le_i_t ti'x]. rewrite -rotD ?rev_cat //= rev_cons cat_rcons index_cat mem_rev size_rev. by rewrite ifN // size_takel //= eqxx addn0. apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|t _|]; rewrite ?permutations_uniq ?iota_uniq //. move=> _ _ /allpairsPdep[t [i [_ ? ->]]] /allpairsPdep[u [j [_ ? ->]]] Etu. have Eij: i = j by rewrite -(xrotK t i) // /xrot Etu xrotK. by move: Etu; rewrite Eij => /rot_inj[->]. rewrite mem_permutations; apply/esym; apply/allpairsPdep/idP=> [[u [i]] | Dt]. rewrite mem_permutations => -[Du _ /(canLR (rotK i))]; rewrite /rotr. by set j := (j in rot j _) => Dt; apply/perm_consP; exists j, u. pose r := rev (rot 1 t); pose i := index x r; pose u := rev (take i r). have r_x: x \in r by rewrite mem_rev mem_rot (perm_mem Dt) mem_head. have [v Duv]: {v | rot i (x :: u ++ v) = t}; first exists (rev (drop i.+1 r)). rewrite -rev_cat -rev_rcons -rot1_cons -cat_cons -(nth_index x r_x). by rewrite -drop_nth ?index_mem // rot_rot !rev_rot revK rotK rotrK. exists (u ++ v), i; rewrite mem_permutations -(perm_cons x) -(perm_rot i) Duv. rewrite mem_iota addn1 ltnS /= index_cat mem_rev size_rev. by have /take'x[le_i_t ti'x] := leqnn i; rewrite ifN ?size_takel ?leq_addr. Qed. Lemma size_permutations s : uniq s -> size (permutations s) = (size s)`!. Proof. move Dn: (size s) => n Us; elim: n s => [[]|n IHn s] //= in Dn Us *. rewrite (perm_size (permutationsE _)) ?Dn // undup_id // factS -Dn. rewrite -(size_iota 0 n`!) -(size_allpairs (fun=>id)) !size_allpairs_dep. by apply/congr1/eq_in_map=> x sx; rewrite size_iota IHn ?size_rem ?Dn ?rem_uniq. Qed. Lemma permutations_all_uniq s : uniq s -> all uniq (permutations s). Proof. by move=> Us; apply/allP=> t; rewrite mem_permutations => /perm_uniq->. Qed. Lemma perm_permutations s t : perm_eq s t -> perm_eq (permutations s) (permutations t). Proof. move=> Est; apply/uniq_perm; try exact: permutations_uniq. by move=> u; rewrite !mem_permutations (permPr Est). Qed. End Permutations.
Range.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kenny Lau, Kim Morrison -/ import Mathlib.Data.List.Chain /-! # Ranges of naturals as lists This file shows basic results about `List.iota`, `List.range`, `List.range'` and defines `List.finRange`. `finRange n` is the list of elements of `Fin n`. `iota n = [n, n - 1, ..., 1]` and `range n = [0, ..., n - 1]` are basic list constructions used for tactics. `range' a b = [a, ..., a + b - 1]` is there to help prove properties about them. Actual maths should use `List.Ico` instead. -/ universe u open Nat namespace List variable {α : Type u} theorem getElem_range'_1 {n m} (i) (H : i < (range' n m).length) : (range' n m)[i] = n + i := by simp theorem chain'_range_succ (r : ℕ → ℕ → Prop) (n : ℕ) : Chain' r (range n.succ) ↔ ∀ m < n, r m m.succ := by rw [range_succ] induction' n with n hn · simp · rw [range_succ] simp only [append_assoc, singleton_append, chain'_append_cons_cons, chain'_singleton, and_true] rw [hn, forall_lt_succ] theorem chain_range_succ (r : ℕ → ℕ → Prop) (n a : ℕ) : Chain r a (range n.succ) ↔ r a 0 ∧ ∀ m < n, r m m.succ := by rw [range_succ_eq_map, chain_cons, and_congr_right_iff, ← chain'_range_succ, range_succ_eq_map] exact fun _ => Iff.rfl section Ranges /-- From `l : List ℕ`, construct `l.ranges : List (List ℕ)` such that `l.ranges.map List.length = l` and `l.ranges.join = range l.sum` * Example: `[1,2,3].ranges = [[0],[1,2],[3,4,5]]` -/ def ranges : List ℕ → List (List ℕ) | [] => nil | a::l => range a::(ranges l).map (map (a + ·)) /-- The members of `l.ranges` are pairwise disjoint -/ theorem ranges_disjoint (l : List ℕ) : Pairwise Disjoint (ranges l) := by induction l with | nil => exact Pairwise.nil | cons a l hl => simp only [ranges, pairwise_cons] constructor · intro s hs obtain ⟨s', _, rfl⟩ := mem_map.mp hs intro u hu rw [mem_map] rintro ⟨v, _, rfl⟩ rw [mem_range] at hu omega · rw [pairwise_map] apply Pairwise.imp _ hl intro u v apply disjoint_map exact fun u v => Nat.add_left_cancel /-- The lengths of the members of `l.ranges` are those given by `l` -/ theorem ranges_length (l : List ℕ) : l.ranges.map length = l := by induction l with | nil => simp only [ranges, map_nil] | cons a l hl => -- (a :: l) simp only [ranges, map_cons, length_range, map_map, cons.injEq, true_and] conv_rhs => rw [← hl] apply map_congr_left intro s _ simp only [Function.comp_apply, length_map] end Ranges end List
AlgebraicCard.lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import Mathlib.Algebra.Polynomial.Cardinal import Mathlib.RingTheory.Algebraic.Basic /-! ### Cardinality of algebraic numbers In this file, we prove variants of the following result: the cardinality of algebraic numbers under an R-algebra is at most `#R[X] * ℵ₀`. Although this can be used to prove that real or complex transcendental numbers exist, a more direct proof is given by `Liouville.transcendental`. -/ universe u v open Cardinal Polynomial Set open Cardinal Polynomial namespace Algebraic theorem infinite_of_charZero (R A : Type*) [CommRing R] [Ring A] [Algebra R A] [CharZero A] : { x : A | IsAlgebraic R x }.Infinite := by letI := MulActionWithZero.nontrivial R A exact infinite_of_injective_forall_mem Nat.cast_injective isAlgebraic_nat theorem aleph0_le_cardinalMk_of_charZero (R A : Type*) [CommRing R] [Ring A] [Algebra R A] [CharZero A] : ℵ₀ ≤ #{ x : A // IsAlgebraic R x } := infinite_iff.1 (Set.infinite_coe_iff.2 <| infinite_of_charZero R A) section lift variable (R : Type u) (A : Type v) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A] [NoZeroSMulDivisors R A] theorem cardinalMk_lift_le_mul : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ Cardinal.lift.{v} #R[X] * ℵ₀ := by rw [← mk_uLift, ← mk_uLift] choose g hg₁ hg₂ using fun x : { x : A | IsAlgebraic R x } => x.coe_prop refine lift_mk_le_lift_mk_mul_of_lift_mk_preimage_le g fun f => ?_ rw [lift_le_aleph0, le_aleph0_iff_set_countable] suffices MapsTo (↑) (g ⁻¹' {f}) (f.rootSet A) from this.countable_of_injOn Subtype.coe_injective.injOn (f.rootSet_finite A).countable rintro x (rfl : g x = f) exact mem_rootSet.2 ⟨hg₁ x, hg₂ x⟩ theorem cardinalMk_lift_le_max : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } ≤ max (Cardinal.lift.{v} #R) ℵ₀ := (cardinalMk_lift_le_mul R A).trans <| (mul_le_mul_right' (lift_le.2 cardinalMk_le_max) _).trans <| by simp @[simp] theorem cardinalMk_lift_of_infinite [Infinite R] : Cardinal.lift.{u} #{ x : A // IsAlgebraic R x } = Cardinal.lift.{v} #R := ((cardinalMk_lift_le_max R A).trans_eq (max_eq_left <| aleph0_le_mk _)).antisymm <| lift_mk_le'.2 ⟨⟨fun x => ⟨algebraMap R A x, isAlgebraic_algebraMap _⟩, fun _ _ h => FaithfulSMul.algebraMap_injective R A (Subtype.ext_iff.1 h)⟩⟩ variable [Countable R] @[simp] protected theorem countable : Set.Countable { x : A | IsAlgebraic R x } := by rw [← le_aleph0_iff_set_countable, ← lift_le_aleph0] apply (cardinalMk_lift_le_max R A).trans simp @[simp] theorem cardinalMk_of_countable_of_charZero [CharZero A] : #{ x : A // IsAlgebraic R x } = ℵ₀ := (Algebraic.countable R A).le_aleph0.antisymm (aleph0_le_cardinalMk_of_charZero R A) end lift section NonLift variable (R A : Type u) [CommRing R] [CommRing A] [IsDomain A] [Algebra R A] [NoZeroSMulDivisors R A] theorem cardinalMk_le_mul : #{ x : A // IsAlgebraic R x } ≤ #R[X] * ℵ₀ := by rw [← lift_id #_, ← lift_id #R[X]] exact cardinalMk_lift_le_mul R A @[stacks 09GK] theorem cardinalMk_le_max : #{ x : A // IsAlgebraic R x } ≤ max #R ℵ₀ := by rw [← lift_id #_, ← lift_id #R] exact cardinalMk_lift_le_max R A @[simp] theorem cardinalMk_of_infinite [Infinite R] : #{ x : A // IsAlgebraic R x } = #R := lift_inj.1 <| cardinalMk_lift_of_infinite R A end NonLift end Algebraic
IntervalIntegral.lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Patrick Massot, Sébastien Gouëzel -/ import Mathlib.MeasureTheory.Integral.IntervalIntegral.Basic import Mathlib.MeasureTheory.Integral.IntervalIntegral.FundThmCalculus import Mathlib.MeasureTheory.Integral.IntervalIntegral.IntegrationByParts deprecated_module (since := "2025-04-13")
Unique.lean
/- Copyright (c) 2021 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.AEEqOfIntegral import Mathlib.MeasureTheory.Function.ConditionalExpectation.AEMeasurable /-! # Uniqueness of the conditional expectation Two Lp functions `f, g` which are almost everywhere strongly measurable with respect to a σ-algebra `m` and verify `∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ` for all `m`-measurable sets `s` are equal almost everywhere. This proves the uniqueness of the conditional expectation, which is not yet defined in this file but is introduced in `Mathlib/MeasureTheory/Function/ConditionalExpectation/Basic.lean`. ## Main statements * `Lp.ae_eq_of_forall_setIntegral_eq'`: two `Lp` functions verifying the equality of integrals defining the conditional expectation are equal. * `ae_eq_of_forall_setIntegral_eq_of_sigma_finite'`: two functions verifying the equality of integrals defining the conditional expectation are equal almost everywhere. Requires `[SigmaFinite (μ.trim hm)]`. -/ open scoped ENNReal MeasureTheory namespace MeasureTheory variable {α E' F' 𝕜 : Type*} {p : ℝ≥0∞} {m m0 : MeasurableSpace α} {μ : Measure α} [RCLike 𝕜] -- 𝕜 for ℝ or ℂ -- E' for an inner product space on which we compute integrals [NormedAddCommGroup E'] [InnerProductSpace 𝕜 E'] [CompleteSpace E'] [NormedSpace ℝ E'] -- F' for integrals on a Lp submodule [NormedAddCommGroup F'] [NormedSpace ℝ F'] [CompleteSpace F'] section UniquenessOfConditionalExpectation /-! ## Uniqueness of the conditional expectation -/ theorem lpMeas.ae_eq_zero_of_forall_setIntegral_eq_zero (hm : m ≤ m0) (f : lpMeas E' 𝕜 m p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn (f : Lp E' p μ) s μ) (hf_zero : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → ∫ x in s, (f : Lp E' p μ) x ∂μ = 0) : f =ᵐ[μ] (0 : α → E') := by obtain ⟨g, hg_sm, hfg⟩ := lpMeas.ae_fin_strongly_measurable' hm f hp_ne_zero hp_ne_top refine hfg.trans ?_ refine ae_eq_zero_of_forall_setIntegral_eq_of_finStronglyMeasurable_trim hm ?_ ?_ hg_sm · intro s hs hμs have hfg_restrict : f =ᵐ[μ.restrict s] g := ae_restrict_of_ae hfg rw [IntegrableOn, integrable_congr hfg_restrict.symm] exact hf_int_finite s hs hμs · intro s hs hμs have hfg_restrict : f =ᵐ[μ.restrict s] g := ae_restrict_of_ae hfg rw [integral_congr_ae hfg_restrict.symm] exact hf_zero s hs hμs variable (𝕜) include 𝕜 in theorem Lp.ae_eq_zero_of_forall_setIntegral_eq_zero' (hm : m ≤ m0) (f : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn f s μ) (hf_zero : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = 0) (hf_meas : AEStronglyMeasurable[m] f μ) : f =ᵐ[μ] 0 := by let f_meas : lpMeas E' 𝕜 m p μ := ⟨f, hf_meas⟩ have hf_f_meas : f =ᵐ[μ] f_meas := by simp [f_meas] refine hf_f_meas.trans ?_ exact lpMeas.ae_eq_zero_of_forall_setIntegral_eq_zero hm f_meas hp_ne_zero hp_ne_top hf_int_finite hf_zero include 𝕜 in /-- **Uniqueness of the conditional expectation** -/ theorem Lp.ae_eq_of_forall_setIntegral_eq' (hm : m ≤ m0) (f g : Lp E' p μ) (hp_ne_zero : p ≠ 0) (hp_ne_top : p ≠ ∞) (hf_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn f s μ) (hg_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn g s μ) (hfg : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hf_meas : AEStronglyMeasurable[m] f μ) (hg_meas : AEStronglyMeasurable[m] g μ) : f =ᵐ[μ] g := by suffices h_sub : ⇑(f - g) =ᵐ[μ] 0 by rw [← sub_ae_eq_zero]; exact (Lp.coeFn_sub f g).symm.trans h_sub have hfg' : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → (∫ x in s, (f - g) x ∂μ) = 0 := by intro s hs hμs rw [integral_congr_ae (ae_restrict_of_ae (Lp.coeFn_sub f g))] rw [integral_sub' (hf_int_finite s hs hμs) (hg_int_finite s hs hμs)] exact sub_eq_zero.mpr (hfg s hs hμs) have hfg_int : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn (⇑(f - g)) s μ := by intro s hs hμs rw [IntegrableOn, integrable_congr (ae_restrict_of_ae (Lp.coeFn_sub f g))] exact (hf_int_finite s hs hμs).sub (hg_int_finite s hs hμs) exact Lp.ae_eq_zero_of_forall_setIntegral_eq_zero' 𝕜 hm (f - g) hp_ne_zero hp_ne_top hfg_int hfg' <| (hf_meas.sub hg_meas).congr (Lp.coeFn_sub f g).symm variable {𝕜} theorem ae_eq_of_forall_setIntegral_eq_of_sigmaFinite' (hm : m ≤ m0) [SigmaFinite (μ.trim hm)] {f g : α → F'} (hf_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn f s μ) (hg_int_finite : ∀ s, MeasurableSet[m] s → μ s < ∞ → IntegrableOn g s μ) (hfg_eq : ∀ s : Set α, MeasurableSet[m] s → μ s < ∞ → ∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ) (hfm : AEStronglyMeasurable[m] f μ) (hgm : AEStronglyMeasurable[m] g μ) : f =ᵐ[μ] g := by rw [← ae_eq_trim_iff_of_aestronglyMeasurable hm hfm hgm] have hf_mk_int_finite (s) : MeasurableSet[m] s → μ.trim hm s < ∞ → @IntegrableOn _ _ m _ _ (hfm.mk f) s (μ.trim hm) := by intro hs hμs rw [trim_measurableSet_eq hm hs] at hμs -- Porting note: `rw [IntegrableOn]` fails with -- synthesized type class instance is not definitionally equal to expression inferred by typing -- rules, synthesized m0 inferred m unfold IntegrableOn rw [restrict_trim hm _ hs] refine Integrable.trim hm ?_ hfm.stronglyMeasurable_mk exact Integrable.congr (hf_int_finite s hs hμs) (ae_restrict_of_ae hfm.ae_eq_mk) have hg_mk_int_finite (s) : MeasurableSet[m] s → μ.trim hm s < ∞ → @IntegrableOn _ _ m _ _ (hgm.mk g) s (μ.trim hm) := by intro hs hμs rw [trim_measurableSet_eq hm hs] at hμs -- Porting note: `rw [IntegrableOn]` fails with -- synthesized type class instance is not definitionally equal to expression inferred by typing -- rules, synthesized m0 inferred m unfold IntegrableOn rw [restrict_trim hm _ hs] refine Integrable.trim hm ?_ hgm.stronglyMeasurable_mk exact Integrable.congr (hg_int_finite s hs hμs) (ae_restrict_of_ae hgm.ae_eq_mk) have hfg_mk_eq : ∀ s : Set α, MeasurableSet[m] s → μ.trim hm s < ∞ → ∫ x in s, hfm.mk f x ∂μ.trim hm = ∫ x in s, hgm.mk g x ∂μ.trim hm := by intro s hs hμs rw [trim_measurableSet_eq hm hs] at hμs rw [restrict_trim hm _ hs, ← integral_trim hm hfm.stronglyMeasurable_mk, ← integral_trim hm hgm.stronglyMeasurable_mk, integral_congr_ae (ae_restrict_of_ae hfm.ae_eq_mk.symm), integral_congr_ae (ae_restrict_of_ae hgm.ae_eq_mk.symm)] exact hfg_eq s hs hμs exact ae_eq_of_forall_setIntegral_eq_of_sigmaFinite hf_mk_int_finite hg_mk_int_finite hfg_mk_eq end UniquenessOfConditionalExpectation section IntegralNormLE variable {s : Set α} /-- Let `m` be a sub-σ-algebra of `m0`, `f` an `m0`-measurable function and `g` an `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫ x in s, ‖g x‖ ∂μ ≤ ∫ x in s, ‖f x‖ ∂μ` on all `m`-measurable sets with finite measure. -/ theorem integral_norm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : StronglyMeasurable f) (hfi : IntegrableOn f s μ) (hg : StronglyMeasurable[m] g) (hgi : IntegrableOn g s μ) (hgf : ∀ t, MeasurableSet[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : MeasurableSet[m] s) (hμs : μ s ≠ ∞) : (∫ x in s, ‖g x‖ ∂μ) ≤ ∫ x in s, ‖f x‖ ∂μ := by rw [integral_norm_eq_pos_sub_neg hgi, integral_norm_eq_pos_sub_neg hfi] have h_meas_nonneg_g : MeasurableSet[m] {x | 0 ≤ g x} := (@stronglyMeasurable_const _ _ m _ _).measurableSet_le hg have h_meas_nonneg_f : MeasurableSet {x | 0 ≤ f x} := stronglyMeasurable_const.measurableSet_le hf have h_meas_nonpos_g : MeasurableSet[m] {x | g x ≤ 0} := hg.measurableSet_le (@stronglyMeasurable_const _ _ m _ _) have h_meas_nonpos_f : MeasurableSet {x | f x ≤ 0} := hf.measurableSet_le stronglyMeasurable_const refine sub_le_sub ?_ ?_ · rw [Measure.restrict_restrict (hm _ h_meas_nonneg_g), Measure.restrict_restrict h_meas_nonneg_f, hgf _ (@MeasurableSet.inter α m _ _ h_meas_nonneg_g hs) ((measure_mono Set.inter_subset_right).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← Measure.restrict_restrict (hm _ h_meas_nonneg_g), ← Measure.restrict_restrict h_meas_nonneg_f] exact setIntegral_le_nonneg (hm _ h_meas_nonneg_g) hf hfi · rw [Measure.restrict_restrict (hm _ h_meas_nonpos_g), Measure.restrict_restrict h_meas_nonpos_f, hgf _ (@MeasurableSet.inter α m _ _ h_meas_nonpos_g hs) ((measure_mono Set.inter_subset_right).trans_lt (lt_top_iff_ne_top.mpr hμs)), ← Measure.restrict_restrict (hm _ h_meas_nonpos_g), ← Measure.restrict_restrict h_meas_nonpos_f] exact setIntegral_nonpos_le (hm _ h_meas_nonpos_g) hf hfi /-- Let `m` be a sub-σ-algebra of `m0`, `f` an `m0`-measurable function and `g` an `m`-measurable function, such that their integrals coincide on `m`-measurable sets with finite measure. Then `∫⁻ x in s, ‖g x‖ₑ ∂μ ≤ ∫⁻ x in s, ‖f x‖ₑ ∂μ` on all `m`-measurable sets with finite measure. -/ theorem lintegral_enorm_le_of_forall_fin_meas_integral_eq (hm : m ≤ m0) {f g : α → ℝ} (hf : StronglyMeasurable f) (hfi : IntegrableOn f s μ) (hg : StronglyMeasurable[m] g) (hgi : IntegrableOn g s μ) (hgf : ∀ t, MeasurableSet[m] t → μ t < ∞ → ∫ x in t, g x ∂μ = ∫ x in t, f x ∂μ) (hs : MeasurableSet[m] s) (hμs : μ s ≠ ∞) : (∫⁻ x in s, ‖g x‖ₑ ∂μ) ≤ ∫⁻ x in s, ‖f x‖ₑ ∂μ := by rw [← ofReal_integral_norm_eq_lintegral_enorm hfi, ← ofReal_integral_norm_eq_lintegral_enorm hgi, ENNReal.ofReal_le_ofReal_iff] · exact integral_norm_le_of_forall_fin_meas_integral_eq hm hf hfi hg hgi hgf hs hμs · positivity end IntegralNormLE end MeasureTheory
alt.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import div fintype tuple tuple bigop prime finset ssralg. From mathcomp Require Import zmodp fingroup morphism perm automorphism quotient. From mathcomp Require Import action cyclic pgroup gseries sylow. From mathcomp Require Import primitive_action nilpotent maximal. (******************************************************************************) (* Definitions of the symmetric and alternate groups, and some properties. *) (* 'Sym_T == The symmetric group over type T (which must have a finType *) (* structure). *) (* := [set: {perm T}] *) (* 'Alt_T == The alternating group over type T. *) (******************************************************************************) Unset Printing Implicit Defensive. Set Implicit Arguments. Unset Strict Implicit. Import GroupScope GRing. HB.instance Definition _ := isMulGroup.Build bool addbA addFb addbb. Section SymAltDef. Variable T : finType. Implicit Types (s : {perm T}) (x y z : T). (** Definitions of the alternate groups and some Properties **) Definition Sym : {set {perm T}} := setT. Canonical Sym_group := Eval hnf in [group of Sym]. Local Notation "'Sym_T" := Sym. Canonical sign_morph := @Morphism _ _ 'Sym_T _ (in2W (@odd_permM _)). Definition Alt := 'ker (@odd_perm T). Canonical Alt_group := Eval hnf in [group of Alt]. Local Notation "'Alt_T" := Alt. Lemma Alt_even p : (p \in 'Alt_T) = ~~ p. Proof. by rewrite !inE /=; case: odd_perm. Qed. Lemma Alt_subset : 'Alt_T \subset 'Sym_T. Proof. exact: subsetT. Qed. Lemma Alt_normal : 'Alt_T <| 'Sym_T. Proof. exact: ker_normal. Qed. Lemma Alt_norm : 'Sym_T \subset 'N('Alt_T). Proof. by case/andP: Alt_normal. Qed. Let n := #|T|. Lemma Alt_index : 1 < n -> #|'Sym_T : 'Alt_T| = 2. Proof. move=> lt1n; rewrite -card_quotient ?Alt_norm //=. have : ('Sym_T / 'Alt_T) \isog (@odd_perm T @* 'Sym_T) by apply: first_isog. case/isogP=> g /injmP/card_in_imset <-. rewrite /morphim setIid=> ->; rewrite -card_bool; apply: eq_card => b. apply/imsetP; case: b => /=; last first. by exists (1 : {perm T}); [rewrite setIid inE | rewrite odd_perm1]. case: (pickP T) lt1n => [x1 _ | d0]; last by rewrite /n eq_card0. rewrite /n (cardD1 x1) ltnS lt0n => /existsP[x2 /=]. by rewrite eq_sym andbT -odd_tperm; exists (tperm x1 x2); rewrite ?inE. Qed. Lemma card_Sym : #|'Sym_T| = n`!. Proof. rewrite -[n]cardsE -card_perm; apply: eq_card => p. by apply/idP/subsetP=> [? ?|]; rewrite !inE. Qed. Lemma card_Alt : 1 < n -> (2 * #|'Alt_T|)%N = n`!. Proof. by move/Alt_index <-; rewrite mulnC (Lagrange Alt_subset) card_Sym. Qed. Lemma Sym_trans : [transitive^n 'Sym_T, on setT | 'P]. Proof. apply/imsetP; pose t1 := [tuple of enum T]. have dt1: t1 \in n.-dtuple(setT) by rewrite inE enum_uniq; apply/subsetP. exists t1 => //; apply/setP=> t; apply/idP/imsetP=> [|[a _ ->{t}]]; last first. by apply: n_act_dtuple => //; apply/astabsP=> x; rewrite !inE. case/dtuple_onP=> injt _; have injf := inj_comp injt enum_rank_inj. exists (perm injf); first by rewrite inE. apply: eq_from_tnth => i; rewrite tnth_map /= [aperm _ _]permE; congr tnth. by rewrite (tnth_nth (enum_default i)) enum_valK. Qed. Lemma Alt_trans : [transitive^n.-2 'Alt_T, on setT | 'P]. Proof. case n_m2: n Sym_trans => [|[|m]] /= tr_m2; try exact: ntransitive0. have tr_m := ntransitive_weak (leqW (leqnSn m)) tr_m2. case/imsetP: tr_m2; case/tupleP=> x; case/tupleP=> y t. rewrite !dtuple_on_add 2![x \in _]inE inE negb_or /= -!andbA. case/and4P=> nxy ntx nty dt _; apply/imsetP; exists t => //; apply/setP=> u. apply/idP/imsetP=> [|[a _ ->{u}]]; last first. by apply: n_act_dtuple => //; apply/astabsP=> z; rewrite !inE. case/(atransP2 tr_m dt)=> /= a _ ->{u}. case odd_a: (odd_perm a); last by exists a => //; rewrite !inE /= odd_a. exists (tperm x y * a); first by rewrite !inE /= odd_permM odd_tperm nxy odd_a. apply/val_inj/eq_in_map => z tz; rewrite actM /= /aperm; congr (a _). by case: tpermP ntx nty => // <-; rewrite tz. Qed. Lemma aperm_faithful (A : {group {perm T}}) : [faithful A, on setT | 'P]. Proof. by apply/faithfulP=> /= p _ np1; apply/eqP/perm_act1P=> y; rewrite np1 ?inE. Qed. End SymAltDef. Arguments Sym T%_type. Arguments Sym_group T%_type. Arguments Alt T%_type. Arguments Alt_group T%_type. Notation "''Sym_' T" := (Sym T) (at level 8, T at level 2, format "''Sym_' T") : group_scope. Notation "''Sym_' T" := (Sym_group T) : Group_scope. Notation "''Alt_' T" := (Alt T) (at level 8, T at level 2, format "''Alt_' T") : group_scope. Notation "''Alt_' T" := (Alt_group T) : Group_scope. Lemma trivial_Alt_2 (T : finType) : #|T| <= 2 -> 'Alt_T = 1. Proof. rewrite leq_eqVlt => /predU1P[] oT. by apply: card_le1_trivg; rewrite -leq_double -mul2n card_Alt oT. suffices Sym1: 'Sym_T = 1 by apply/trivgP; rewrite -Sym1 subsetT. by apply: card1_trivg; rewrite card_Sym; case: #|T| oT; do 2?case. Qed. Lemma simple_Alt_3 (T : finType) : #|T| = 3 -> simple 'Alt_T. Proof. move=> T3; have{T3} oA: #|'Alt_T| = 3. by apply: double_inj; rewrite -mul2n card_Alt T3. apply/simpleP; split=> [|K]; [by rewrite trivg_card1 oA | case/andP=> sKH _]. have:= cardSg sKH; rewrite oA dvdn_divisors // !inE orbC /= -oA. case/pred2P=> eqK; [right | left]; apply/eqP. by rewrite eqEcard sKH eqK leqnn. by rewrite eq_sym eqEcard sub1G eqK cards1. Qed. Lemma not_simple_Alt_4 (T : finType) : #|T| = 4 -> ~~ simple 'Alt_T. Proof. move=> oT; set A := 'Alt_T. have oA: #|A| = 12 by apply: double_inj; rewrite -mul2n card_Alt oT. suffices [p]: exists p, [/\ prime p, 1 < #|A|`_p < #|A| & #|'Syl_p(A)| == 1%N]. case=> p_pr pA_int; rewrite /A; case/normal_sylowP=> P; case/pHallP. rewrite /= -/A => sPA pP nPA; apply/simpleP=> [] [_]; rewrite -pP in pA_int. by case/(_ P)=> // defP; rewrite defP oA ?cards1 in pA_int. have: #|'Syl_3(A)| \in filter [pred d | d %% 3 == 1%N] (divisors 12). by rewrite mem_filter -dvdn_divisors //= -oA card_Syl_dvd ?card_Syl_mod. rewrite /= oA mem_seq2 orbC. case/predU1P=> [oQ3|]; [exists 2 | exists 3]; split; rewrite ?p_part //. pose A3 := [set x : {perm T} | #[x] == 3]; suffices oA3: #|A :&: A3| = 8. have sQ2 P: P \in 'Syl_2(A) -> P :=: A :\: A3. rewrite inE pHallE oA p_part -natTrecE /= => /andP[sPA /eqP oP]. apply/eqP; rewrite eqEcard -(leq_add2l 8) -{1}oA3 cardsID oA oP. rewrite andbT subsetD sPA; apply/exists_inP=> -[x] /= Px. by rewrite inE => /eqP ox; have:= order_dvdG Px; rewrite oP ox. have [/= P sylP] := Sylow_exists 2 [group of A]. rewrite -(([set P] =P 'Syl_2(A)) _) ?cards1 // eqEsubset sub1set inE sylP. by apply/subsetP=> Q sylQ; rewrite inE -val_eqE /= !sQ2 // inE. rewrite -[8]/(4 * 2)%N -{}oQ3 -sum1_card -sum_nat_const. rewrite (partition_big (fun x => <[x]>%G) [in 'Syl_3(A)]) => [|x]; last first. by case/setIP=> Ax; rewrite /= !inE pHallE p_part cycle_subG Ax oA. apply: eq_bigr => Q; rewrite inE pHallE oA p_part -?natTrecE //=. case/andP=> sQA /eqP oQ; have:= oQ. rewrite (cardsD1 1) group1 -sum1_card => [[/= <-]]; apply: eq_bigl => x. rewrite setIC -val_eqE /= 2!inE in_setD1 -andbA -{4}[x]expg1 -order_dvdn dvdn1. apply/and3P/andP=> [[/eqP-> _ /eqP <-] | [ntx Qx]]; first by rewrite cycle_id. have:= order_dvdG Qx; rewrite oQ dvdn_divisors // mem_seq2 (negPf ntx) /=. by rewrite eqEcard cycle_subG Qx (subsetP sQA) // oQ /order => /eqP->. Qed. Lemma simple_Alt5_base (T : finType) : #|T| = 5 -> simple 'Alt_T. Proof. move=> oT. have F1: #|'Alt_T| = 60 by apply: double_inj; rewrite -mul2n card_Alt oT. have FF (H : {group {perm T}}): H <| 'Alt_T -> H :<>: 1 -> 20 %| #|H|. - move=> Hh1 Hh3. have [x _]: exists x, x \in T by apply/existsP/eqP; rewrite oT. have F2 := Alt_trans T; rewrite oT /= in F2. have F3: [transitive 'Alt_T, on setT | 'P] by apply: ntransitive1 F2. have F4: [primitive 'Alt_T, on setT | 'P] by apply: ntransitive_primitive F2. case: (prim_trans_norm F4 Hh1) => F5. by case: Hh3; apply/trivgP; apply: subset_trans F5 (aperm_faithful _). have F6: 5 %| #|H| by rewrite -oT -cardsT (atrans_dvd F5). have F7: 4 %| #|H|. have F7: #|[set~ x]| = 4 by rewrite cardsC1 oT. case: (pickP [in [set~ x]]) => [y Hy | ?]; last by rewrite eq_card0 in F7. pose K := 'C_H[x | 'P]%G. have F8 : K \subset H by apply: subsetIl. pose Gx := 'C_('Alt_T)[x | 'P]%G. have F9: [transitive^2 Gx, on [set~ x] | 'P]. by rewrite -[[set~ x]]setTI -setDE stab_ntransitive ?inE. have F10: [transitive Gx, on [set~ x] | 'P]. exact: ntransitive1 F9. have F11: [primitive Gx, on [set~ x] | 'P]. exact: ntransitive_primitive F9. have F12: K \subset Gx by apply: setSI; apply: normal_sub. have F13: K <| Gx by rewrite /(K <| _) F12 normsIG // normal_norm. case: (prim_trans_norm F11 F13) => Ksub; last first. by apply: dvdn_trans (cardSg F8); rewrite -F7; apply: atrans_dvd Ksub. have F14: [faithful Gx, on [set~ x] | 'P]. apply/subsetP=> g; do 2![case/setIP] => Altg cgx cgx'. apply: (subsetP (aperm_faithful 'Alt_T)). rewrite inE Altg /=; apply/astabP=> z _. case: (z =P x) => [->|]; first exact: (astab1P cgx). by move/eqP=> nxz; rewrite (astabP cgx') ?inE //. have Hreg g (z : T): g \in H -> g z = z -> g = 1. have F15 h: h \in H -> h x = x -> h = 1. move=> Hh Hhx; have: h \in K by rewrite inE Hh; apply/astab1P. by rewrite (trivGP (subset_trans Ksub F14)) => /set1P. move=> Hg Hgz; have:= in_setT x; rewrite -(atransP F3 z) ?inE //. case/imsetP=> g1 Hg1 Hg2; apply: (conjg_inj g1); rewrite conj1g. apply: F15; last by rewrite Hg2 -permM mulKVg permM Hgz. by case/normalP: Hh1 => _ nH1; rewrite -(nH1 _ Hg1) memJ_conjg. clear K F8 F12 F13 Ksub F14. case: (Cauchy _ F6) => // h Hh /eqP Horder. have diff_hnx_x n: 0 < n -> n < 5 -> x != (h ^+ n) x. move=> Hn1 Hn2; rewrite eq_sym; apply/negP => HH. have: #[h ^+ n] = 5. rewrite orderXgcd // (eqP Horder). by move: Hn1 Hn2 {HH}; do 5 (case: n => [|n] //). have Hhd2: h ^+ n \in H by rewrite groupX. by rewrite (Hreg _ _ Hhd2 (eqP HH)) order1. pose S1 := [tuple x; h x; (h ^+ 3) x]. have DnS1: S1 \in 3.-dtuple(setT). rewrite inE memtE subset_all /= !inE /= !negb_or -!andbA /= andbT. rewrite -{1}[h]expg1 !diff_hnx_x // expgSr permM. by rewrite (inj_eq perm_inj) diff_hnx_x. pose S2 := [tuple x; h x; (h ^+ 2) x]. have DnS2: S2 \in 3.-dtuple(setT). rewrite inE memtE subset_all /= !inE /= !negb_or -!andbA /= andbT. rewrite -{1}[h]expg1 !diff_hnx_x // expgSr permM. by rewrite (inj_eq perm_inj) diff_hnx_x. case: (atransP2 F2 DnS1 DnS2) => g Hg [/=]. rewrite /aperm => Hgx Hghx Hgh3x. have h_g_com: h * g = g * h. suff HH: (g * h * g^-1) * h^-1 = 1 by rewrite -[h * g]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hgx Hghx -!permM mulKVg mulgV perm1. rewrite groupM // ?groupV // (conjgCV g) mulgK -mem_conjg. by case/normalP: Hh1 => _ ->. have: (g * (h ^+ 2) * g ^-1) x = (h ^+ 3) x. rewrite !permM -Hgx. have ->: h (h x) = (h ^+ 2) x by rewrite /= permM. by rewrite {1}Hgh3x -!permM /= mulgV mulg1 -expgSr. rewrite commuteX // mulgK {1}[expgn]lock expgS permM -lock. by move/perm_inj=> eqxhx; case/eqP: (diff_hnx_x 1%N isT isT); rewrite expg1. by rewrite (@Gauss_dvd 4 5) // F7. apply/simpleP; split => [|H Hnorm]; first by rewrite trivg_card1 F1. case Hcard1: (#|H| == 1%N); move/eqP: Hcard1 => Hcard1. by left; apply: card1_trivg; rewrite Hcard1. right; case Hcard60: (#|H| == 60); move/eqP: Hcard60 => Hcard60. by apply/eqP; rewrite eqEcard Hcard60 F1 andbT; case/andP: Hnorm. have {Hcard1 Hcard60} Hcard20: #|H| = 20. have Hdiv: 20 %| #|H| by apply: FF => // HH; case Hcard1; rewrite HH cards1. case H20: (#|H| == 20); first exact/eqP. case: Hcard60; case/andP: Hnorm; move/cardSg; rewrite F1 => Hdiv1 _. by case/dvdnP: Hdiv H20 Hdiv1 => n ->; move: n; do 4!case=> //. have prime_5: prime 5 by []. have nSyl5: #|'Syl_5(H)| = 1%N. move: (card_Syl_dvd 5 H) (card_Syl_mod H prime_5). rewrite Hcard20; case: (card _) => // n Hdiv. move: (dvdn_leq (isT: (0 < 20)%N) Hdiv). by move: (n) Hdiv; do 20 (case=> //). case: (Sylow_exists 5 H) => S; case/pHallP=> sSH oS. have{} oS: #|S| = 5 by rewrite oS p_part Hcard20. suff: 20 %| #|S| by rewrite oS. apply: FF => [|S1]; last by rewrite S1 cards1 in oS. apply: char_normal_trans Hnorm; apply: lone_subgroup_char => // Q sQH isoQS. rewrite subEproper; apply/norP=> [[nQS _]]; move: nSyl5. rewrite (cardsD1 S) (cardsD1 Q) 4!{1}inE nQS !pHallE sQH sSH Hcard20 p_part. by rewrite (card_isog isoQS) oS. Qed. Section Restrict. Variables (T : finType) (x : T). Notation T' := {y | y != x}. Lemma rfd_funP (p : {perm T}) (u : T') : let p1 := if p x == x then p else 1 in p1 (val u) != x. Proof. case: (p x =P x) => /= [pxx | _]; last by rewrite perm1 (valP u). by rewrite -[x in _ != x]pxx (inj_eq perm_inj); apply: (valP u). Qed. Definition rfd_fun p := [fun u => Sub ((_ : {perm T}) _) (rfd_funP p u) : T']. Lemma rfdP p : injective (rfd_fun p). Proof. apply: can_inj (rfd_fun p^-1) _ => u; apply: val_inj => /=. rewrite -(can_eq (permK p)) permKV eq_sym. by case: eqP => _; rewrite !(perm1, permK). Qed. Definition rfd p := perm (@rfdP p). Hypothesis card_T : 2 < #|T|. Lemma rfd_morph : {in 'C_('Sym_T)[x | 'P] &, {morph rfd : y z / y * z}}. Proof. move=> p q; rewrite !setIA !setIid; move/astab1P=> p_x; move/astab1P=> q_x. apply/permP=> u; apply: val_inj. by rewrite permE /= !permM !permE /= [p x]p_x [q x]q_x eqxx permM /=. Qed. Canonical rfd_morphism := Morphism rfd_morph. Definition rgd_fun (p : {perm T'}) := [fun x1 => if insub x1 is Some u then sval (p u) else x]. Lemma rgdP p : injective (rgd_fun p). Proof. apply: can_inj (rgd_fun p^-1) _ => y /=. case: (insubP _ y) => [u _ val_u|]; first by rewrite valK permK. by rewrite negbK; move/eqP->; rewrite insubF //= eqxx. Qed. Definition rgd p := perm (@rgdP p). Lemma rfd_odd (p : {perm T}) : p x = x -> rfd p = p :> bool. Proof. have rfd1: rfd 1 = 1. by apply/permP => u; apply: val_inj; rewrite permE /= if_same !perm1. have [n] := ubnP #|[set x | p x != x]|; elim: n p => // n IHn p le_p_n px_x. have [p_id | [x1 Hx1]] := set_0Vmem [set x | p x != x]. suffices ->: p = 1 by rewrite rfd1 !odd_perm1. by apply/permP => z; apply: contraFeq (in_set0 z); rewrite perm1 -p_id inE. have nx1x: x1 != x by apply: contraTneq Hx1 => ->; rewrite inE px_x eqxx. have npxx1: p x != x1 by apply: contraNneq nx1x => <-; rewrite px_x. have npx1x: p x1 != x by rewrite -px_x (inj_eq perm_inj). pose p1 := p * tperm x1 (p x1). have fix_p1 y: p y = y -> p1 y = y. by move=> pyy; rewrite permM; have [<-|/perm_inj<-|] := tpermP; rewrite ?pyy. have p1x_x: p1 x = x by apply: fix_p1. have{le_p_n} lt_p1_n: #|[set x | p1 x != x]| < n. move: le_p_n; rewrite ltnS (cardsD1 x1) Hx1; apply/leq_trans/subset_leq_card. rewrite subsetD1 inE permM tpermR eqxx andbT. by apply/subsetP=> y /[!inE]; apply: contraNneq=> /fix_p1->. transitivity (p1 (+) true); last first. by rewrite odd_permM odd_tperm -Hx1 inE eq_sym addbK. have ->: p = p1 * tperm x1 (p x1) by rewrite -tpermV mulgK. rewrite morphM; last 2 first; first by rewrite 2!inE; apply/astab1P. by rewrite 2!inE; apply/astab1P; rewrite -[RHS]p1x_x permM px_x. rewrite odd_permM IHn //=; congr (_ (+) _). pose x2 : T' := Sub x1 nx1x; pose px2 : T' := Sub (p x1) npx1x. suffices ->: rfd (tperm x1 (p x1)) = tperm x2 px2. by rewrite odd_tperm eq_sym; rewrite inE in Hx1. apply/permP => z; apply/val_eqP; rewrite permE /= tpermD // eqxx. by rewrite !permE /= -!val_eqE /= !(fun_if sval) /=. Qed. Lemma rfd_iso : 'C_('Alt_T)[x | 'P] \isog 'Alt_T'. Proof. have rgd_x p: rgd p x = x by rewrite permE /= insubF //= eqxx. have rfd_rgd p: rfd (rgd p) = p. apply/permP => [[z Hz]]; apply/val_eqP; rewrite !permE. by rewrite /= [rgd _ _]permE /= insubF eqxx // permE /= insubT. have sSd: 'C_('Alt_T)[x | 'P] \subset 'dom rfd. by apply/subsetP=> p /[!inE]/= /andP[]. apply/isogP; exists [morphism of restrm sSd rfd] => /=; last first. rewrite morphim_restrm setIid; apply/setP=> z; apply/morphimP/idP=> [[p _]|]. case/setIP; rewrite Alt_even => Hp; move/astab1P=> Hp1 ->. by rewrite Alt_even rfd_odd. have dz': rgd z x == x by rewrite rgd_x. move=> kz; exists (rgd z); last by rewrite /= rfd_rgd. by rewrite 2!inE (sameP astab1P eqP). rewrite 4!inE /= (sameP astab1P eqP) dz' -rfd_odd; last exact/eqP. by rewrite rfd_rgd mker // ?set11. apply/injmP=> x1 y1 /=. case/setIP=> Hax1; move/astab1P; rewrite /= /aperm => Hx1. case/setIP=> Hay1; move/astab1P; rewrite /= /aperm => Hy1 Hr. apply/permP => z. case (z =P x) => [->|]; [by rewrite Hx1 | move/eqP => nzx]. move: (congr1 (fun q : {perm T'} => q (Sub z nzx)) Hr). by rewrite !permE => [[]]; rewrite Hx1 Hy1 !eqxx. Qed. End Restrict. Lemma simple_Alt5 (T : finType) : #|T| >= 5 -> simple 'Alt_T. Proof. suff F1 n: #|T| = n + 5 -> simple 'Alt_T by move/subnK/esym/F1. elim: n T => [| n Hrec T Hde]; first exact: simple_Alt5_base. have oT: 5 < #|T| by rewrite Hde addnC. apply/simpleP; split=> [|H Hnorm]; last have [Hh1 nH] := andP Hnorm. rewrite trivg_card1 -[#|_|]half_double -mul2n card_Alt Hde addnC //. by rewrite addSn factS mulnC -(prednK (fact_gt0 _)). case E1: (pred0b T); first by rewrite /pred0b in E1; rewrite (eqP E1) in oT. case/pred0Pn: E1 => x _; have Hx := in_setT x. have F2: [transitive^4 'Alt_T, on setT | 'P]. by apply: ntransitive_weak (Alt_trans T); rewrite -(subnKC oT). have F3 := ntransitive1 (isT: 0 < 4) F2. have F4 := ntransitive_primitive (isT: 1 < 4) F2. case Hcard1: (#|H| == 1%N); move/eqP: Hcard1 => Hcard1. by left; apply: card1_trivg; rewrite Hcard1. right; case: (prim_trans_norm F4 Hnorm) => F5. by rewrite (trivGP (subset_trans F5 (aperm_faithful _))) cards1 in Hcard1. case E1: (pred0b (predD1 T x)). rewrite /pred0b in E1; move: oT. by rewrite (cardD1 x) (eqP E1); case: (T x). case/pred0Pn: E1 => y Hdy; case/andP: (Hdy) => diff_x_y Hy. pose K := 'C_H[x | 'P]%G. have F8: K \subset H by apply: subsetIl. pose Gx := 'C_('Alt_T)[x | 'P]. have F9: [transitive^3 Gx, on [set~ x] | 'P]. by rewrite -[[set~ x]]setTI -setDE stab_ntransitive ?inE. have F10: [transitive Gx, on [set~ x] | 'P]. by apply: ntransitive1 F9. have F11: [primitive Gx, on [set~ x] | 'P]. by apply: ntransitive_primitive F9. have F12: K \subset Gx by rewrite setSI // normal_sub. have F13: K <| Gx by apply/andP; rewrite normsIG. have:= prim_trans_norm F11; case/(_ K) => //= => Ksub; last first. have F14: Gx * H = 'Alt_T by apply/(subgroup_transitiveP _ _ F3). have: simple Gx. by rewrite (isog_simple (rfd_iso x)) Hrec //= card_sig cardC1 Hde. case/simpleP=> _ simGx; case/simGx: F13 => /= HH2. case Ez: (pred0b (predD1 (predD1 T x) y)). move: oT; rewrite /pred0b in Ez. by rewrite (cardD1 x) (cardD1 y) (eqP Ez) inE /= inE /= diff_x_y. case/pred0Pn: Ez => z; case/andP => diff_y_z Hdz. have [diff_x_z Hz] := andP Hdz. have: z \in [set~ x] by rewrite !inE. rewrite -(atransP Ksub y) ?inE //; case/imsetP => g. rewrite /= HH2 inE; move/eqP=> -> HH4. by case/negP: diff_y_z; rewrite HH4 act1. by rewrite /= -F14 -[Gx]HH2 (mulSGid F8). have F14: [faithful Gx, on [set~ x] | 'P]. apply: subset_trans (aperm_faithful 'Sym_T); rewrite subsetI subsetT. apply/subsetP=> g; do 2![case/setIP]=> _ cgx cgx'; apply/astabP=> z _ /=. case: (z =P x) => [->|]; first exact: (astab1P cgx). by move/eqP=> zx; rewrite [_ g](astabP cgx') ?inE. have Hreg g z: g \in H -> g z = z -> g = 1. have F15 h: h \in H -> h x = x -> h = 1. move=> Hh Hhx; have: h \in K by rewrite inE Hh; apply/astab1P. by rewrite [K](trivGP (subset_trans Ksub F14)) => /set1P. move=> Hg Hgz; have:= in_setT x; rewrite -(atransP F3 z) ?inE //. case/imsetP=> g1 Hg1 Hg2; apply: (conjg_inj g1); rewrite conj1g. apply: F15; last by rewrite Hg2 -permM mulKVg permM Hgz. by rewrite memJ_norm ?(subsetP nH). clear K F8 F12 F13 Ksub F14. have Hcard: 5 < #|H|. apply: (leq_trans oT); apply: dvdn_leq; first exact: cardG_gt0. by rewrite -cardsT (atrans_dvd F5). case Eh: (pred0b [predD1 H & 1]). by move: Hcard; rewrite /pred0b in Eh; rewrite (cardD1 1) group1 (eqP Eh). case/pred0Pn: Eh => h; case/andP => diff_1_h /= Hh. case Eg: (pred0b (predD1 (predD1 [predD1 H & 1] h) h^-1)). move: Hcard; rewrite ltnNge; case/negP. rewrite (cardD1 1) group1 (cardD1 h) (cardD1 h^-1) (eqnP Eg). by do 2!case: (_ \in _). case/pred0Pn: Eg => g; case/andP => diff_h1_g; case/andP => diff_h_g. case/andP => diff_1_g /= Hg. case diff_hx_x: (h x == x). by case/negP: diff_1_h; apply/eqP; apply: (Hreg _ _ Hh (eqP diff_hx_x)). case diff_gx_x: (g x == x). case/negP: diff_1_g; apply/eqP; apply: (Hreg _ _ Hg (eqP diff_gx_x)). case diff_gx_hx: (g x == h x). case/negP: diff_h_g; apply/eqP; symmetry; apply: (mulIg g^-1); rewrite gsimp. apply: (Hreg _ x); first by rewrite groupM // groupV. by rewrite permM -(eqP diff_gx_hx) -permM mulgV perm1. case diff_hgx_x: ((h * g) x == x). case/negP: diff_h1_g; apply/eqP; apply: (mulgI h); rewrite !gsimp. by apply: (Hreg _ x); [apply: groupM | apply/eqP]. case diff_hgx_hx: ((h * g) x == h x). case/negP: diff_1_g; apply/eqP. by apply: (Hreg _ (h x)) => //; apply/eqP; rewrite -permM. case diff_hgx_gx: ((h * g) x == g x). by case/idP: diff_hx_x; rewrite -(can_eq (permK g)) -permM. case Ez: (pred0b (predD1 (predD1 (predD1 (predD1 T x) (h x)) (g x)) ((h * g) x))). - move: oT; rewrite /pred0b in Ez. rewrite (cardD1 x) (cardD1 (h x)) (cardD1 (g x)) (cardD1 ((h * g) x)). by rewrite (eqP Ez) addnC; do 3!case: (_ x \in _). case/pred0Pn: Ez => z. case/and5P=> diff_hgx_z diff_gx_z diff_hx_z diff_x_z /= Hz. pose S1 := [tuple x; h x; g x; z]. have DnS1: S1 \in 4.-dtuple(setT). rewrite inE memtE subset_all -!andbA !negb_or /= !inE !andbT. rewrite -!(eq_sym z) diff_gx_z diff_x_z diff_hx_z. by rewrite !(eq_sym x) diff_hx_x diff_gx_x eq_sym diff_gx_hx. pose S2 := [tuple x; h x; g x; (h * g) x]. have DnS2: S2 \in 4.-dtuple(setT). rewrite inE memtE subset_all -!andbA !negb_or /= !inE !andbT !(eq_sym x). rewrite diff_hx_x diff_gx_x diff_hgx_x. by rewrite !(eq_sym (h x)) diff_gx_hx diff_hgx_hx eq_sym diff_hgx_gx. case: (atransP2 F2 DnS1 DnS2) => k Hk [/=]. rewrite /aperm => Hkx Hkhx Hkgx Hkhgx. have h_k_com: h * k = k * h. suff HH: (k * h * k^-1) * h^-1 = 1 by rewrite -[h * k]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hkx Hkhx -!permM mulKVg mulgV perm1. by rewrite groupM // ?groupV // (conjgCV k) mulgK -mem_conjg (normsP nH). have g_k_com: g * k = k * g. suff HH: (k * g * k^-1) * g^-1 = 1 by rewrite -[g * k]mul1g -HH !gnorm. apply: (Hreg _ x); last first. by rewrite !permM -Hkx Hkgx -!permM mulKVg mulgV perm1. by rewrite groupM // ?groupV // (conjgCV k) mulgK -mem_conjg (normsP nH). have HH: (k * (h * g) * k ^-1) x = z. by rewrite 2!permM -Hkx Hkhgx -permM mulgV perm1. case/negP: diff_hgx_z. rewrite -HH !mulgA -h_k_com -!mulgA [k * _]mulgA. by rewrite -g_k_com -!mulgA mulgV mulg1. Qed. Lemma gen_tperm_circular_shift (X : finType) x y c : prime #|X| -> x != y -> #[c]%g = #|X| -> <<[set tperm x y; c]>>%g = ('Sym_X)%g. Proof. move=> Xprime neq_xy ord_c; apply/eqP; rewrite eqEsubset subsetT/=. have c_gt1 : (1 < #[c]%g)%N by rewrite ord_c prime_gt1. have cppSS : #[c]%g.-2.+2 = #|X| by rewrite ?prednK ?ltn_predRL. pose f (i : 'Z_#[c]%g) : X := Zpm i x. have [g fK gK] : bijective f. apply: inj_card_bij; rewrite ?cppSS ?card_ord// /f /Zpm => i j cijx. pose stabx := ('C_<[c]>[x | 'P])%g. have cjix : (c ^+ (j - i)%R)%g x = x. by apply: (@perm_inj _ (c ^+ i)%g); rewrite -permM -expgD_Zp// addrNK. have : (c ^+ (j - i)%R)%g \in stabx. by rewrite !inE ?groupX ?mem_gen ?sub1set ?inE// ['P%act _ _]cjix eqxx. rewrite [stabx]perm_prime_astab// => /set1gP. move=> /(congr1 (mulg (c ^+ i))); rewrite -expgD_Zp// addrC addrNK mulg1. by move=> /eqP; rewrite eq_expg_ord// ?cppSS ?ord_c// => /eqP->. pose gsf s := g \o s \o f. have gsf_inj (s : {perm X}) : injective (gsf s). apply: inj_comp; last exact: can_inj fK. by apply: inj_comp; [exact: can_inj gK|exact: perm_inj]. pose fsg s := f \o s \o g. have fsg_inj (s : {perm _}) : injective (fsg s). apply: inj_comp; last exact: can_inj gK. by apply: inj_comp; [exact: can_inj fK|exact: perm_inj]. have gsf_morphic : morphic 'Sym_X (fun s => perm (gsf_inj s)). apply/morphicP => u v _ _; apply/permP => /= i. by rewrite !permE/= !permE /gsf /= gK permM. pose phi := morphm gsf_morphic; rewrite /= in phi. have phi_inj : ('injm phi)%g. apply/subsetP => /= u /mker/=; rewrite morphmE => gsfu1. apply/set1gP/permP=> z; have /permP/(_ (g z)) := gsfu1. by rewrite !perm1 permE /gsf/= gK => /(can_inj gK). have phiT : (phi @* 'Sym_X)%g = [set: {perm 'Z_#[c]%g}]. apply/eqP; rewrite eqEsubset subsetT/=; apply/subsetP => /= u _. apply/morphimP; exists (perm (fsg_inj u)); rewrite ?in_setT//. by apply/permP => /= i; rewrite morphmE permE /gsf/fsg/= permE/= !fK. have f0 : f 0%R = x by rewrite /f /Zpm permX. pose k := g y; have k_gt0 : (k > 0)%N. by rewrite lt0n (val_eqE k 0%R) -(can_eq fK) eq_sym gK f0. have phixy : phi (tperm x y) = tperm (0%R : 'Z_#[c]) k. apply/permP => i; rewrite permE/= /gsf/=; apply: (canLR fK). by rewrite !permE/= -f0 -[y]gK !(can_eq fK) -!fun_if. have phic : phi c = perm (addrI (1%R : 'Z_#[c])). apply/permP => i; rewrite /phi morphmE !permE /gsf/=; apply: (canLR fK). by rewrite /f /Zpm -permM addrC expgD_Zp. rewrite -(injmSK phi_inj)//= morphim_gen/= ?subsetT//= -/phi. rewrite phiT /morphim !setTI/= -/phi imsetU1 imset_set1/= phixy phic. suff /gen_tpermn_circular_shift<- : coprime #[c]%g.-2.+2 (k - 0)%R by []. by rewrite subr0 prime_coprime ?gtnNdvd// ?cppSS. Qed. Section Perm_solvable. Local Open Scope nat_scope. Variable T : finType. Lemma solvable_AltF : 4 < #|T| -> solvable 'Alt_T = false. Proof. move=> card_T; apply/negP => Alt_solvable. have/simple_Alt5 Alt_simple := card_T. have := simple_sol_prime Alt_solvable Alt_simple. have lt_T n : n <= 4 -> n < #|T| by move/leq_ltn_trans; apply. have -> : #|('Alt_T)%G| = #|T|`! %/ 2 by rewrite -card_Alt ?mulKn ?lt_T. move/even_prime => [/eqP|]; apply/negP. rewrite neq_ltn leq_divRL // mulnC -[2 * 3]/(3`!). by apply/orP; right; apply/ltnW/ltn_fact/lt_T. by rewrite -dvdn2 dvdn_divRL dvdn_fact //=; apply/ltnW/lt_T. Qed. Lemma solvable_SymF : 4 < #|T| -> solvable 'Sym_T = false. Proof. by rewrite (series_sol (Alt_normal T)) => /solvable_AltF->. Qed. End Perm_solvable.
fingroup.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import fintype div path tuple bigop prime finset. From mathcomp Require Export monoid. (******************************************************************************) (* Finite groups *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file defines the main interface for finite groups: *) (* finGroupType == the structure for finite types with a group law *) (* The HB class is called FinGroup. *) (* {group gT} == type of groups with elements of type gT *) (* baseFinGroupType == the structure for finite types with a monoid law *) (* and an involutive antimorphism; finGroupType is *) (* derived from baseFinGroupType *) (* The HB class is called BaseFinGroup. *) (* FinGroupType mulVg == the finGroupType structure for an existing *) (* baseFinGroupType structure, built from a proof of *) (* the left inverse group axiom for that structure's *) (* operations *) (* [group of G] == a clone for an existing {group gT} structure on *) (* G : {set gT} (the existing structure might be for *) (* some delta-expansion of G) *) (* If gT implements finGroupType, then we can form {set gT}, the type of *) (* finite sets with elements of type gT (as finGroupType extends finType). *) (* The group law extends pointwise to {set gT}, which thus implements a sub- *) (* interface baseFinGroupType of finGroupType. To be consistent with the *) (* predType interface, this is done by coercion to FinGroup.arg_sort, an *) (* alias for FinGroup.sort. Accordingly, all pointwise group operations below *) (* have arguments of type (FinGroup.arg_sort) gT and return results of type *) (* FinGroup.sort gT. *) (* The notations below are declared in two scopes: *) (* group_scope (delimiter %g) for point operations and set constructs. *) (* Group_scope (delimiter %G) for explicit {group gT} structures. *) (* These scopes should not be opened globally, although group_scope is often *) (* opened locally in group-theory files (via Import GroupScope). *) (* As {group gT} is both a subtype and an interface structure for {set gT}, *) (* the fact that a given G : {set gT} is a group can (and usually should) be *) (* inferred by type inference with canonical structures. This means that all *) (* `group' constructions (e.g., the normaliser 'N_G(H)) actually define sets *) (* with a canonical {group gT} structure; the %G delimiter can be used to *) (* specify the actual {group gT} structure (e.g., 'N_G(H)%G). *) (* Operations on elements of a group: *) (* x * y == the group product of x and y *) (* x ^+ n == the nth power of x, i.e., x * ... * x (n times) *) (* x^-1 == the group inverse of x *) (* x ^- n == the inverse of x ^+ n (notation for (x ^+ n)^-1) *) (* 1 == the unit element *) (* x ^ y == the conjugate of x by y (i.e., y^-1 * (x * y)) *) (* [~ x, y] == the commutator of x and y (i.e., x^-1 * x ^ y) *) (* [~ x1, ..., xn] == the commutator of x1, ..., xn (associating left) *) (* \prod_(i ...) x i == the product of the x i (order-sensitive) *) (* commute x y <-> x and y commute *) (* centralises x A <-> x centralises A *) (* 'C[x] == the set of elements that commute with x *) (* 'C_G[x] == the set of elements of G that commute with x *) (* <[x]> == the cyclic subgroup generated by the element x *) (* #[x] == the order of the element x, i.e., #|<[x]>| *) (* Operations on subsets/subgroups of a finite group: *) (* H * G == {xy | x \in H, y \in G} *) (* 1 or [1] or [1 gT] == the unit group *) (* [set: gT]%G == the group of all x : gT (in Group_scope) *) (* group_set G == G contains 1 and is closed under binary product; *) (* this is the characteristic property of the *) (* {group gT} subtype of {set gT} *) (* [subg G] == the subtype, set, or group of all x \in G: this *) (* notation is defined simultaneously in %type, %g *) (* and %G scopes, and G must denote a {group gT} *) (* structure (G is in the %G scope) *) (* subg, sgval == the projection into and injection from [subg G] *) (* H^# == the set H minus the unit element *) (* repr H == some element of H if 1 \notin H != set0, else 1 *) (* (repr is defined over sets of a baseFinGroupType, *) (* so it can be used, e.g., to pick right cosets.) *) (* x *: H == left coset of H by x *) (* lcosets H G == the set of the left cosets of H by elements of G *) (* H :* x == right coset of H by x *) (* rcosets H G == the set of the right cosets of H by elements of G *) (* #|G : H| == the index of H in G, i.e., #|rcosets G H| *) (* H :^ x == the conjugate of H by x *) (* x ^: H == the conjugate class of x in H *) (* classes G == the set of all conjugate classes of G *) (* G :^: H == {G :^ x | x \in H} *) (* class_support G H == {x ^ y | x \in G, y \in H} *) (* commg_set G H == {[~ x, y] | x \in G, y \in H}; NOT the commutator! *) (* <<H>> == the subgroup generated by the set H *) (* [~: G, H] == the commmutator subgroup of G and H, i.e., *) (* <<commg_set G H>>> *) (* [~: H1, ..., Hn] == commutator subgroup of H1, ..., Hn (left assoc.) *) (* H <*> G == the subgroup generated by sets H and G (H join G) *) (* (H * G)%G == the join of G H : {group gT} (convertible, but not *) (* identical to (G <*> H)%G) *) (* (\prod_(i ...) H i)%G == the group generated by the H i *) (* {in G, centralised H} <-> G centralises H *) (* {in G, normalised H} <-> G normalises H *) (* <-> forall x, x \in G -> H :^ x = H *) (* 'N(H) == the normaliser of H *) (* 'N_G(H) == the normaliser of H in G *) (* H <| G <=> H is a normal subgroup of G *) (* 'C(H) == the centraliser of H *) (* 'C_G(H) == the centraliser of H in G *) (* gcore H G == the largest subgroup of H normalised by G *) (* If H is a subgroup of G, this is the largest *) (* normal subgroup of G contained in H). *) (* abelian H <=> H is abelian *) (* subgroups G == the set of subgroups of G, i.e., the set of all *) (* H : {group gT} such that H \subset G *) (* In the notation below G is a variable that is bound in P. *) (* [max G | P] <=> G is the largest group such that P holds *) (* [max H of G | P] <=> H is the largest group G such that P holds *) (* [max G | P & Q] := [max G | P && Q], likewise [max H of G | P & Q] *) (* [min G | P] <=> G is the smallest group such that P holds *) (* [min G | P & Q] := [min G | P && Q], likewise [min H of G | P & Q] *) (* [min H of G | P] <=> H is the smallest group G such that P holds *) (* In addition to the generic suffixes described in ssrbool.v and finset.v, *) (* we associate the following suffixes to group operations: *) (* 1 - identity element, as in group1 : 1 \in G *) (* M - multiplication, as is invMg : (x * y)^-1 = y^-1 * x^-1 *) (* Also nat multiplication, for expgM : x ^+ (m * n) = x ^+ m ^+ n *) (* D - (nat) addition, for expgD : x ^+ (m + n) = x ^+ m * x ^+ n *) (* V - inverse, as in mulgV : x * x^-1 = 1 *) (* X - exponentiation, as in conjXg : (x ^+ n) ^ y = (x ^ y) ^+ n *) (* J - conjugation, as in orderJ : #[x ^ y] = #[x] *) (* R - commutator, as in conjRg : [~ x, y] ^ z = [~ x ^ z, y ^ z] *) (* Y - join, as in centY : 'C(G <*> H) = 'C(G) :&: 'C(H) *) (* We sometimes prefix these with an `s' to indicate a set-lifted operation, *) (* e.g., conjsMg : (A * B) :^ x = A :^ x * B :^ x. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope Group_scope. Delimit Scope Group_scope with G. (* This module can be imported to open the scope for group element *) (* operations locally to a file, without exporting the Open to *) (* clients of that file (as Open would do). *) Module GroupScope. Open Scope group_scope. End GroupScope. Import GroupScope. (* These are the operation notations introduced by this file. *) Reserved Notation "[ ~ x1 , x2 , .. , xn ]" (format "'[ ' [ ~ x1 , '/' x2 , '/' .. , '/' xn ] ']'"). Reserved Notation "[ 1 gT ]" (format "[ 1 gT ]"). Reserved Notation "[ 1 ]" (format "[ 1 ]"). Reserved Notation "[ 'subg' G ]" (format "[ 'subg' G ]"). #[warning="-postfix-notation-not-level-1"] Reserved Notation "A ^#" (at level 3, format "A ^#"). Reserved Notation "A :^ x" (at level 35, right associativity). Reserved Notation "x ^: B" (at level 35, right associativity). Reserved Notation "A :^: B" (at level 35, right associativity). Reserved Notation "#| B : A |" (A at level 99, format "#| B : A |"). Reserved Notation "''N' ( A )" (format "''N' ( A )"). Reserved Notation "''N_' G ( A )" (G at level 2, format "''N_' G ( A )"). Reserved Notation "A <| B" (at level 70, no associativity). Reserved Notation "A <*> B" (at level 40, left associativity). Reserved Notation "[ ~: A1 , A2 , .. , An ]" (format "[ ~: '[' A1 , '/' A2 , '/' .. , '/' An ']' ]"). Reserved Notation "[ 'max' A 'of' G | gP ]" (format "[ '[hv' 'max' A 'of' G '/ ' | gP ']' ]"). Reserved Notation "[ 'max' G | gP ]" (format "[ '[hv' 'max' G '/ ' | gP ']' ]"). Reserved Notation "[ 'max' A 'of' G | gP & gQ ]" (format "[ '[hv' 'max' A 'of' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'max' G | gP & gQ ]" (format "[ '[hv' 'max' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'min' A 'of' G | gP ]" (format "[ '[hv' 'min' A 'of' G '/ ' | gP ']' ]"). Reserved Notation "[ 'min' G | gP ]" (format "[ '[hv' 'min' G '/ ' | gP ']' ]"). Reserved Notation "[ 'min' A 'of' G | gP & gQ ]" (format "[ '[hv' 'min' A 'of' G '/ ' | gP '/ ' & gQ ']' ]"). Reserved Notation "[ 'min' G | gP & gQ ]" (format "[ '[hv' 'min' G '/ ' | gP '/ ' & gQ ']' ]"). (* We split the group axiomatisation in two. We define a *) (* class of "base groups", which are basically monoids *) (* with an involutive antimorphism, from which we derive *) (* the class of groups proper. This allows us to reuse *) (* much of the group notation and algebraic axioms for *) (* group subsets, by defining a base group class on them. *) (* We use class/mixins here rather than telescopes to *) (* be able to interoperate with the type coercions. *) (* Another potential benefit (not exploited here) would *) (* be to define a class for infinite groups, which could *) (* share all of the algebraic laws. *) HB.mixin Record isMulBaseGroup G := { mulg_subdef : G -> G -> G; oneg_subdef : G; invg_subdef : G -> G; mulgA_subproof : associative mulg_subdef ; mul1g_subproof : left_id oneg_subdef mulg_subdef ; invgK_subproof : involutive invg_subdef ; invMg_subproof : {morph invg_subdef : x y / mulg_subdef x y >-> mulg_subdef y x} }. (* We want to use sort as a coercion class, both to infer *) (* argument scopes properly, and to allow groups and cosets to *) (* coerce to the base group of group subsets. *) (* However, the return type of group operations should NOT be a *) (* coercion class, since this would trump the real (head-normal) *) (* coercion class for concrete group types, thus spoiling the *) (* coercion of A * B to pred_sort in x \in A * B, or rho * tau to *) (* ffun and Funclass in (rho * tau) x, when rho tau : perm T. *) (* Therefore we define an alias of sort for argument types, and *) (* make it the default coercion FinGroup.base_type >-> Sortclass *) (* so that arguments of a functions whose parameters are of type, *) (* say, gT : finGroupType, can be coerced to the coercion class *) (* of arg_sort. Care should be taken, however, to declare the *) (* return type of functions and operators as FinGroup.sort gT *) (* rather than gT, e.g., mulg : gT -> gT -> FinGroup.sort gT. *) (* Note that since we do this here and in quotient.v for all the *) (* basic functions, the inferred return type should generally be *) (* correct. *) #[arg_sort, short(type="baseFinGroupType")] HB.structure Definition BaseFinGroup := { G of isMulBaseGroup G & Finite G }. Module BaseFinGroupExports. Bind Scope group_scope with BaseFinGroup.arg_sort. Bind Scope group_scope with BaseFinGroup.sort. End BaseFinGroupExports. HB.export BaseFinGroupExports. Module Notations. Section ElementOps. Variable T : baseFinGroupType. Notation rT := (BaseFinGroup.sort T). Definition oneg : rT := Eval unfold oneg_subdef in @oneg_subdef T. Definition mulg : T -> T -> rT := Eval unfold mulg_subdef in @mulg_subdef T. Definition invg : T -> rT := Eval unfold invg_subdef in @invg_subdef T. Definition expgn (x : T) n : rT := iterop n mulg x oneg. End ElementOps. Arguments expgn : simpl never. Notation "1" := (@oneg _) : group_scope. Notation "x1 * x2" := (mulg x1 x2) : group_scope. Notation "x ^-1" := (invg x) : group_scope. Notation "x ^+ n" := (expgn x n) : group_scope. Notation "x ^- n" := (x ^+ n)^-1 : group_scope. End Notations. HB.export Notations. HB.mixin Record BaseFinGroup_isGroup G of BaseFinGroup G := { mulVg_subproof : left_inverse (@oneg G) (@invg _) (@mulg _) }. #[short(type="finGroupType")] HB.structure Definition FinGroup := { G of BaseFinGroup_isGroup G & BaseFinGroup G }. Module FinGroupExports. Bind Scope group_scope with FinGroup.sort. End FinGroupExports. HB.export FinGroupExports. HB.factory Record isMulGroup G of Finite G := { mulg : G -> G -> G; oneg : G; invg : G -> G; mulgA : associative mulg; mul1g : left_id oneg mulg; mulVg : left_inverse oneg invg mulg; }. HB.builders Context G of isMulGroup G. Notation "1" := oneg. Infix "*" := mulg. Notation "x ^-1" := (invg x). Lemma mk_invgK : involutive invg. Proof. have mulV21 x: x^-1^-1 * 1 = x by rewrite -(mulVg x) mulgA mulVg mul1g. by move=> x; rewrite -[_ ^-1]mulV21 -(mul1g 1) mulgA !mulV21. Qed. Lemma mk_invMg : {morph invg : x y / x * y >-> y * x}. Proof. have mulgV x: x * x^-1 = 1 by rewrite -{1}[x]mk_invgK mulVg. move=> x y /=; rewrite -[y^-1 * _]mul1g -(mulVg (x * y)) -2!mulgA (mulgA y). by rewrite mulgV mul1g mulgV -(mulgV (x * y)) mulgA mulVg mul1g. Qed. HB.instance Definition _ := isMulBaseGroup.Build G mulgA mul1g mk_invgK mk_invMg. HB.instance Definition _ := BaseFinGroup_isGroup.Build G mulVg. HB.end. #[compress_coercions] HB.instance Definition _ (T : baseFinGroupType) : Finite (BaseFinGroup.arg_sort T) := Finite.class T. (* Arguments of conjg are restricted to true groups to avoid an *) (* improper interpretation of A ^ B with A and B sets, namely: *) (* {x^-1 * (y * z) | y \in A, x, z \in B} *) Definition conjg (T : finGroupType) (x y : T) := y^-1 * (x * y). Notation "x1 ^ x2" := (conjg x1 x2) : group_scope. Definition commg (T : finGroupType) (x y : T) := x^-1 * x ^ y. Notation "[ ~ x1 , x2 , .. , xn ]" := (commg .. (commg x1 x2) .. xn) : group_scope. Prenex Implicits mulg invg expgn conjg commg. Notation "\prod_ ( i <- r | P ) F" := (\big[mulg/1]_(i <- r | P%B) F%g) : group_scope. Notation "\prod_ ( i <- r ) F" := (\big[mulg/1]_(i <- r) F%g) : group_scope. Notation "\prod_ ( m <= i < n | P ) F" := (\big[mulg/1]_(m <= i < n | P%B) F%g) : group_scope. Notation "\prod_ ( m <= i < n ) F" := (\big[mulg/1]_(m <= i < n) F%g) : group_scope. Notation "\prod_ ( i | P ) F" := (\big[mulg/1]_(i | P%B) F%g) : group_scope. Notation "\prod_ i F" := (\big[mulg/1]_i F%g) : group_scope. Notation "\prod_ ( i : t | P ) F" := (\big[mulg/1]_(i : t | P%B) F%g) (only parsing) : group_scope. Notation "\prod_ ( i : t ) F" := (\big[mulg/1]_(i : t) F%g) (only parsing) : group_scope. Notation "\prod_ ( i < n | P ) F" := (\big[mulg/1]_(i < n | P%B) F%g) : group_scope. Notation "\prod_ ( i < n ) F" := (\big[mulg/1]_(i < n) F%g) : group_scope. Notation "\prod_ ( i 'in' A | P ) F" := (\big[mulg/1]_(i in A | P%B) F%g) : group_scope. Notation "\prod_ ( i 'in' A ) F" := (\big[mulg/1]_(i in A) F%g) : group_scope. Section PreGroupIdentities. Variable T : baseFinGroupType. Implicit Types x y z : T. Local Notation mulgT := (@mulg T). Lemma mulgA : associative mulgT. Proof. exact: mulgA_subproof. Qed. Lemma mul1g : left_id 1 mulgT. Proof. exact: mul1g_subproof. Qed. Lemma invgK : @involutive T invg. Proof. exact: invgK_subproof. Qed. Lemma invMg x y : (x * y)^-1 = y^-1 * x^-1. Proof. exact: invMg_subproof. Qed. Lemma invg_inj : @injective T T invg. Proof. exact: can_inj invgK. Qed. Lemma eq_invg_sym x y : (x^-1 == y) = (x == y^-1). Proof. by apply: (inv_eq invgK). Qed. Lemma invg1 : 1^-1 = 1 :> T. Proof. by apply: invg_inj; rewrite -{1}[1^-1]mul1g invMg invgK mul1g. Qed. Lemma eq_invg1 x : (x^-1 == 1) = (x == 1). Proof. by rewrite eq_invg_sym invg1. Qed. Lemma mulg1 : right_id 1 mulgT. Proof. by move=> x; apply: invg_inj; rewrite invMg invg1 mul1g. Qed. HB.instance Definition _ := Monoid.isLaw.Build T 1 mulgT mulgA mul1g mulg1. Lemma expgnE x n : x ^+ n = iterop n mulg x 1. Proof. by []. Qed. Lemma expg0 x : x ^+ 0 = 1. Proof. by []. Qed. Lemma expg1 x : x ^+ 1 = x. Proof. by []. Qed. Lemma expgS x n : x ^+ n.+1 = x * x ^+ n. Proof. by case: n => //; rewrite mulg1. Qed. Lemma expg1n n : 1 ^+ n = 1 :> T. Proof. by elim: n => // n IHn; rewrite expgS mul1g. Qed. Lemma expgD x n m : x ^+ (n + m) = x ^+ n * x ^+ m. Proof. by elim: n => [|n IHn]; rewrite ?mul1g // !expgS IHn mulgA. Qed. Lemma expgSr x n : x ^+ n.+1 = x ^+ n * x. Proof. by rewrite -addn1 expgD expg1. Qed. Lemma expgM x n m : x ^+ (n * m) = x ^+ n ^+ m. Proof. elim: m => [|m IHm]; first by rewrite muln0 expg0. by rewrite mulnS expgD IHm expgS. Qed. Lemma expgAC x m n : x ^+ m ^+ n = x ^+ n ^+ m. Proof. by rewrite -!expgM mulnC. Qed. Definition commute x y := x * y = y * x. Lemma commute_refl x : commute x x. Proof. by []. Qed. Lemma commute_sym x y : commute x y -> commute y x. Proof. by []. Qed. Lemma commute1 x : commute x 1. Proof. by rewrite /commute mulg1 mul1g. Qed. Lemma commuteM x y z : commute x y -> commute x z -> commute x (y * z). Proof. by move=> cxy cxz; rewrite /commute -mulgA -cxz !mulgA cxy. Qed. Lemma commuteX x y n : commute x y -> commute x (y ^+ n). Proof. by move=> cxy; case: n; [apply: commute1 | elim=> // n; apply: commuteM]. Qed. Lemma commuteX2 x y m n : commute x y -> commute (x ^+ m) (y ^+ n). Proof. by move=> cxy; apply/commuteX/commute_sym/commuteX. Qed. Lemma expgVn x n : x^-1 ^+ n = x ^- n. Proof. by elim: n => [|n IHn]; rewrite ?invg1 // expgSr expgS invMg IHn. Qed. Lemma expgMn x y n : commute x y -> (x * y) ^+ n = x ^+ n * y ^+ n. Proof. move=> cxy; elim: n => [|n IHn]; first by rewrite mulg1. by rewrite !expgS IHn -mulgA (mulgA y) (commuteX _ (commute_sym cxy)) !mulgA. Qed. End PreGroupIdentities. #[global] Hint Resolve commute1 : core. Arguments invg_inj {T} [x1 x2]. Prenex Implicits commute invgK. Section GroupIdentities. Variable T : finGroupType. Implicit Types x y z : T. Local Notation mulgT := (@mulg T). Lemma mulVg : left_inverse 1 invg mulgT. Proof. exact: mulVg_subproof. Qed. Lemma mulgV : right_inverse 1 invg mulgT. Proof. by move=> x; rewrite -{1}(invgK x) mulVg. Qed. Lemma mulKg : left_loop invg mulgT. Proof. by move=> x y; rewrite mulgA mulVg mul1g. Qed. Lemma mulKVg : rev_left_loop invg mulgT. Proof. by move=> x y; rewrite mulgA mulgV mul1g. Qed. Lemma mulgI : right_injective mulgT. Proof. by move=> x; apply: can_inj (mulKg x). Qed. Lemma mulgK : right_loop invg mulgT. Proof. by move=> x y; rewrite -mulgA mulgV mulg1. Qed. Lemma mulgKV : rev_right_loop invg mulgT. Proof. by move=> x y; rewrite -mulgA mulVg mulg1. Qed. Lemma mulIg : left_injective mulgT. Proof. by move=> x; apply: can_inj (mulgK x). Qed. Lemma eq_invg_mul x y : (x^-1 == y :> T) = (x * y == 1 :> T). Proof. by rewrite -(inj_eq (@mulgI x)) mulgV eq_sym. Qed. Lemma eq_mulgV1 x y : (x == y) = (x * y^-1 == 1 :> T). Proof. by rewrite -(inj_eq invg_inj) eq_invg_mul. Qed. Lemma eq_mulVg1 x y : (x == y) = (x^-1 * y == 1 :> T). Proof. by rewrite -eq_invg_mul invgK. Qed. Lemma commuteV x y : commute x y -> commute x y^-1. Proof. by move=> cxy; apply: (@mulIg y); rewrite mulgKV -mulgA cxy mulKg. Qed. Lemma conjgE x y : x ^ y = y^-1 * (x * y). Proof. by []. Qed. Lemma conjgC x y : x * y = y * x ^ y. Proof. by rewrite mulKVg. Qed. Lemma conjgCV x y : x * y = y ^ x^-1 * x. Proof. by rewrite -mulgA mulgKV invgK. Qed. Lemma conjg1 x : x ^ 1 = x. Proof. by rewrite conjgE commute1 mulKg. Qed. Lemma conj1g x : 1 ^ x = 1. Proof. by rewrite conjgE mul1g mulVg. Qed. Lemma conjMg x y z : (x * y) ^ z = x ^ z * y ^ z. Proof. by rewrite !conjgE !mulgA mulgK. Qed. Lemma conjgM x y z : x ^ (y * z) = (x ^ y) ^ z. Proof. by rewrite !conjgE invMg !mulgA. Qed. Lemma conjVg x y : x^-1 ^ y = (x ^ y)^-1. Proof. by rewrite !conjgE !invMg invgK mulgA. Qed. Lemma conjJg x y z : (x ^ y) ^ z = (x ^ z) ^ y ^ z. Proof. by rewrite 2!conjMg conjVg. Qed. Lemma conjXg x y n : (x ^+ n) ^ y = (x ^ y) ^+ n. Proof. by elim: n => [|n IHn]; rewrite ?conj1g // !expgS conjMg IHn. Qed. Lemma conjgK : @right_loop T T invg conjg. Proof. by move=> y x; rewrite -conjgM mulgV conjg1. Qed. Lemma conjgKV : @rev_right_loop T T invg conjg. Proof. by move=> y x; rewrite -conjgM mulVg conjg1. Qed. Lemma conjg_inj : @left_injective T T T conjg. Proof. by move=> y; apply: can_inj (conjgK y). Qed. Lemma conjg_eq1 x y : (x ^ y == 1) = (x == 1). Proof. by rewrite (canF_eq (conjgK _)) conj1g. Qed. Lemma conjg_prod I r (P : pred I) F z : (\prod_(i <- r | P i) F i) ^ z = \prod_(i <- r | P i) (F i ^ z). Proof. by apply: (big_morph (conjg^~ z)) => [x y|]; rewrite ?conj1g ?conjMg. Qed. Lemma commgEl x y : [~ x, y] = x^-1 * x ^ y. Proof. by []. Qed. Lemma commgEr x y : [~ x, y] = y^-1 ^ x * y. Proof. by rewrite -!mulgA. Qed. Lemma commgC x y : x * y = y * x * [~ x, y]. Proof. by rewrite -mulgA !mulKVg. Qed. Lemma commgCV x y : x * y = [~ x^-1, y^-1] * (y * x). Proof. by rewrite commgEl !mulgA !invgK !mulgKV. Qed. Lemma conjRg x y z : [~ x, y] ^ z = [~ x ^ z, y ^ z]. Proof. by rewrite !conjMg !conjVg. Qed. Lemma invg_comm x y : [~ x, y]^-1 = [~ y, x]. Proof. by rewrite commgEr conjVg invMg invgK. Qed. Lemma commgP x y : reflect (commute x y) ([~ x, y] == 1 :> T). Proof. by rewrite [[~ x, y]]mulgA -invMg -eq_mulVg1 eq_sym; apply: eqP. Qed. Lemma conjg_fixP x y : reflect (x ^ y = x) ([~ x, y] == 1 :> T). Proof. by rewrite -eq_mulVg1 eq_sym; apply: eqP. Qed. Lemma commg1_sym x y : ([~ x, y] == 1 :> T) = ([~ y, x] == 1 :> T). Proof. by rewrite -invg_comm (inv_eq invgK) invg1. Qed. Lemma commg1 x : [~ x, 1] = 1. Proof. exact/eqP/commgP. Qed. Lemma comm1g x : [~ 1, x] = 1. Proof. by rewrite -invg_comm commg1 invg1. Qed. Lemma commgg x : [~ x, x] = 1. Proof. exact/eqP/commgP. Qed. Lemma commgXg x n : [~ x, x ^+ n] = 1. Proof. exact/eqP/commgP/commuteX. Qed. Lemma commgVg x : [~ x, x^-1] = 1. Proof. exact/eqP/commgP/commuteV. Qed. Lemma commgXVg x n : [~ x, x ^- n] = 1. Proof. exact/eqP/commgP/commuteV/commuteX. Qed. (* Other commg identities should slot in here. *) End GroupIdentities. #[global] Hint Rewrite mulg1 @mul1g invg1 @mulVg mulgV (@invgK) mulgK mulgKV @invMg @mulgA : gsimpl. Ltac gsimpl := autorewrite with gsimpl; try done. Definition gsimp := (@mulg1, @mul1g, (@invg1, @invgK), (@mulgV, @mulVg)). Definition gnorm := (gsimp, (@mulgK, @mulgKV, (@mulgA, @invMg))). Arguments mulgI [T]. Arguments mulIg [T]. Arguments conjg_inj {T} x [x1 x2]. Arguments commgP {T x y}. Arguments conjg_fixP {T x y}. Section Repr. (* Plucking a set representative. *) Variable gT : baseFinGroupType. Implicit Type A : {set gT}. Definition repr A := if 1 \in A then 1 else odflt 1 [pick x in A]. Lemma mem_repr A x : x \in A -> repr A \in A. Proof. by rewrite /repr; case: ifP => // _; case: pickP => // A0; rewrite [x \in A]A0. Qed. Lemma card_mem_repr A : #|A| > 0 -> repr A \in A. Proof. by rewrite lt0n => /existsP[x]; apply: mem_repr. Qed. Lemma repr_set1 x : repr [set x] = x. Proof. by apply/set1P/card_mem_repr; rewrite cards1. Qed. Lemma repr_set0 : repr set0 = 1. Proof. by rewrite /repr; case: pickP => [x|_] /[!inE]. Qed. End Repr. Arguments mem_repr [gT A]. Section BaseSetMulDef. (* We only assume a baseFinGroupType to allow this construct to be iterated. *) Variable gT : baseFinGroupType. Implicit Types A B : {set gT}. (* Set-lifted group operations. *) Definition set_mulg A B := mulg @2: (A, B). Definition set_invg A := invg @^-1: A. (* The pre-group structure of group subsets. *) Lemma set_mul1g : left_id [set 1] set_mulg. Proof. move=> A; apply/setP=> y; apply/imset2P/idP=> [[_ x /set1P-> Ax ->] | Ay]. by rewrite mul1g. by exists (1 : gT) y; rewrite ?(set11, mul1g). Qed. Lemma set_mulgA : associative set_mulg. Proof. move=> A B C; apply/setP=> y. apply/imset2P/imset2P=> [[x1 z Ax1 /imset2P[x2 x3 Bx2 Cx3 ->] ->]| [z x3]]. by exists (x1 * x2) x3; rewrite ?mulgA //; apply/imset2P; exists x1 x2. case/imset2P=> x1 x2 Ax1 Bx2 -> Cx3 ->. by exists x1 (x2 * x3); rewrite ?mulgA //; apply/imset2P; exists x2 x3. Qed. Lemma set_invgK : involutive set_invg. Proof. by move=> A; apply/setP=> x; rewrite !inE invgK. Qed. Lemma set_invgM : {morph set_invg : A B / set_mulg A B >-> set_mulg B A}. Proof. move=> A B; apply/setP=> z; rewrite inE. apply/imset2P/imset2P=> [[x y Ax By /(canRL invgK)->] | [y x]]. by exists y^-1 x^-1; rewrite ?invMg // inE invgK. by rewrite !inE => By1 Ax1 ->; exists x^-1 y^-1; rewrite ?invMg. Qed. HB.instance Definition set_base_group := isMulBaseGroup.Build (set_type gT) set_mulgA set_mul1g set_invgK set_invgM. HB.instance Definition _ : isMulBaseGroup {set gT} := set_base_group. End BaseSetMulDef. (* Time to open the bag of dirty tricks. When we define groups down below *) (* as a subtype of {set gT}, we need them to be able to coerce to sets in *) (* both set-style contexts (x \in G) and monoid-style contexts (G * H), *) (* and we need the coercion function to be EXACTLY the structure *) (* projection in BOTH cases -- otherwise the canonical unification breaks.*) (* Alas, Coq doesn't let us use the same coercion function twice, even *) (* when the targets are convertible. Our workaround (ab)uses the module *) (* system to declare two different identity coercions on an alias class. *) Module GroupSet. Definition sort (gT : baseFinGroupType) := {set gT}. End GroupSet. Identity Coercion GroupSet_of_sort : GroupSet.sort >-> set_of. Module Type GroupSetBaseGroupSig. Definition sort (gT : baseFinGroupType) := BaseFinGroup.arg_sort {set gT}. End GroupSetBaseGroupSig. Module MakeGroupSetBaseGroup (Gset_base : GroupSetBaseGroupSig). Identity Coercion of_sort : Gset_base.sort >-> BaseFinGroup.arg_sort. End MakeGroupSetBaseGroup. Module Export GroupSetBaseGroup := MakeGroupSetBaseGroup GroupSet. HB.instance Definition _ gT : Finite (GroupSet.sort gT) := Finite.class {set gT}. Section GroupSetMulDef. (* Some of these constructs could be defined on a baseFinGroupType. *) (* We restrict them to proper finGroupType because we only develop *) (* the theory for that case. *) Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Type x y : gT. Definition lcoset A x := mulg x @: A. Definition rcoset A x := mulg^~ x @: A. Definition lcosets A B := lcoset A @: B. Definition rcosets A B := rcoset A @: B. Definition indexg B A := #|rcosets A B|. Definition conjugate A x := conjg^~ x @: A. Definition conjugates A B := conjugate A @: B. Definition class x B := conjg x @: B. Definition classes A := class^~ A @: A. Definition class_support A B := conjg @2: (A, B). Definition commg_set A B := commg @2: (A, B). (* These will only be used later, but are defined here so that we can *) (* keep all the Notation together. *) Definition normaliser A := [set x | conjugate A x \subset A]. Definition centraliser A := \bigcap_(x in A) normaliser [set x]. Definition abelian A := A \subset centraliser A. Definition normal A B := (A \subset B) && (B \subset normaliser A). (* "normalised" and "centralise[s|d]" are intended to be used with *) (* the {in ...} form, as in abelian below. *) Definition normalised A := forall x, conjugate A x = A. Definition centralises x A := forall y, y \in A -> commute x y. Definition centralised A := forall x, centralises x A. End GroupSetMulDef. Arguments lcoset _ _%_g _%_g. Arguments rcoset _ _%_g _%_g. Arguments rcosets _ _%_g _%_g. Arguments lcosets _ _%_g _%_g. Arguments indexg _ _%_g _%_g. Arguments conjugate _ _%_g _%_g. Arguments conjugates _ _%_g _%_g. Arguments class _ _%_g _%_g. Arguments classes _ _%_g. Arguments class_support _ _%_g _%_g. Arguments commg_set _ _%_g _%_g. Arguments normaliser _ _%_g. Arguments centraliser _ _%_g. Arguments abelian _ _%_g. Arguments normal _ _%_g _%_g. Arguments normalised _ _%_g. Arguments centralises _ _%_g _%_g. Arguments centralised _ _%_g. Notation "[ 1 gT ]" := (1 : {set gT}) : group_scope. Notation "[ 1 ]" := [1 FinGroup.sort _] : group_scope. Notation "A ^#" := (A :\ 1) : group_scope. Notation "x *: A" := ([set x%g] * A) : group_scope. Notation "A :* x" := (A * [set x%g]) : group_scope. Notation "A :^ x" := (conjugate A x) : group_scope. Notation "x ^: B" := (class x B) : group_scope. Notation "A :^: B" := (conjugates A B) : group_scope. Notation "#| B : A |" := (indexg B A) : group_scope. (* No notation for lcoset and rcoset, which are to be used mostly *) (* in curried form; x *: B and A :* 1 denote singleton products, *) (* so we can use mulgA, mulg1, etc, on, say, A :* 1 * B :* x. *) (* No notation for the set commutator generator set commg_set. *) Notation "''N' ( A )" := (normaliser A) : group_scope. Notation "''N_' G ( A )" := (G%g :&: 'N(A)) : group_scope. Notation "A <| B" := (normal A B) : group_scope. Notation "''C' ( A )" := (centraliser A) : group_scope. Notation "''C_' G ( A )" := (G%g :&: 'C(A)) : group_scope. Notation "''C_' ( G ) ( A )" := 'C_G(A) (only parsing) : group_scope. Notation "''C' [ x ]" := 'N([set x%g]) : group_scope. Notation "''C_' G [ x ]" := 'N_G([set x%g]) : group_scope. Notation "''C_' ( G ) [ x ]" := 'C_G[x] (only parsing) : group_scope. Prenex Implicits repr lcoset rcoset lcosets rcosets normal. Prenex Implicits conjugate conjugates class classes class_support. Prenex Implicits commg_set normalised centralised abelian. Section BaseSetMulProp. (* Properties of the purely multiplicative structure. *) Variable gT : baseFinGroupType. Implicit Types A B C D : {set gT}. Implicit Type x y z : gT. (* Set product. We already have all the pregroup identities, so we *) (* only need to add the monotonicity rules. *) Lemma mulsgP A B x : reflect (imset2_spec mulg (mem A) (fun _ => mem B) x) (x \in A * B). Proof. exact: imset2P. Qed. Lemma mem_mulg A B x y : x \in A -> y \in B -> x * y \in A * B. Proof. by move=> Ax By; apply/mulsgP; exists x y. Qed. Lemma prodsgP (I : finType) (P : pred I) (A : I -> {set gT}) x : reflect (exists2 c, forall i, P i -> c i \in A i & x = \prod_(i | P i) c i) (x \in \prod_(i | P i) A i). Proof. have [r big_r [Ur mem_r] _] := big_enumP P. pose inA c := all (fun i => c i \in A i); rewrite -big_r; set piAx := x \in _. suffices{big_r} IHr: reflect (exists2 c, inA c r & x = \prod_(i <- r) c i) piAx. apply: (iffP IHr) => -[c inAc ->]; do [exists c; last by rewrite big_r]. by move=> i Pi; rewrite (allP inAc) ?mem_r. by apply/allP=> i; rewrite mem_r => /inAc. elim: {P mem_r}r x @piAx Ur => /= [x _ | i r IHr x /andP[r'i /IHr{}IHr]]. by rewrite unlock; apply: (iffP set1P) => [-> | [] //]; exists (fun=> x). rewrite big_cons; apply: (iffP idP) => [|[c /andP[Aci Ac] ->]]; last first. by rewrite big_cons mem_mulg //; apply/IHr=> //; exists c. case/mulsgP=> c_i _ Ac_i /IHr[c /allP-inAcr ->] ->{x}. exists [eta c with i |-> c_i]; rewrite /= ?big_cons eqxx ?Ac_i. by apply/allP=> j rj; rewrite /= ifN ?(memPn r'i) ?inAcr. by congr (_ * _); apply: eq_big_seq => j rj; rewrite ifN ?(memPn r'i). Qed. Lemma mem_prodg (I : finType) (P : pred I) (A : I -> {set gT}) c : (forall i, P i -> c i \in A i) -> \prod_(i | P i) c i \in \prod_(i | P i) A i. Proof. by move=> Ac; apply/prodsgP; exists c. Qed. Lemma mulSg A B C : A \subset B -> A * C \subset B * C. Proof. exact: imset2Sl. Qed. Lemma mulgS A B C : B \subset C -> A * B \subset A * C. Proof. exact: imset2Sr. Qed. Lemma mulgSS A B C D : A \subset B -> C \subset D -> A * C \subset B * D. Proof. exact: imset2S. Qed. Lemma mulg_subl A B : 1 \in B -> A \subset A * B. Proof. by move=> B1; rewrite -{1}(mulg1 A) mulgS ?sub1set. Qed. Lemma mulg_subr A B : 1 \in A -> B \subset A * B. Proof. by move=> A1; rewrite -{1}(mul1g B) mulSg ?sub1set. Qed. Lemma mulUg A B C : (A :|: B) * C = (A * C) :|: (B * C). Proof. exact: imset2Ul. Qed. Lemma mulgU A B C : A * (B :|: C) = (A * B) :|: (A * C). Proof. exact: imset2Ur. Qed. (* Set (pointwise) inverse. *) Lemma invUg A B : (A :|: B)^-1 = A^-1 :|: B^-1. Proof. exact: preimsetU. Qed. Lemma invIg A B : (A :&: B)^-1 = A^-1 :&: B^-1. Proof. exact: preimsetI. Qed. Lemma invDg A B : (A :\: B)^-1 = A^-1 :\: B^-1. Proof. exact: preimsetD. Qed. Lemma invCg A : (~: A)^-1 = ~: A^-1. Proof. exact: preimsetC. Qed. Lemma invSg A B : (A^-1 \subset B^-1) = (A \subset B). Proof. by rewrite !(sameP setIidPl eqP) -invIg (inj_eq invg_inj). Qed. Lemma mem_invg x A : (x \in A^-1) = (x^-1 \in A). Proof. by rewrite inE. Qed. Lemma memV_invg x A : (x^-1 \in A^-1) = (x \in A). Proof. by rewrite inE invgK. Qed. Lemma card_invg A : #|A^-1| = #|A|. Proof. exact/card_preimset/invg_inj. Qed. (* Product with singletons. *) Lemma set1gE : 1 = [set 1] :> {set gT}. Proof. by []. Qed. Lemma set1gP x : reflect (x = 1) (x \in [1 gT]). Proof. exact: set1P. Qed. Lemma mulg_set1 x y : [set x] :* y = [set x * y]. Proof. by rewrite [_ * _]imset2_set1l imset_set1. Qed. Lemma invg_set1 x : [set x]^-1 = [set x^-1]. Proof. by apply/setP=> y; rewrite !inE inv_eq //; apply: invgK. Qed. End BaseSetMulProp. Arguments set1gP {gT x}. Arguments mulsgP {gT A B x}. Arguments prodsgP {gT I P A x}. Section GroupSetMulProp. (* Constructs that need a finGroupType *) Variable gT : finGroupType. Implicit Types A B C D : {set gT}. Implicit Type x y z : gT. (* Left cosets. *) Lemma lcosetE A x : lcoset A x = x *: A. Proof. by rewrite [_ * _]imset2_set1l. Qed. Lemma card_lcoset A x : #|x *: A| = #|A|. Proof. by rewrite -lcosetE (card_imset _ (mulgI _)). Qed. Lemma mem_lcoset A x y : (y \in x *: A) = (x^-1 * y \in A). Proof. by rewrite -lcosetE [_ x](can_imset_pre _ (mulKg _)) inE. Qed. Lemma lcosetP A x y : reflect (exists2 a, a \in A & y = x * a) (y \in x *: A). Proof. by rewrite -lcosetE; apply: imsetP. Qed. Lemma lcosetsP A B C : reflect (exists2 x, x \in B & C = x *: A) (C \in lcosets A B). Proof. by apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?lcosetE. Qed. Lemma lcosetM A x y : (x * y) *: A = x *: (y *: A). Proof. by rewrite -mulg_set1 mulgA. Qed. Lemma lcoset1 A : 1 *: A = A. Proof. exact: mul1g. Qed. Lemma lcosetK : left_loop invg (fun x A => x *: A). Proof. by move=> x A; rewrite -lcosetM mulVg mul1g. Qed. Lemma lcosetKV : rev_left_loop invg (fun x A => x *: A). Proof. by move=> x A; rewrite -lcosetM mulgV mul1g. Qed. Lemma lcoset_inj : right_injective (fun x A => x *: A). Proof. by move=> x; apply: can_inj (lcosetK x). Qed. Lemma lcosetS x A B : (x *: A \subset x *: B) = (A \subset B). Proof. apply/idP/idP=> sAB; last exact: mulgS. by rewrite -(lcosetK x A) -(lcosetK x B) mulgS. Qed. Lemma sub_lcoset x A B : (A \subset x *: B) = (x^-1 *: A \subset B). Proof. by rewrite -(lcosetS x^-1) lcosetK. Qed. Lemma sub_lcosetV x A B : (A \subset x^-1 *: B) = (x *: A \subset B). Proof. by rewrite sub_lcoset invgK. Qed. (* Right cosets. *) Lemma rcosetE A x : rcoset A x = A :* x. Proof. by rewrite [_ * _]imset2_set1r. Qed. Lemma card_rcoset A x : #|A :* x| = #|A|. Proof. by rewrite -rcosetE (card_imset _ (mulIg _)). Qed. Lemma mem_rcoset A x y : (y \in A :* x) = (y * x^-1 \in A). Proof. by rewrite -rcosetE [_ x](can_imset_pre A (mulgK _)) inE. Qed. Lemma rcosetP A x y : reflect (exists2 a, a \in A & y = a * x) (y \in A :* x). Proof. by rewrite -rcosetE; apply: imsetP. Qed. Lemma rcosetsP A B C : reflect (exists2 x, x \in B & C = A :* x) (C \in rcosets A B). Proof. by apply: (iffP imsetP) => [] [x Bx ->]; exists x; rewrite ?rcosetE. Qed. Lemma rcosetM A x y : A :* (x * y) = A :* x :* y. Proof. by rewrite -mulg_set1 mulgA. Qed. Lemma rcoset1 A : A :* 1 = A. Proof. exact: mulg1. Qed. Lemma rcosetK : right_loop invg (fun A x => A :* x). Proof. by move=> x A; rewrite -rcosetM mulgV mulg1. Qed. Lemma rcosetKV : rev_right_loop invg (fun A x => A :* x). Proof. by move=> x A; rewrite -rcosetM mulVg mulg1. Qed. Lemma rcoset_inj : left_injective (fun A x => A :* x). Proof. by move=> x; apply: can_inj (rcosetK x). Qed. Lemma rcosetS x A B : (A :* x \subset B :* x) = (A \subset B). Proof. apply/idP/idP=> sAB; last exact: mulSg. by rewrite -(rcosetK x A) -(rcosetK x B) mulSg. Qed. Lemma sub_rcoset x A B : (A \subset B :* x) = (A :* x ^-1 \subset B). Proof. by rewrite -(rcosetS x^-1) rcosetK. Qed. Lemma sub_rcosetV x A B : (A \subset B :* x^-1) = (A :* x \subset B). Proof. by rewrite sub_rcoset invgK. Qed. (* Inverse maps lcosets to rcosets *) Lemma invg_lcosets A B : (lcosets A B)^-1 = rcosets A^-1 B^-1. Proof. rewrite /A^-1/= -![_^-1](can_imset_pre _ invgK) -[RHS]imset_comp -imset_comp. by apply: eq_imset => x /=; rewrite lcosetE rcosetE invMg invg_set1. Qed. (* Conjugates. *) Lemma conjg_preim A x : A :^ x = (conjg^~ x^-1) @^-1: A. Proof. exact: can_imset_pre (conjgK _). Qed. Lemma mem_conjg A x y : (y \in A :^ x) = (y ^ x^-1 \in A). Proof. by rewrite conjg_preim inE. Qed. Lemma mem_conjgV A x y : (y \in A :^ x^-1) = (y ^ x \in A). Proof. by rewrite mem_conjg invgK. Qed. Lemma memJ_conjg A x y : (y ^ x \in A :^ x) = (y \in A). Proof. by rewrite mem_conjg conjgK. Qed. Lemma conjsgE A x : A :^ x = x^-1 *: (A :* x). Proof. by apply/setP=> y; rewrite mem_lcoset mem_rcoset -mulgA mem_conjg. Qed. Lemma conjsg1 A : A :^ 1 = A. Proof. by rewrite conjsgE invg1 mul1g mulg1. Qed. Lemma conjsgM A x y : A :^ (x * y) = (A :^ x) :^ y. Proof. by rewrite !conjsgE invMg -!mulg_set1 !mulgA. Qed. Lemma conjsgK : @right_loop _ gT invg conjugate. Proof. by move=> x A; rewrite -conjsgM mulgV conjsg1. Qed. Lemma conjsgKV : @rev_right_loop _ gT invg conjugate. Proof. by move=> x A; rewrite -conjsgM mulVg conjsg1. Qed. Lemma conjsg_inj : @left_injective _ gT _ conjugate. Proof. by move=> x; apply: can_inj (conjsgK x). Qed. Lemma cardJg A x : #|A :^ x| = #|A|. Proof. by rewrite (card_imset _ (conjg_inj x)). Qed. Lemma conjSg A B x : (A :^ x \subset B :^ x) = (A \subset B). Proof. by rewrite !conjsgE lcosetS rcosetS. Qed. Lemma properJ A B x : (A :^ x \proper B :^ x) = (A \proper B). Proof. by rewrite /proper !conjSg. Qed. Lemma sub_conjg A B x : (A :^ x \subset B) = (A \subset B :^ x^-1). Proof. by rewrite -(conjSg A _ x) conjsgKV. Qed. Lemma sub_conjgV A B x : (A :^ x^-1 \subset B) = (A \subset B :^ x). Proof. by rewrite -(conjSg _ B x) conjsgKV. Qed. Lemma conjg_set1 x y : [set x] :^ y = [set x ^ y]. Proof. by rewrite [_ :^ _]imset_set1. Qed. Lemma conjs1g x : 1 :^ x = 1. Proof. by rewrite conjg_set1 conj1g. Qed. Lemma conjsg_eq1 A x : (A :^ x == 1%g) = (A == 1%g). Proof. by rewrite (canF_eq (conjsgK x)) conjs1g. Qed. Lemma conjsMg A B x : (A * B) :^ x = A :^ x * B :^ x. Proof. by rewrite !conjsgE !mulgA rcosetK. Qed. Lemma conjIg A B x : (A :&: B) :^ x = A :^ x :&: B :^ x. Proof. by rewrite !conjg_preim preimsetI. Qed. Lemma conj0g x : set0 :^ x = set0. Proof. exact: imset0. Qed. Lemma conjTg x : [set: gT] :^ x = [set: gT]. Proof. by rewrite conjg_preim preimsetT. Qed. Lemma bigcapJ I r (P : pred I) (B : I -> {set gT}) x : \bigcap_(i <- r | P i) (B i :^ x) = (\bigcap_(i <- r | P i) B i) :^ x. Proof. by rewrite (big_endo (conjugate^~ x)) => // [B1 B2|]; rewrite (conjTg, conjIg). Qed. Lemma conjUg A B x : (A :|: B) :^ x = A :^ x :|: B :^ x. Proof. by rewrite !conjg_preim preimsetU. Qed. Lemma bigcupJ I r (P : pred I) (B : I -> {set gT}) x : \bigcup_(i <- r | P i) (B i :^ x) = (\bigcup_(i <- r | P i) B i) :^ x. Proof. rewrite (big_endo (conjugate^~ x)) => // [B1 B2|]; first by rewrite conjUg. exact: imset0. Qed. Lemma conjCg A x : (~: A) :^ x = ~: A :^ x. Proof. by rewrite !conjg_preim preimsetC. Qed. Lemma conjDg A B x : (A :\: B) :^ x = A :^ x :\: B :^ x. Proof. by rewrite !setDE !(conjCg, conjIg). Qed. Lemma conjD1g A x : A^# :^ x = (A :^ x)^#. Proof. by rewrite conjDg conjs1g. Qed. (* Classes; not much for now. *) Lemma memJ_class x y A : y \in A -> x ^ y \in x ^: A. Proof. exact: imset_f. Qed. Lemma classS x A B : A \subset B -> x ^: A \subset x ^: B. Proof. exact: imsetS. Qed. Lemma class_set1 x y : x ^: [set y] = [set x ^ y]. Proof. exact: imset_set1. Qed. Lemma class1g x A : x \in A -> 1 ^: A = 1. Proof. move=> Ax; apply/setP=> y. by apply/imsetP/set1P=> [[a Aa]|] ->; last exists x; rewrite ?conj1g. Qed. Lemma classVg x A : x^-1 ^: A = (x ^: A)^-1. Proof. apply/setP=> xy; rewrite inE; apply/imsetP/imsetP=> [] [y Ay def_xy]. by rewrite def_xy conjVg invgK; exists y. by rewrite -[xy]invgK def_xy -conjVg; exists y. Qed. Lemma mem_classes x A : x \in A -> x ^: A \in classes A. Proof. exact: imset_f. Qed. Lemma memJ_class_support A B x y : x \in A -> y \in B -> x ^ y \in class_support A B. Proof. by move=> Ax By; apply: imset2_f. Qed. Lemma class_supportM A B C : class_support A (B * C) = class_support (class_support A B) C. Proof. apply/setP=> x; apply/imset2P/imset2P=> [[a y Aa] | [y c]]. case/mulsgP=> b c Bb Cc -> ->{x y}. by exists (a ^ b) c; rewrite ?(imset2_f, conjgM). case/imset2P=> a b Aa Bb -> Cc ->{x y}. by exists a (b * c); rewrite ?(mem_mulg, conjgM). Qed. Lemma class_support_set1l A x : class_support [set x] A = x ^: A. Proof. exact: imset2_set1l. Qed. Lemma class_support_set1r A x : class_support A [set x] = A :^ x. Proof. exact: imset2_set1r. Qed. Lemma classM x A B : x ^: (A * B) = class_support (x ^: A) B. Proof. by rewrite -!class_support_set1l class_supportM. Qed. Lemma class_lcoset x y A : x ^: (y *: A) = (x ^ y) ^: A. Proof. by rewrite classM class_set1 class_support_set1l. Qed. Lemma class_rcoset x A y : x ^: (A :* y) = (x ^: A) :^ y. Proof. by rewrite -class_support_set1r classM. Qed. (* Conjugate set. *) Lemma conjugatesS A B C : B \subset C -> A :^: B \subset A :^: C. Proof. exact: imsetS. Qed. Lemma conjugates_set1 A x : A :^: [set x] = [set A :^ x]. Proof. exact: imset_set1. Qed. Lemma conjugates_conj A x B : (A :^ x) :^: B = A :^: (x *: B). Proof. rewrite /conjugates [x *: B]imset2_set1l -imset_comp. by apply: eq_imset => y /=; rewrite conjsgM. Qed. (* Class support. *) Lemma class_supportEl A B : class_support A B = \bigcup_(x in A) x ^: B. Proof. exact: curry_imset2l. Qed. Lemma class_supportEr A B : class_support A B = \bigcup_(x in B) A :^ x. Proof. exact: curry_imset2r. Qed. (* Groups (at last!) *) Definition group_set A := (1 \in A) && (A * A \subset A). Lemma group_setP A : reflect (1 \in A /\ {in A & A, forall x y, x * y \in A}) (group_set A). Proof. apply: (iffP andP) => [] [A1 AM]; split=> {A1}//. by move=> x y Ax Ay; apply: (subsetP AM); rewrite mem_mulg. by apply/subsetP=> _ /mulsgP[x y Ax Ay ->]; apply: AM. Qed. Structure group_type : Type := Group { gval :> GroupSet.sort gT; _ : group_set gval }. Definition group_of : predArgType := group_type. Local Notation groupT := group_of. Identity Coercion type_of_group : group_of >-> group_type. HB.instance Definition _ := [isSub for gval]. #[hnf] HB.instance Definition _ := [Finite of group_type by <:]. (* No predType or baseFinGroupType structures, as these would hide the *) (* group-to-set coercion and thus spoil unification. *) HB.instance Definition _ := SubFinite.copy groupT group_type. Definition group (A : {set gT}) gA : groupT := @Group A gA. Definition clone_group G := let: Group _ gP := G return {type of Group for G} -> groupT in fun k => k gP. Lemma group_inj : injective gval. Proof. exact: val_inj. Qed. Lemma groupP (G : groupT) : group_set G. Proof. by case: G. Qed. Lemma congr_group (H K : groupT) : H = K -> H :=: K. Proof. exact: congr1. Qed. Lemma isgroupP A : reflect (exists G : groupT, A = G) (group_set A). Proof. by apply: (iffP idP) => [gA | [[B gB] -> //]]; exists (Group gA). Qed. Lemma group_set_one : group_set 1. Proof. by rewrite /group_set set11 mulg1 subxx. Qed. Canonical one_group := group group_set_one. Canonical set1_group := @group [set 1] group_set_one. Lemma group_setT : group_set (setTfor gT). Proof. by apply/group_setP; split=> [|x y _ _]; rewrite inE. Qed. Canonical setT_group := group group_setT. End GroupSetMulProp. Arguments group_of gT%_type. Arguments lcosetP {gT A x y}. Arguments lcosetsP {gT A B C}. Arguments rcosetP {gT A x y}. Arguments rcosetsP {gT A B C}. Arguments group_setP {gT A}. Arguments setT_group gT%_type. Prenex Implicits group_set mulsgP set1gP. Notation "{ 'group' gT }" := (group_of gT) (format "{ 'group' gT }") : type_scope. Notation "[ 'group' 'of' G ]" := (clone_group (@group _ G)) (format "[ 'group' 'of' G ]") : form_scope. Bind Scope Group_scope with group_type. Bind Scope Group_scope with group_of. Notation "1" := (one_group _) : Group_scope. Notation "[ 1 gT ]" := (1%G : {group gT}) : Group_scope. Notation "[ 'set' : gT ]" := (setT_group gT) : Group_scope. (* These definitions come early so we can establish the Notation. *) HB.lock Definition generated (gT : finGroupType) (A : {set gT}) := \bigcap_(G : {group gT} | A \subset G) G. Canonical generated_unlockable := Unlockable generated.unlock. Definition gcore (gT : finGroupType) (A B : {set gT}) := \bigcap_(x in B) A :^ x. Definition joing (gT : finGroupType) (A B : {set gT}) := generated (A :|: B). Definition commutator (gT : finGroupType) (A B : {set gT}) := generated (commg_set A B). Definition cycle (gT : finGroupType) (x : gT) := generated [set x]. Definition order (gT : finGroupType) (x : gT) := #|cycle x|. Arguments commutator _ _%_g _%_g. Arguments joing _ _%_g _%_g. Arguments generated _ _%_g. (* Helper notation for defining new groups that need a bespoke finGroupType. *) (* The actual group for such a type (say, my_gT) will be the full group, *) (* i.e., [set: my_gT] or [set: my_gT]%G, but Coq will not recognize *) (* specific notation for these because of the coercions inserted during type *) (* inference, unless they are defined as [set: gsort my_gT] using the *) (* Notation below. *) Notation gsort gT := (BaseFinGroup.arg_sort gT%type) (only parsing). Notation "<< A >>" := (generated A) : group_scope. Notation "<[ x ] >" := (cycle x) : group_scope. Notation "#[ x ]" := (order x) : group_scope. Notation "A <*> B" := (joing A B) : group_scope. Notation "[ ~: A1 , A2 , .. , An ]" := (commutator .. (commutator A1 A2) .. An) : group_scope. Prenex Implicits order cycle gcore. Section GroupProp. Variable gT : finGroupType. Notation sT := {set gT}. Implicit Types A B C D : sT. Implicit Types x y z : gT. Implicit Types G H K : {group gT}. Section OneGroup. Variable G : {group gT}. Lemma valG : val G = G. Proof. by []. Qed. (* Non-triviality. *) Lemma group1 : 1 \in G. Proof. by case/group_setP: (valP G). Qed. #[local] Hint Resolve group1 : core. Lemma group1_contra x : x \notin G -> x != 1. Proof. by apply: contraNneq => ->. Qed. Lemma sub1G : [1 gT] \subset G. Proof. by rewrite sub1set. Qed. Lemma subG1 : (G \subset [1]) = (G :==: 1). Proof. by rewrite eqEsubset sub1G andbT. Qed. Lemma setI1g : 1 :&: G = 1. Proof. exact: (setIidPl sub1G). Qed. Lemma setIg1 : G :&: 1 = 1. Proof. exact: (setIidPr sub1G). Qed. Lemma subG1_contra H : G \subset H -> G :!=: 1 -> H :!=: 1. Proof. by move=> sGH; rewrite -subG1; apply: contraNneq => <-. Qed. Lemma repr_group : repr G = 1. Proof. by rewrite /repr group1. Qed. Lemma cardG_gt0 : 0 < #|G|. Proof. by rewrite lt0n; apply/existsP; exists (1 : gT). Qed. Lemma indexg_gt0 A : 0 < #|G : A|. Proof. rewrite lt0n; apply/existsP; exists A. by rewrite -{2}[A]mulg1 -rcosetE; apply: imset_f. Qed. Lemma trivgP : reflect (G :=: 1) (G \subset [1]). Proof. by rewrite subG1; apply: eqP. Qed. Lemma trivGP : reflect (G = 1%G) (G \subset [1]). Proof. by rewrite subG1; apply: eqP. Qed. Lemma proper1G : ([1] \proper G) = (G :!=: 1). Proof. by rewrite properEneq sub1G andbT eq_sym. Qed. Lemma in_one_group x : (x \in 1%G) = (x == 1). Proof. by rewrite -[x \in _]/(x \in [set 1]) !inE. Qed. Definition inE := (in_one_group, inE). Lemma trivgPn : reflect (exists2 x, x \in G & x != 1) (G :!=: 1). Proof. rewrite -subG1. by apply: (iffP subsetPn) => [] [x Gx x1]; exists x; rewrite ?inE in x1 *. Qed. Lemma trivg_card_le1 : (G :==: 1) = (#|G| <= 1). Proof. by rewrite eq_sym eqEcard cards1 sub1G. Qed. Lemma trivg_card1 : (G :==: 1) = (#|G| == 1%N). Proof. by rewrite trivg_card_le1 eqn_leq cardG_gt0 andbT. Qed. Lemma cardG_gt1 : (#|G| > 1) = (G :!=: 1). Proof. by rewrite trivg_card_le1 ltnNge. Qed. Lemma card_le1_trivg : #|G| <= 1 -> G :=: 1. Proof. by rewrite -trivg_card_le1; move/eqP. Qed. Lemma card1_trivg : #|G| = 1%N -> G :=: 1. Proof. by move=> G1; rewrite card_le1_trivg ?G1. Qed. (* Inclusion and product. *) Lemma mulG_subl A : A \subset A * G. Proof. exact: mulg_subl group1. Qed. Lemma mulG_subr A : A \subset ((G : {set gT}) * A ). Proof. exact: mulg_subr group1. Qed. Lemma mulGid : (G : {set gT}) * G = G. Proof. by apply/eqP; rewrite eqEsubset mulG_subr andbT; case/andP: (valP G). Qed. Lemma mulGS A B : (G * A \subset G * B) = (A \subset G * B). Proof. apply/idP/idP; first exact: subset_trans (mulG_subr A). by move/(mulgS G); rewrite mulgA mulGid. Qed. Lemma mulSG A B : (A * G \subset B * G) = (A \subset B * G). Proof. apply/idP/idP; first exact: subset_trans (mulG_subl A). by move/(mulSg G); rewrite -mulgA mulGid. Qed. Lemma mul_subG A B : A \subset G -> B \subset G -> A * B \subset G. Proof. by move=> sAG sBG; rewrite -mulGid mulgSS. Qed. Lemma prod_subG (I : Type) (r : seq I) (P : {pred I}) (F : I -> {set gT}) : (forall i, P i -> F i \subset G) -> \prod_(i <- r | P i) F i \subset G. Proof. move=> subFG; elim/big_rec: _ => [|/= i A /subFG]; first by rewrite sub1set. exact: mul_subG. Qed. (* Membership lemmas *) Lemma groupM x y : x \in G -> y \in G -> x * y \in G. Proof. by case/group_setP: (valP G) x y. Qed. Lemma groupX x n : x \in G -> x ^+ n \in G. Proof. by move=> Gx; elim: n => [|n IHn]; rewrite ?group1 // expgS groupM. Qed. Lemma groupVr x : x \in G -> x^-1 \in G. Proof. move=> Gx; rewrite -(mul1g x^-1) -mem_rcoset ((G :* x =P G) _) //. by rewrite eqEcard card_rcoset leqnn mul_subG ?sub1set. Qed. Lemma groupVl x : x^-1 \in G -> x \in G. Proof. by move/groupVr; rewrite invgK. Qed. Lemma groupV x : (x^-1 \in G) = (x \in G). Proof. by apply/idP/idP; [apply: groupVl | apply: groupVr]. Qed. Lemma groupMl x y : x \in G -> (x * y \in G) = (y \in G). Proof. move=> Gx; apply/idP/idP=> [Gxy|]; last exact: groupM. by rewrite -(mulKg x y) groupM ?groupVr. Qed. Lemma groupMr x y : x \in G -> (y * x \in G) = (y \in G). Proof. by move=> Gx; rewrite -[_ \in G]groupV invMg groupMl groupV. Qed. Definition in_group := (group1, groupV, (groupMl, groupX)). Lemma groupJ x y : x \in G -> y \in G -> x ^ y \in G. Proof. by move=> Gx Gy; rewrite !in_group. Qed. Lemma groupJr x y : y \in G -> (x ^ y \in G) = (x \in G). Proof. by move=> Gy; rewrite groupMl (groupMr, groupV). Qed. Lemma groupR x y : x \in G -> y \in G -> [~ x, y] \in G. Proof. by move=> Gx Gy; rewrite !in_group. Qed. Lemma group_prod I r (P : pred I) F : (forall i, P i -> F i \in G) -> \prod_(i <- r | P i) F i \in G. Proof. by move=> G_P; elim/big_ind: _ => //; apply: groupM. Qed. (* Inverse is an anti-morphism. *) Lemma invGid : G^-1 = G. Proof. by apply/setP=> x; rewrite inE groupV. Qed. Lemma inv_subG A : (A^-1 \subset G) = (A \subset G). Proof. by rewrite -{1}invGid invSg. Qed. Lemma invg_lcoset x : (x *: G)^-1 = G :* x^-1. Proof. by rewrite invMg invGid invg_set1. Qed. Lemma invg_rcoset x : (G :* x)^-1 = x^-1 *: G. Proof. by rewrite invMg invGid invg_set1. Qed. Lemma memV_lcosetV x y : (y^-1 \in x^-1 *: G) = (y \in G :* x). Proof. by rewrite -invg_rcoset memV_invg. Qed. Lemma memV_rcosetV x y : (y^-1 \in G :* x^-1) = (y \in x *: G). Proof. by rewrite -invg_lcoset memV_invg. Qed. (* Product idempotence *) Lemma mulSgGid A x : x \in A -> A \subset G -> A * G = G. Proof. move=> Ax sAG; apply/eqP; rewrite eqEsubset -{2}mulGid mulSg //=. apply/subsetP=> y Gy; rewrite -(mulKVg x y) mem_mulg // groupMr // groupV. exact: (subsetP sAG). Qed. Lemma mulGSgid A x : x \in A -> A \subset G -> G * A = G. Proof. rewrite -memV_invg -invSg invGid => Ax sAG. by apply: invg_inj; rewrite invMg invGid (mulSgGid Ax). Qed. (* Left cosets *) Lemma lcoset_refl x : x \in x *: G. Proof. by rewrite mem_lcoset mulVg group1. Qed. Lemma lcoset_sym x y : (x \in y *: G) = (y \in x *: G). Proof. by rewrite !mem_lcoset -groupV invMg invgK. Qed. Lemma lcoset_eqP {x y} : reflect (x *: G = y *: G) (x \in y *: G). Proof. suffices <-: (x *: G == y *: G) = (x \in y *: G) by apply: eqP. by rewrite eqEsubset !mulSG !sub1set lcoset_sym andbb. Qed. Lemma lcoset_transl x y z : x \in y *: G -> (x \in z *: G) = (y \in z *: G). Proof. by move=> Gyx; rewrite -2!(lcoset_sym z) (lcoset_eqP Gyx). Qed. Lemma lcoset_trans x y z : x \in y *: G -> y \in z *: G -> x \in z *: G. Proof. by move/lcoset_transl->. Qed. Lemma lcoset_id x : x \in G -> x *: G = G. Proof. by move=> Gx; rewrite (lcoset_eqP (_ : x \in 1 *: G)) mul1g. Qed. (* Right cosets, with an elimination form for repr. *) Lemma rcoset_refl x : x \in G :* x. Proof. by rewrite mem_rcoset mulgV group1. Qed. Lemma rcoset_sym x y : (x \in G :* y) = (y \in G :* x). Proof. by rewrite -!memV_lcosetV lcoset_sym. Qed. Lemma rcoset_eqP {x y} : reflect (G :* x = G :* y) (x \in G :* y). Proof. suffices <-: (G :* x == G :* y) = (x \in G :* y) by apply: eqP. by rewrite eqEsubset !mulGS !sub1set rcoset_sym andbb. Qed. Lemma rcoset_transl x y z : x \in G :* y -> (x \in G :* z) = (y \in G :* z). Proof. by move=> Gyx; rewrite -2!(rcoset_sym z) (rcoset_eqP Gyx). Qed. Lemma rcoset_trans x y z : x \in G :* y -> y \in G :* z -> x \in G :* z. Proof. by move/rcoset_transl->. Qed. Lemma rcoset_id x : x \in G -> G :* x = G. Proof. by move=> Gx; rewrite (rcoset_eqP (_ : x \in G :* 1)) mulg1. Qed. (* Elimination form. *) Variant rcoset_repr_spec x : gT -> Type := RcosetReprSpec g : g \in G -> rcoset_repr_spec x (g * x). Lemma mem_repr_rcoset x : repr (G :* x) \in G :* x. Proof. exact: mem_repr (rcoset_refl x). Qed. (* This form sometimes fails because ssreflect 1.1 delegates matching to the *) (* (weaker) primitive Coq algorithm for general (co)inductive type families. *) Lemma repr_rcosetP x : rcoset_repr_spec x (repr (G :* x)). Proof. by rewrite -[repr _](mulgKV x); split; rewrite -mem_rcoset mem_repr_rcoset. Qed. Lemma rcoset_repr x : G :* (repr (G :* x)) = G :* x. Proof. exact/rcoset_eqP/mem_repr_rcoset. Qed. (* Coset spaces. *) Lemma mem_rcosets A x : (G :* x \in rcosets G A) = (x \in G * A). Proof. apply/rcosetsP/mulsgP=> [[a Aa /rcoset_eqP/rcosetP[g]] | ]; first by exists g a. by case=> g a Gg Aa ->{x}; exists a; rewrite // rcosetM rcoset_id. Qed. Lemma mem_lcosets A x : (x *: G \in lcosets G A) = (x \in A * G). Proof. rewrite -[LHS]memV_invg invg_lcoset invg_lcosets. by rewrite -[RHS]memV_invg invMg invGid mem_rcosets. Qed. (* Conjugates. *) Lemma group_setJ A x : group_set (A :^ x) = group_set A. Proof. by rewrite /group_set mem_conjg conj1g -conjsMg conjSg. Qed. Lemma group_set_conjG x : group_set (G :^ x). Proof. by rewrite group_setJ groupP. Qed. Canonical conjG_group x := group (group_set_conjG x). Lemma conjGid : {in G, normalised G}. Proof. by move=> x Gx; apply/setP=> y; rewrite mem_conjg groupJr ?groupV. Qed. Lemma conj_subG x A : x \in G -> A \subset G -> A :^ x \subset G. Proof. by move=> Gx sAG; rewrite -(conjGid Gx) conjSg. Qed. (* Classes *) Lemma class1G : 1 ^: G = 1. Proof. exact: class1g group1. Qed. Lemma classes1 : [1] \in classes G. Proof. by rewrite -class1G mem_classes. Qed. Lemma classGidl x y : y \in G -> (x ^ y) ^: G = x ^: G. Proof. by move=> Gy; rewrite -class_lcoset lcoset_id. Qed. Lemma classGidr x : {in G, normalised (x ^: G)}. Proof. by move=> y Gy /=; rewrite -class_rcoset rcoset_id. Qed. Lemma class_refl x : x \in x ^: G. Proof. by apply/imsetP; exists 1; rewrite ?conjg1. Qed. #[local] Hint Resolve class_refl : core. Lemma class_eqP x y : reflect (x ^: G = y ^: G) (x \in y ^: G). Proof. by apply: (iffP idP) => [/imsetP[z Gz ->] | <-]; rewrite ?class_refl ?classGidl. Qed. Lemma class_sym x y : (x \in y ^: G) = (y \in x ^: G). Proof. by apply/idP/idP=> /class_eqP->. Qed. Lemma class_transl x y z : x \in y ^: G -> (x \in z ^: G) = (y \in z ^: G). Proof. by rewrite -!(class_sym z) => /class_eqP->. Qed. Lemma class_trans x y z : x \in y ^: G -> y \in z ^: G -> x \in z ^: G. Proof. by move/class_transl->. Qed. Lemma repr_class x : {y | y \in G & repr (x ^: G) = x ^ y}. Proof. set z := repr _; have: #|[set y in G | z == x ^ y]| > 0. have: z \in x ^: G by apply: (mem_repr x). by case/imsetP=> y Gy ->; rewrite (cardD1 y) inE Gy eqxx. by move/card_mem_repr; move: (repr _) => y /setIdP[Gy /eqP]; exists y. Qed. Lemma classG_eq1 x : (x ^: G == 1) = (x == 1). Proof. apply/eqP/eqP=> [xG1 | ->]; last exact: class1G. by have:= class_refl x; rewrite xG1 => /set1P. Qed. Lemma class_subG x A : x \in G -> A \subset G -> x ^: A \subset G. Proof. move=> Gx sAG; apply/subsetP=> _ /imsetP[y Ay ->]. by rewrite groupJ // (subsetP sAG). Qed. Lemma repr_classesP xG : reflect (repr xG \in G /\ xG = repr xG ^: G) (xG \in classes G). Proof. apply: (iffP imsetP) => [[x Gx ->] | []]; last by exists (repr xG). by have [y Gy ->] := repr_class x; rewrite classGidl ?groupJ. Qed. Lemma mem_repr_classes xG : xG \in classes G -> repr xG \in xG. Proof. by case/repr_classesP=> _ {2}->; apply: class_refl. Qed. Lemma classes_gt0 : 0 < #|classes G|. Proof. by rewrite (cardsD1 1) classes1. Qed. Lemma classes_gt1 : (#|classes G| > 1) = (G :!=: 1). Proof. rewrite (cardsD1 1) classes1 ltnS lt0n cards_eq0. apply/set0Pn/trivgPn=> [[xG /setD1P[nt_xG]] | [x Gx ntx]]. by case/imsetP=> x Gx def_xG; rewrite def_xG classG_eq1 in nt_xG; exists x. by exists (x ^: G); rewrite !inE classG_eq1 ntx; apply: imset_f. Qed. Lemma mem_class_support A x : x \in A -> x \in class_support A G. Proof. by move=> Ax; rewrite -[x]conjg1 memJ_class_support. Qed. Lemma class_supportGidl A x : x \in G -> class_support (A :^ x) G = class_support A G. Proof. by move=> Gx; rewrite -class_support_set1r -class_supportM lcoset_id. Qed. Lemma class_supportGidr A : {in G, normalised (class_support A G)}. Proof. by move=> x Gx /=; rewrite -class_support_set1r -class_supportM rcoset_id. Qed. Lemma class_support_subG A : A \subset G -> class_support A G \subset G. Proof. by move=> sAG; rewrite class_supportEr; apply/bigcupsP=> x Gx; apply: conj_subG. Qed. Lemma sub_class_support A : A \subset class_support A G. Proof. by rewrite class_supportEr (bigcup_max 1) ?conjsg1. Qed. Lemma class_support_id : class_support G G = G. Proof. by apply/eqP; rewrite eqEsubset sub_class_support class_support_subG. Qed. Lemma class_supportD1 A : (class_support A G)^# = cover (A^# :^: G). Proof. rewrite cover_imset class_supportEr setDE big_distrl /=. by apply: eq_bigr => x _; rewrite -setDE conjD1g. Qed. (* Subgroup Type construction. *) (* We only expect to use this for abstract groups, so we don't project *) (* the argument to a set. *) Inductive subg_of : predArgType := Subg x & x \in G. Definition sgval u := let: Subg x _ := u in x. Definition subg_of_Sub := Eval hnf in [isSub for sgval]. HB.instance Definition _ := subg_of_Sub. #[hnf] HB.instance Definition _ := [Finite of subg_of by <:]. Lemma subgP u : sgval u \in G. Proof. exact: valP. Qed. Lemma subg_inj : injective sgval. Proof. exact: val_inj. Qed. Lemma congr_subg u v : u = v -> sgval u = sgval v. Proof. exact: congr1. Qed. Definition subg_one := Subg group1. Definition subg_inv u := Subg (groupVr (subgP u)). Definition subg_mul u v := Subg (groupM (subgP u) (subgP v)). Lemma subg_oneP : left_id subg_one subg_mul. Proof. by move=> u; apply: val_inj; apply: mul1g. Qed. Lemma subg_invP : left_inverse subg_one subg_inv subg_mul. Proof. by move=> u; apply: val_inj; apply: mulVg. Qed. Lemma subg_mulP : associative subg_mul. Proof. by move=> u v w; apply: val_inj; apply: mulgA. Qed. HB.instance Definition _ := isMulGroup.Build subg_of subg_mulP subg_oneP subg_invP. Lemma sgvalM : {in setT &, {morph sgval : x y / x * y}}. Proof. by []. Qed. Lemma valgM : {in setT &, {morph val : x y / (x : subg_of) * y >-> x * y}}. Proof. by []. Qed. Definition subg : gT -> subg_of := insubd (1 : subg_of). Lemma subgK x : x \in G -> val (subg x) = x. Proof. by move=> Gx; rewrite insubdK. Qed. Lemma sgvalK : cancel sgval subg. Proof. by case=> x Gx; apply: val_inj; apply: subgK. Qed. Lemma subg_default x : (x \in G) = false -> val (subg x) = 1. Proof. by move=> Gx; rewrite val_insubd Gx. Qed. Lemma subgM : {in G &, {morph subg : x y / x * y}}. Proof. by move=> x y Gx Gy; apply: val_inj; rewrite /= !subgK ?groupM. Qed. End OneGroup. #[local] Hint Resolve group1 : core. Lemma groupD1_inj G H : G^# = H^# -> G :=: H. Proof. by move/(congr1 (setU 1)); rewrite !setD1K. Qed. Lemma invMG G H : (G * H)^-1 = H * G. Proof. by rewrite invMg !invGid. Qed. Lemma mulSGid G H : H \subset G -> H * G = G. Proof. exact: mulSgGid (group1 H). Qed. Lemma mulGSid G H : H \subset G -> G * H = G. Proof. exact: mulGSgid (group1 H). Qed. Lemma mulGidPl G H : reflect (G * H = G) (H \subset G). Proof. by apply: (iffP idP) => [|<-]; [apply: mulGSid | apply: mulG_subr]. Qed. Lemma mulGidPr G H : reflect (G * H = H) (G \subset H). Proof. by apply: (iffP idP) => [|<-]; [apply: mulSGid | apply: mulG_subl]. Qed. Lemma comm_group_setP G H : reflect (commute G H) (group_set (G * H)). Proof. rewrite /group_set (subsetP (mulG_subl _ _)) ?group1 // andbC. have <-: #|G * H| <= #|H * G| by rewrite -invMG card_invg. by rewrite -mulgA mulGS mulgA mulSG -eqEcard eq_sym; apply: eqP. Qed. Lemma card_lcosets G H : #|lcosets H G| = #|G : H|. Proof. by rewrite -card_invg invg_lcosets !invGid. Qed. (* Group Modularity equations *) Lemma group_modl A B G : A \subset G -> A * (B :&: G) = A * B :&: G. Proof. move=> sAG; apply/eqP; rewrite eqEsubset subsetI mulgS ?subsetIl //. rewrite -{2}mulGid mulgSS ?subsetIr //. apply/subsetP => _ /setIP[/mulsgP[a b Aa Bb ->] Gab]. by rewrite mem_mulg // inE Bb -(groupMl _ (subsetP sAG _ Aa)). Qed. Lemma group_modr A B G : B \subset G -> (G :&: A) * B = G :&: A * B. Proof. move=> sBG; apply: invg_inj; rewrite !(invMg, invIg) invGid !(setIC G). by rewrite group_modl // -invGid invSg. Qed. End GroupProp. #[global] Hint Extern 0 (is_true (1%g \in _)) => apply: group1 : core. #[global] Hint Extern 0 (is_true (0 < #|_|)) => apply: cardG_gt0 : core. #[global] Hint Extern 0 (is_true (0 < #|_ : _|)) => apply: indexg_gt0 : core. Notation "G :^ x" := (conjG_group G x) : Group_scope. Notation "[ 'subg' G ]" := (subg_of G) : type_scope. Notation "[ 'subg' G ]" := [set: subg_of G] : group_scope. Notation "[ 'subg' G ]" := [set: subg_of G]%G : Group_scope. Prenex Implicits subg sgval subg_of. Bind Scope group_scope with subg_of. Arguments subgK {gT G}. Arguments sgvalK {gT G}. Arguments subg_inj {gT G} [u1 u2] eq_u12 : rename. Arguments trivgP {gT G}. Arguments trivGP {gT G}. Arguments lcoset_eqP {gT G x y}. Arguments rcoset_eqP {gT G x y}. Arguments mulGidPl {gT G H}. Arguments mulGidPr {gT G H}. Arguments comm_group_setP {gT G H}. Arguments class_eqP {gT G x y}. Arguments repr_classesP {gT G xG}. Section GroupInter. Variable gT : finGroupType. Implicit Types A B : {set gT}. Implicit Types G H : {group gT}. Lemma group_setI G H : group_set (G :&: H). Proof. apply/group_setP; split=> [|x y]; rewrite !inE ?group1 //. by case/andP=> Gx Hx; rewrite !groupMl. Qed. Canonical setI_group G H := group (group_setI G H). Section Nary. Variables (I : finType) (P : pred I) (F : I -> {group gT}). Lemma group_set_bigcap : group_set (\bigcap_(i | P i) F i). Proof. by elim/big_rec: _ => [|i G _ gG]; rewrite -1?(insubdK 1%G gG) groupP. Qed. Canonical bigcap_group := group group_set_bigcap. End Nary. Lemma group_set_generated (A : {set gT}) : group_set <<A>>. Proof. by rewrite unlock group_set_bigcap. Qed. Canonical generated_group A := group (group_set_generated A). Canonical gcore_group G A : {group _} := Eval hnf in [group of gcore G A]. Canonical commutator_group A B : {group _} := Eval hnf in [group of [~: A, B]]. Canonical joing_group A B : {group _} := Eval hnf in [group of A <*> B]. Canonical cycle_group x : {group _} := Eval hnf in [group of <[x]>]. Definition joinG G H := joing_group G H. Definition subgroups A := [set G : {group gT} | G \subset A]. Lemma order_gt0 (x : gT) : 0 < #[x]. Proof. exact: cardG_gt0. Qed. End GroupInter. #[global] Hint Resolve order_gt0 : core. Arguments generated_group _ _%_g. Arguments joing_group _ _%_g _%_g. Arguments subgroups _ _%_g. Notation "G :&: H" := (setI_group G H) : Group_scope. Notation "<< A >>" := (generated_group A) : Group_scope. Notation "<[ x ] >" := (cycle_group x) : Group_scope. Notation "[ ~: A1 , A2 , .. , An ]" := (commutator_group .. (commutator_group A1 A2) .. An) : Group_scope. Notation "A <*> B" := (joing_group A B) : Group_scope. Notation "G * H" := (joinG G H) : Group_scope. Prenex Implicits joinG subgroups. Notation "\prod_ ( i <- r | P ) F" := (\big[joinG/1%G]_(i <- r | P%B) F%G) : Group_scope. Notation "\prod_ ( i <- r ) F" := (\big[joinG/1%G]_(i <- r) F%G) : Group_scope. Notation "\prod_ ( m <= i < n | P ) F" := (\big[joinG/1%G]_(m <= i < n | P%B) F%G) : Group_scope. Notation "\prod_ ( m <= i < n ) F" := (\big[joinG/1%G]_(m <= i < n) F%G) : Group_scope. Notation "\prod_ ( i | P ) F" := (\big[joinG/1%G]_(i | P%B) F%G) : Group_scope. Notation "\prod_ i F" := (\big[joinG/1%G]_i F%G) : Group_scope. Notation "\prod_ ( i : t | P ) F" := (\big[joinG/1%G]_(i : t | P%B) F%G) (only parsing) : Group_scope. Notation "\prod_ ( i : t ) F" := (\big[joinG/1%G]_(i : t) F%G) (only parsing) : Group_scope. Notation "\prod_ ( i < n | P ) F" := (\big[joinG/1%G]_(i < n | P%B) F%G) : Group_scope. Notation "\prod_ ( i < n ) F" := (\big[joinG/1%G]_(i < n) F%G) : Group_scope. Notation "\prod_ ( i 'in' A | P ) F" := (\big[joinG/1%G]_(i in A | P%B) F%G) : Group_scope. Notation "\prod_ ( i 'in' A ) F" := (\big[joinG/1%G]_(i in A) F%G) : Group_scope. Section Lagrange. Variable gT : finGroupType. Implicit Types G H K : {group gT}. Lemma LagrangeI G H : (#|G :&: H| * #|G : H|)%N = #|G|. Proof. rewrite -[#|G|]sum1_card (partition_big_imset (rcoset H)) /=. rewrite mulnC -sum_nat_const; apply: eq_bigr => _ /rcosetsP[x Gx ->]. rewrite -(card_rcoset _ x) -sum1_card; apply: eq_bigl => y. by rewrite rcosetE (sameP eqP rcoset_eqP) group_modr ?sub1set // !inE. Qed. Lemma divgI G H : #|G| %/ #|G :&: H| = #|G : H|. Proof. by rewrite -(LagrangeI G H) mulKn ?cardG_gt0. Qed. Lemma divg_index G H : #|G| %/ #|G : H| = #|G :&: H|. Proof. by rewrite -(LagrangeI G H) mulnK. Qed. Lemma dvdn_indexg G H : #|G : H| %| #|G|. Proof. by rewrite -(LagrangeI G H) dvdn_mull. Qed. Theorem Lagrange G H : H \subset G -> (#|H| * #|G : H|)%N = #|G|. Proof. by move/setIidPr=> sHG; rewrite -{1}sHG LagrangeI. Qed. Lemma cardSg G H : H \subset G -> #|H| %| #|G|. Proof. by move/Lagrange <-; rewrite dvdn_mulr. Qed. Lemma lognSg p G H : G \subset H -> logn p #|G| <= logn p #|H|. Proof. by move=> sGH; rewrite dvdn_leq_log ?cardSg. Qed. Lemma piSg G H : G \subset H -> {subset \pi(gval G) <= \pi(gval H)}. Proof. move=> sGH p; rewrite !mem_primes !cardG_gt0 => /and3P[-> _ pG]. exact: dvdn_trans (cardSg sGH). Qed. Lemma divgS G H : H \subset G -> #|G| %/ #|H| = #|G : H|. Proof. by move/Lagrange <-; rewrite mulKn. Qed. Lemma divg_indexS G H : H \subset G -> #|G| %/ #|G : H| = #|H|. Proof. by move/Lagrange <-; rewrite mulnK. Qed. Lemma coprimeSg G H p : H \subset G -> coprime #|G| p -> coprime #|H| p. Proof. by move=> sHG; apply: coprime_dvdl (cardSg sHG). Qed. Lemma coprimegS G H p : H \subset G -> coprime p #|G| -> coprime p #|H|. Proof. by move=> sHG; apply: coprime_dvdr (cardSg sHG). Qed. Lemma indexJg G H x : #|G :^ x : H :^ x| = #|G : H|. Proof. by rewrite -!divgI -conjIg !cardJg. Qed. Lemma indexgg G : #|G : G| = 1%N. Proof. by rewrite -divgS // divnn cardG_gt0. Qed. Lemma rcosets_id G : rcosets G G = [set G : {set gT}]. Proof. apply/esym/eqP; rewrite eqEcard sub1set [#|_|]indexgg cards1 andbT. by apply/rcosetsP; exists 1; rewrite ?mulg1. Qed. Lemma Lagrange_index G H K : H \subset G -> K \subset H -> (#|G : H| * #|H : K|)%N = #|G : K|. Proof. move=> sHG sKH; apply/eqP; rewrite mulnC -(eqn_pmul2l (cardG_gt0 K)). by rewrite mulnA !Lagrange // (subset_trans sKH). Qed. Lemma indexgI G H : #|G : G :&: H| = #|G : H|. Proof. by rewrite -[RHS]divgI divgS ?subsetIl. Qed. Lemma indexgS G H K : H \subset K -> #|G : K| %| #|G : H|. Proof. move=> sHK; rewrite -(@dvdn_pmul2l #|G :&: K|) ?cardG_gt0 // LagrangeI. by rewrite -(Lagrange (setIS G sHK)) mulnAC LagrangeI dvdn_mulr. Qed. Lemma indexSg G H K : H \subset K -> K \subset G -> #|K : H| %| #|G : H|. Proof. move=> sHK sKG; rewrite -(@dvdn_pmul2l #|H|) ?cardG_gt0 //. by rewrite !Lagrange ?(cardSg, subset_trans sHK). Qed. Lemma indexg_eq1 G H : (#|G : H| == 1%N) = (G \subset H). Proof. rewrite eqn_leq -(leq_pmul2l (cardG_gt0 (G :&: H))) LagrangeI muln1. by rewrite indexg_gt0 andbT (sameP setIidPl eqP) eqEcard subsetIl. Qed. Lemma indexg_gt1 G H : (#|G : H| > 1) = ~~ (G \subset H). Proof. by rewrite -indexg_eq1 eqn_leq indexg_gt0 andbT -ltnNge. Qed. Lemma index1g G H : H \subset G -> #|G : H| = 1%N -> H :=: G. Proof. by move=> sHG iHG; apply/eqP; rewrite eqEsubset sHG -indexg_eq1 iHG. Qed. Lemma indexg1 G : #|G : 1| = #|G|. Proof. by rewrite -divgS ?sub1G // cards1 divn1. Qed. Lemma indexMg G A : #|G * A : G| = #|A : G|. Proof. apply/eq_card/setP/eqP; rewrite eqEsubset andbC imsetS ?mulG_subr //. by apply/subsetP=> _ /rcosetsP[x GAx ->]; rewrite mem_rcosets. Qed. Lemma rcosets_partition_mul G H : partition (rcosets H G) (H * G). Proof. set HG := H * G; have sGHG: {subset G <= HG} by apply/subsetP/mulG_subr. have defHx x: x \in HG -> [set y in HG | rcoset H x == rcoset H y] = H :* x. move=> HGx; apply/setP=> y; rewrite inE !rcosetE (sameP eqP rcoset_eqP). by rewrite rcoset_sym; apply/andb_idl/subsetP; rewrite mulGS sub1set. have:= preim_partitionP (rcoset H) HG; congr (partition _ _); apply/setP=> Hx. apply/imsetP/idP=> [[x HGx ->] | ]; first by rewrite defHx // mem_rcosets. by case/rcosetsP=> x /sGHG-HGx ->; exists x; rewrite ?defHx. Qed. Lemma rcosets_partition G H : H \subset G -> partition (rcosets H G) G. Proof. by move=> sHG; have:= rcosets_partition_mul G H; rewrite mulSGid. Qed. Lemma LagrangeMl G H : (#|G| * #|H : G|)%N = #|G * H|. Proof. rewrite mulnC -(card_uniform_partition _ (rcosets_partition_mul H G)) //. by move=> _ /rcosetsP[x Hx ->]; rewrite card_rcoset. Qed. Lemma LagrangeMr G H : (#|G : H| * #|H|)%N = #|G * H|. Proof. by rewrite mulnC LagrangeMl -card_invg invMg !invGid. Qed. Lemma mul_cardG G H : (#|G| * #|H| = #|G * H|%g * #|G :&: H|)%N. Proof. by rewrite -LagrangeMr -(LagrangeI G H) -mulnA mulnC. Qed. Lemma dvdn_cardMg G H : #|G * H| %| #|G| * #|H|. Proof. by rewrite mul_cardG dvdn_mulr. Qed. Lemma cardMg_divn G H : #|G * H| = (#|G| * #|H|) %/ #|G :&: H|. Proof. by rewrite mul_cardG mulnK ?cardG_gt0. Qed. Lemma cardIg_divn G H : #|G :&: H| = (#|G| * #|H|) %/ #|G * H|. Proof. by rewrite mul_cardG mulKn // (cardD1 (1 * 1)) mem_mulg. Qed. Lemma TI_cardMg G H : G :&: H = 1 -> #|G * H| = (#|G| * #|H|)%N. Proof. by move=> tiGH; rewrite mul_cardG tiGH cards1 muln1. Qed. Lemma cardMg_TI G H : #|G| * #|H| <= #|G * H| -> G :&: H = 1. Proof. move=> leGH; apply: card_le1_trivg. rewrite -(@leq_pmul2l #|G * H|); first by rewrite -mul_cardG muln1. by apply: leq_trans leGH; rewrite muln_gt0 !cardG_gt0. Qed. Lemma coprime_TIg G H : coprime #|G| #|H| -> G :&: H = 1. Proof. move=> coGH; apply/eqP; rewrite trivg_card1 -dvdn1 -{}(eqnP coGH). by rewrite dvdn_gcd /= {2}setIC !cardSg ?subsetIl. Qed. Lemma prime_TIg G H : prime #|G| -> ~~ (G \subset H) -> G :&: H = 1. Proof. case/primeP=> _ /(_ _ (cardSg (subsetIl G H))). rewrite (sameP setIidPl eqP) eqEcard subsetIl => /pred2P[/card1_trivg|] //= ->. by case/negP. Qed. Lemma prime_meetG G H : prime #|G| -> G :&: H != 1 -> G \subset H. Proof. by move=> prG; apply: contraR; move/prime_TIg->. Qed. Lemma coprime_cardMg G H : coprime #|G| #|H| -> #|G * H| = (#|G| * #|H|)%N. Proof. by move=> coGH; rewrite TI_cardMg ?coprime_TIg. Qed. Lemma coprime_index_mulG G H K : H \subset G -> K \subset G -> coprime #|G : H| #|G : K| -> H * K = G. Proof. move=> sHG sKG co_iG_HK; apply/eqP; rewrite eqEcard mul_subG //=. rewrite -(@leq_pmul2r #|H :&: K|) ?cardG_gt0 // -mul_cardG. rewrite -(Lagrange sHG) -(LagrangeI K H) mulnAC setIC -mulnA. rewrite !leq_pmul2l ?cardG_gt0 // dvdn_leq // -(Gauss_dvdr _ co_iG_HK). by rewrite -(indexgI K) Lagrange_index ?indexgS ?subsetIl ?subsetIr. Qed. End Lagrange. Section GeneratedGroup. Variable gT : finGroupType. Implicit Types x y z : gT. Implicit Types A B C D : {set gT}. Implicit Types G H K : {group gT}. Lemma subset_gen A : A \subset <<A>>. Proof. rewrite [@generated]unlock; exact/bigcapsP. Qed. Lemma sub_gen A B : A \subset B -> A \subset <<B>>. Proof. by move/subset_trans=> -> //; apply: subset_gen. Qed. Lemma mem_gen x A : x \in A -> x \in <<A>>. Proof. exact: subsetP (subset_gen A) x. Qed. Lemma generatedP x A : reflect (forall G, A \subset G -> x \in G) (x \in <<A>>). Proof. rewrite [@generated]unlock; exact: bigcapP. Qed. Lemma gen_subG A G : (<<A>> \subset G) = (A \subset G). Proof. apply/idP/idP=> [|sAG]; first exact: subset_trans (subset_gen A). by apply/subsetP=> x /generatedP; apply. Qed. Lemma genGid G : <<G>> = G. Proof. by apply/eqP; rewrite eqEsubset gen_subG subset_gen andbT. Qed. Lemma genGidG G : <<G>>%G = G. Proof. by apply: val_inj; apply: genGid. Qed. Lemma gen_set_id A : group_set A -> <<A>> = A. Proof. by move=> gA; apply: (genGid (group gA)). Qed. Lemma genS A B : A \subset B -> <<A>> \subset <<B>>. Proof. by move=> sAB; rewrite gen_subG sub_gen. Qed. Lemma gen0 : <<set0>> = 1 :> {set gT}. Proof. by apply/eqP; rewrite eqEsubset sub1G gen_subG sub0set. Qed. Lemma gen_expgs A : {n | <<A>> = (1 |: A) ^+ n}. Proof. set B := (1 |: A); pose N := #|gT|. have BsubG n : B ^+ n \subset <<A>>. by elim: n => [|n IHn]; rewrite ?expgS ?mul_subG ?subUset ?sub1G ?subset_gen. have B_1 n : 1 \in B ^+ n. by elim: n => [|n IHn]; rewrite ?set11 // expgS mulUg mul1g inE IHn. case: (pickP (fun i : 'I_N => B ^+ i.+1 \subset B ^+ i)) => [n fixBn | no_fix]. exists n; apply/eqP; rewrite eqEsubset BsubG andbT. rewrite -[B ^+ n]gen_set_id ?genS ?subsetUr //. by apply: subset_trans fixBn; rewrite expgS mulUg subsetU ?mulg_subl ?orbT. rewrite /group_set B_1 /=. elim: {2}(n : nat) => [|m IHm]; first by rewrite mulg1. by apply: subset_trans fixBn; rewrite !expgSr mulgA mulSg. suffices: N < #|B ^+ N| by rewrite ltnNge max_card. have [] := ubnPgeq N; elim=> [|n IHn] lt_nN; first by rewrite cards1. apply: leq_ltn_trans (IHn (ltnW lt_nN)) (proper_card _). by rewrite /proper (no_fix (Ordinal lt_nN)) expgS mulUg mul1g subsetUl. Qed. Lemma gen_prodgP A x : reflect (exists n, exists2 c, forall i : 'I_n, c i \in A & x = \prod_i c i) (x \in <<A>>). Proof. apply: (iffP idP) => [|[n [c Ac ->]]]; last first. by apply: group_prod => i _; rewrite mem_gen ?Ac. have [n ->] := gen_expgs A; rewrite /expgn Monoid.iteropE /=. rewrite -[n]card_ord -big_const => /prodsgP[/= c Ac def_x]. have{Ac def_x} ->: x = \prod_(i | c i \in A) c i. rewrite big_mkcond {x}def_x; apply: eq_bigr => i _. by case/setU1P: (Ac i isT) => -> //; rewrite if_same. have [e <- [_ /= mem_e] _] := big_enumP [preim c of A]. pose t := in_tuple e; rewrite -[e]/(val t) big_tuple. by exists (size e), (c \o tnth t) => // i; rewrite -mem_e mem_tnth. Qed. Lemma genD A B : A \subset <<A :\: B>> -> <<A :\: B>> = <<A>>. Proof. by move=> sAB; apply/eqP; rewrite eqEsubset genS (subsetDl, gen_subG). Qed. Lemma genV A : <<A^-1>> = <<A>>. Proof. apply/eqP; rewrite eqEsubset !gen_subG -!(invSg _ <<_>>) invgK. by rewrite !invGid !subset_gen. Qed. Lemma genJ A z : <<A :^z>> = <<A>> :^ z. Proof. by apply/eqP; rewrite eqEsubset sub_conjg !gen_subG conjSg -?sub_conjg !sub_gen. Qed. Lemma conjYg A B z : (A <*> B) :^z = A :^ z <*> B :^ z. Proof. by rewrite -genJ conjUg. Qed. Lemma genD1 A x : x \in <<A :\ x>> -> <<A :\ x>> = <<A>>. Proof. move=> gA'x; apply/eqP; rewrite eqEsubset genS; last by rewrite subsetDl. rewrite gen_subG; apply/subsetP=> y Ay. by case: (y =P x) => [-> //|]; move/eqP=> nyx; rewrite mem_gen // !inE nyx. Qed. Lemma genD1id A : <<A^#>> = <<A>>. Proof. by rewrite genD1 ?group1. Qed. Notation joingT := (@joing gT) (only parsing). Notation joinGT := (@joinG gT) (only parsing). Lemma joingE A B : A <*> B = <<A :|: B>>. Proof. by []. Qed. Lemma joinGE G H : (G * H)%G = (G <*> H)%G. Proof. by []. Qed. Lemma joingC : commutative joingT. Proof. by move=> A B; rewrite /joing setUC. Qed. Lemma joing_idr A B : A <*> <<B>> = A <*> B. Proof. apply/eqP; rewrite eqEsubset gen_subG subUset gen_subG /=. by rewrite -subUset subset_gen genS // setUS // subset_gen. Qed. Lemma joing_idl A B : <<A>> <*> B = A <*> B. Proof. by rewrite -!(joingC B) joing_idr. Qed. Lemma joing_subl A B : A \subset A <*> B. Proof. by rewrite sub_gen ?subsetUl. Qed. Lemma joing_subr A B : B \subset A <*> B. Proof. by rewrite sub_gen ?subsetUr. Qed. Lemma join_subG A B G : (A <*> B \subset G) = (A \subset G) && (B \subset G). Proof. by rewrite gen_subG subUset. Qed. Lemma joing_idPl G A : reflect (G <*> A = G) (A \subset G). Proof. apply: (iffP idP) => [sHG | <-]; last by rewrite joing_subr. by rewrite joingE (setUidPl sHG) genGid. Qed. Lemma joing_idPr A G : reflect (A <*> G = G) (A \subset G). Proof. by rewrite joingC; apply: joing_idPl. Qed. Lemma joing_subP A B G : reflect (A \subset G /\ B \subset G) (A <*> B \subset G). Proof. by rewrite join_subG; apply: andP. Qed. Lemma joing_sub A B C : A <*> B = C -> A \subset C /\ B \subset C. Proof. by move <-; apply/joing_subP. Qed. Lemma genDU A B C : A \subset C -> <<C :\: A>> = <<B>> -> <<A :|: B>> = <<C>>. Proof. move=> sAC; rewrite -joingE -joing_idr => <- {B}; rewrite joing_idr. by congr <<_>>; rewrite setDE setUIr setUCr setIT; apply/setUidPr. Qed. Lemma joingA : associative joingT. Proof. by move=> A B C; rewrite joing_idl joing_idr /joing setUA. Qed. Lemma joing1G G : 1 <*> G = G. Proof. by rewrite -gen0 joing_idl /joing set0U genGid. Qed. Lemma joingG1 G : G <*> 1 = G. Proof. by rewrite joingC joing1G. Qed. Lemma genM_join G H : <<G * H>> = G <*> H. Proof. apply/eqP; rewrite eqEsubset gen_subG /= -{1}[G <*> H]mulGid. rewrite genS; last by rewrite subUset mulG_subl mulG_subr. by rewrite mulgSS ?(sub_gen, subsetUl, subsetUr). Qed. Lemma mulG_subG G H K : (G * H \subset K) = (G \subset K) && (H \subset K). Proof. by rewrite -gen_subG genM_join join_subG. Qed. Lemma mulGsubP K H G : reflect (K \subset G /\ H \subset G) (K * H \subset G). Proof. by rewrite mulG_subG; apply: andP. Qed. Lemma mulG_sub K H A : K * H = A -> K \subset A /\ H \subset A. Proof. by move <-; rewrite mulG_subl mulG_subr. Qed. Lemma trivMg G H : (G * H == 1) = (G :==: 1) && (H :==: 1). Proof. by rewrite !eqEsubset -{2}[1]mulGid mulgSS ?sub1G // !andbT mulG_subG. Qed. Lemma comm_joingE G H : commute G H -> G <*> H = G * H. Proof. by move/comm_group_setP=> gGH; rewrite -genM_join; apply: (genGid (group gGH)). Qed. Lemma joinGC : commutative joinGT. Proof. by move=> G H; apply: val_inj; apply: joingC. Qed. Lemma joinGA : associative joinGT. Proof. by move=> G H K; apply: val_inj; apply: joingA. Qed. Lemma join1G : left_id 1%G joinGT. Proof. by move=> G; apply: val_inj; apply: joing1G. Qed. Lemma joinG1 : right_id 1%G joinGT. Proof. by move=> G; apply: val_inj; apply: joingG1. Qed. HB.instance Definition _ := Monoid.isComLaw.Build {group gT} 1%G joinGT joinGA joinGC join1G. Lemma bigprodGEgen I r (P : pred I) (F : I -> {set gT}) : (\prod_(i <- r | P i) <<F i>>)%G :=: << \bigcup_(i <- r | P i) F i >>. Proof. elim/big_rec2: _ => /= [|i A _ _ ->]; first by rewrite gen0. by rewrite joing_idl joing_idr. Qed. Lemma bigprodGE I r (P : pred I) (F : I -> {group gT}) : (\prod_(i <- r | P i) F i)%G :=: << \bigcup_(i <- r | P i) F i >>. Proof. rewrite -bigprodGEgen /=; apply: congr_group. by apply: eq_bigr => i _; rewrite genGidG. Qed. Lemma mem_commg A B x y : x \in A -> y \in B -> [~ x, y] \in [~: A, B]. Proof. by move=> Ax By; rewrite mem_gen ?imset2_f. Qed. Lemma commSg A B C : A \subset B -> [~: A, C] \subset [~: B, C]. Proof. by move=> sAC; rewrite genS ?imset2S. Qed. Lemma commgS A B C : B \subset C -> [~: A, B] \subset [~: A, C]. Proof. by move=> sBC; rewrite genS ?imset2S. Qed. Lemma commgSS A B C D : A \subset B -> C \subset D -> [~: A, C] \subset [~: B, D]. Proof. by move=> sAB sCD; rewrite genS ?imset2S. Qed. Lemma der1_subG G : [~: G, G] \subset G. Proof. by rewrite gen_subG; apply/subsetP=> _ /imset2P[x y Gx Gy ->]; apply: groupR. Qed. Lemma comm_subG A B G : A \subset G -> B \subset G -> [~: A, B] \subset G. Proof. by move=> sAG sBG; apply: subset_trans (der1_subG G); apply: commgSS. Qed. Lemma commGC A B : [~: A, B] = [~: B, A]. Proof. rewrite -[[~: A, B]]genV; congr <<_>>; apply/setP=> z; rewrite inE. by apply/imset2P/imset2P=> [] [x y Ax Ay]; last rewrite -{1}(invgK z); rewrite -invg_comm => /invg_inj->; exists y x. Qed. Lemma conjsRg A B x : [~: A, B] :^ x = [~: A :^ x, B :^ x]. Proof. wlog suffices: A B x / [~: A, B] :^ x \subset [~: A :^ x, B :^ x]. move=> subJ; apply/eqP; rewrite eqEsubset subJ /= -sub_conjgV. by rewrite -{2}(conjsgK x A) -{2}(conjsgK x B). rewrite -genJ gen_subG; apply/subsetP=> _ /imsetP[_ /imset2P[y z Ay Bz ->] ->]. by rewrite conjRg mem_commg ?memJ_conjg. Qed. End GeneratedGroup. Arguments gen_prodgP {gT A x}. Arguments joing_idPl {gT G A}. Arguments joing_idPr {gT A G}. Arguments mulGsubP {gT K H G}. Arguments joing_subP {gT A B G}. Section Cycles. (* Elementary properties of cycles and order, needed in perm.v. *) (* More advanced results on the structure of cyclic groups will *) (* be given in cyclic.v. *) Variable gT : finGroupType. Implicit Types x y : gT. Implicit Types G : {group gT}. Import Monoid.Theory. Lemma cycle1 : <[1]> = [1 gT]. Proof. exact: genGid. Qed. Lemma order1 : #[1 : gT] = 1%N. Proof. by rewrite /order cycle1 cards1. Qed. Lemma cycle_id x : x \in <[x]>. Proof. by rewrite mem_gen // set11. Qed. Lemma mem_cycle x i : x ^+ i \in <[x]>. Proof. by rewrite groupX // cycle_id. Qed. Lemma cycle_subG x G : (<[x]> \subset G) = (x \in G). Proof. by rewrite gen_subG sub1set. Qed. Lemma cycle_eq1 x : (<[x]> == 1) = (x == 1). Proof. by rewrite eqEsubset sub1G andbT cycle_subG inE. Qed. Lemma orderE x : #[x] = #|<[x]>|. Proof. by []. Qed. Lemma order_eq1 x : (#[x] == 1%N) = (x == 1). Proof. by rewrite -trivg_card1 cycle_eq1. Qed. Lemma order_gt1 x : (#[x] > 1) = (x != 1). Proof. by rewrite ltnNge -trivg_card_le1 cycle_eq1. Qed. Lemma cycle_traject x : <[x]> =i traject (mulg x) 1 #[x]. Proof. set t := _ 1; apply: fsym; apply/subset_cardP; last first. by apply/subsetP=> _ /trajectP[i _ ->]; rewrite -iteropE mem_cycle. rewrite (card_uniqP _) ?size_traject //; case def_n: #[_] => // [n]. rewrite looping_uniq; apply: contraL (card_size (t n)) => /loopingP t_xi. rewrite -ltnNge size_traject -def_n ?subset_leq_card //. rewrite -(eq_subset_r (in_set _)) {}/t; set G := finset _. rewrite -[x]mulg1 -[G]gen_set_id ?genS ?sub1set ?inE ?(t_xi 1%N)//. apply/group_setP; split=> [|y z]; rewrite !inE ?(t_xi 0) //. by do 2!case/trajectP=> ? _ ->; rewrite -!iteropE -expgD [x ^+ _]iteropE. Qed. Lemma cycle2g x : #[x] = 2 -> <[x]> = [set 1; x]. Proof. by move=> ox; apply/setP=> y; rewrite cycle_traject ox !inE mulg1. Qed. Lemma cyclePmin x y : y \in <[x]> -> {i | i < #[x] & y = x ^+ i}. Proof. rewrite cycle_traject; set tx := traject _ _ #[x] => tx_y; pose i := index y tx. have lt_i_x : i < #[x] by rewrite -index_mem size_traject in tx_y. by exists i; rewrite // [x ^+ i]iteropE /= -(nth_traject _ lt_i_x) nth_index. Qed. Lemma cycleP x y : reflect (exists i, y = x ^+ i) (y \in <[x]>). Proof. by apply: (iffP idP) => [/cyclePmin[i _]|[i ->]]; [exists i | apply: mem_cycle]. Qed. Lemma expg_order x : x ^+ #[x] = 1. Proof. have: uniq (traject (mulg x) 1 #[x]). by apply/card_uniqP; rewrite size_traject -(eq_card (cycle_traject x)). case/cyclePmin: (mem_cycle x #[x]) => [] [//|i] ltix. rewrite -(subnKC ltix) addSnnS /= expgD; move: (_ - _) => j x_j1. case/andP=> /trajectP[]; exists j; first exact: leq_addl. by apply: (mulgI (x ^+ i.+1)); rewrite -iterSr iterS -iteropE -expgS mulg1. Qed. Lemma expg_mod p k x : x ^+ p = 1 -> x ^+ (k %% p) = x ^+ k. Proof. move=> xp. by rewrite {2}(divn_eq k p) expgD mulnC expgM xp expg1n mul1g. Qed. Lemma expg_mod_order x i : x ^+ (i %% #[x]) = x ^+ i. Proof. by rewrite expg_mod // expg_order. Qed. Lemma invg_expg x : x^-1 = x ^+ #[x].-1. Proof. by apply/eqP; rewrite eq_invg_mul -expgS prednK ?expg_order. Qed. Lemma invg2id x : #[x] = 2 -> x^-1 = x. Proof. by move=> ox; rewrite invg_expg ox. Qed. Lemma cycleX x i : <[x ^+ i]> \subset <[x]>. Proof. by rewrite cycle_subG; apply: mem_cycle. Qed. Lemma cycleV x : <[x^-1]> = <[x]>. Proof. by apply/eqP; rewrite eq_sym eqEsubset !cycle_subG groupV -groupV !cycle_id. Qed. Lemma orderV x : #[x^-1] = #[x]. Proof. by rewrite /order cycleV. Qed. Lemma cycleJ x y : <[x ^ y]> = <[x]> :^ y. Proof. by rewrite -genJ conjg_set1. Qed. Lemma orderJ x y : #[x ^ y] = #[x]. Proof. by rewrite /order cycleJ cardJg. Qed. End Cycles. Section Normaliser. Variable gT : finGroupType. Implicit Types x y z : gT. Implicit Types A B C D : {set gT}. Implicit Type G H K : {group gT}. Lemma normP x A : reflect (A :^ x = A) (x \in 'N(A)). Proof. suffices ->: (x \in 'N(A)) = (A :^ x == A) by apply: eqP. by rewrite eqEcard cardJg leqnn andbT inE. Qed. Arguments normP {x A}. Lemma group_set_normaliser A : group_set 'N(A). Proof. apply/group_setP; split=> [|x y Nx Ny]; rewrite inE ?conjsg1 //. by rewrite conjsgM !(normP _). Qed. Canonical normaliser_group A := group (group_set_normaliser A). Lemma normsP A B : reflect {in A, normalised B} (A \subset 'N(B)). Proof. apply: (iffP subsetP) => nBA x Ax; last by rewrite inE nBA //. by apply/normP; apply: nBA. Qed. Arguments normsP {A B}. Lemma memJ_norm x y A : x \in 'N(A) -> (y ^ x \in A) = (y \in A). Proof. by move=> Nx; rewrite -{1}(normP Nx) memJ_conjg. Qed. Lemma norms_cycle x y : (<[y]> \subset 'N(<[x]>)) = (x ^ y \in <[x]>). Proof. by rewrite cycle_subG inE -cycleJ cycle_subG. Qed. Lemma norm1 : 'N(1) = setT :> {set gT}. Proof. by apply/setP=> x; rewrite !inE conjs1g subxx. Qed. Lemma norms1 A : A \subset 'N(1). Proof. by rewrite norm1 subsetT. Qed. Lemma normCs A : 'N(~: A) = 'N(A). Proof. by apply/setP=> x; rewrite -groupV !inE conjCg setCS sub_conjg. Qed. Lemma normG G : G \subset 'N(G). Proof. by apply/normsP; apply: conjGid. Qed. Lemma normT : 'N([set: gT]) = [set: gT]. Proof. by apply/eqP; rewrite -subTset normG. Qed. Lemma normsG A G : A \subset G -> A \subset 'N(G). Proof. by move=> sAG; apply: subset_trans (normG G). Qed. Lemma normC A B : A \subset 'N(B) -> commute A B. Proof. move/subsetP=> nBA; apply/setP=> u. apply/mulsgP/mulsgP=> [[x y Ax By] | [y x By Ax]] -> {u}. by exists (y ^ x^-1) x; rewrite -?conjgCV // memJ_norm // groupV nBA. by exists x (y ^ x); rewrite -?conjgC // memJ_norm // nBA. Qed. Lemma norm_joinEl G H : G \subset 'N(H) -> G <*> H = G * H. Proof. by move/normC/comm_joingE. Qed. Lemma norm_joinEr G H : H \subset 'N(G) -> G <*> H = G * H. Proof. by move/normC=> cHG; apply: comm_joingE. Qed. Lemma norm_rlcoset G x : x \in 'N(G) -> G :* x = x *: G. Proof. by rewrite -sub1set => /normC. Qed. Lemma rcoset_mul G x y : x \in 'N(G) -> (G :* x) * (G :* y) = G :* (x * y). Proof. move/norm_rlcoset=> GxxG. by rewrite mulgA -(mulgA _ _ G) -GxxG mulgA mulGid -mulgA mulg_set1. Qed. Lemma normJ A x : 'N(A :^ x) = 'N(A) :^ x. Proof. by apply/setP=> y; rewrite mem_conjg !inE -conjsgM conjgCV conjsgM conjSg. Qed. Lemma norm_conj_norm x A B : x \in 'N(A) -> (A \subset 'N(B :^ x)) = (A \subset 'N(B)). Proof. by move=> Nx; rewrite normJ -sub_conjgV (normP _) ?groupV. Qed. Lemma norm_gen A : 'N(A) \subset 'N(<<A>>). Proof. by apply/normsP=> x Nx; rewrite -genJ (normP Nx). Qed. Lemma class_norm x G : G \subset 'N(x ^: G). Proof. by apply/normsP=> y; apply: classGidr. Qed. Lemma class_normal x G : x \in G -> x ^: G <| G. Proof. by move=> Gx; rewrite /normal class_norm class_subG. Qed. Lemma class_sub_norm G A x : G \subset 'N(A) -> (x ^: G \subset A) = (x \in A). Proof. move=> nAG; apply/subsetP/idP=> [-> // | Ax xy]; first exact: class_refl. by case/imsetP=> y Gy ->; rewrite memJ_norm ?(subsetP nAG). Qed. Lemma class_support_norm A G : G \subset 'N(class_support A G). Proof. by apply/normsP; apply: class_supportGidr. Qed. Lemma class_support_sub_norm A B G : A \subset G -> B \subset 'N(G) -> class_support A B \subset G. Proof. move=> sAG nGB; rewrite class_supportEr. by apply/bigcupsP=> x Bx; rewrite -(normsP nGB x Bx) conjSg. Qed. Section norm_trans. Variables (A B C D : {set gT}). Hypotheses (nBA : A \subset 'N(B)) (nCA : A \subset 'N(C)). Lemma norms_gen : A \subset 'N(<<B>>). Proof. exact: subset_trans nBA (norm_gen B). Qed. Lemma norms_norm : A \subset 'N('N(B)). Proof. by apply/normsP=> x Ax; rewrite -normJ (normsP nBA). Qed. Lemma normsI : A \subset 'N(B :&: C). Proof. by apply/normsP=> x Ax; rewrite conjIg !(normsP _ x Ax). Qed. Lemma normsU : A \subset 'N(B :|: C). Proof. by apply/normsP=> x Ax; rewrite conjUg !(normsP _ x Ax). Qed. Lemma normsIs : B \subset 'N(D) -> A :&: B \subset 'N(C :&: D). Proof. move/normsP=> nDB; apply/normsP=> x; case/setIP=> Ax Bx. by rewrite conjIg (normsP nCA) ?nDB. Qed. Lemma normsD : A \subset 'N(B :\: C). Proof. by apply/normsP=> x Ax; rewrite conjDg !(normsP _ x Ax). Qed. Lemma normsM : A \subset 'N(B * C). Proof. by apply/normsP=> x Ax; rewrite conjsMg !(normsP _ x Ax). Qed. Lemma normsY : A \subset 'N(B <*> C). Proof. by apply/normsP=> x Ax; rewrite -genJ conjUg !(normsP _ x Ax). Qed. Lemma normsR : A \subset 'N([~: B, C]). Proof. by apply/normsP=> x Ax; rewrite conjsRg !(normsP _ x Ax). Qed. Lemma norms_class_support : A \subset 'N(class_support B C). Proof. apply/subsetP=> x Ax; rewrite inE sub_conjg class_supportEr. apply/bigcupsP=> y Cy; rewrite -sub_conjg -conjsgM conjgC conjsgM. by rewrite (normsP nBA) // bigcup_sup ?memJ_norm ?(subsetP nCA). Qed. End norm_trans. Lemma normsIG A B G : A \subset 'N(B) -> A :&: G \subset 'N(B :&: G). Proof. by move/normsIs->; rewrite ?normG. Qed. Lemma normsGI A B G : A \subset 'N(B) -> G :&: A \subset 'N(G :&: B). Proof. by move=> nBA; rewrite !(setIC G) normsIG. Qed. Lemma norms_bigcap I r (P : pred I) A (B_ : I -> {set gT}) : A \subset \bigcap_(i <- r | P i) 'N(B_ i) -> A \subset 'N(\bigcap_(i <- r | P i) B_ i). Proof. elim/big_rec2: _ => [|i B N _ IH /subsetIP[nBiA /IH]]; last exact: normsI. by rewrite normT. Qed. Lemma norms_bigcup I r (P : pred I) A (B_ : I -> {set gT}) : A \subset \bigcap_(i <- r | P i) 'N(B_ i) -> A \subset 'N(\bigcup_(i <- r | P i) B_ i). Proof. move=> nBA; rewrite -normCs setC_bigcup norms_bigcap //. by rewrite (eq_bigr _ (fun _ _ => normCs _)). Qed. Lemma normsD1 A B : A \subset 'N(B) -> A \subset 'N(B^#). Proof. by move/normsD->; rewrite ?norms1. Qed. Lemma normD1 A : 'N(A^#) = 'N(A). Proof. apply/eqP; rewrite eqEsubset normsD1 //. rewrite -{2}(setID A 1) setIC normsU //; apply/normsP=> x _; apply/setP=> y. by rewrite conjIg conjs1g !inE mem_conjg; case: eqP => // ->; rewrite conj1g. Qed. Lemma normalP A B : reflect (A \subset B /\ {in B, normalised A}) (A <| B). Proof. by apply: (iffP andP)=> [] [sAB]; move/normsP. Qed. Lemma normal_sub A B : A <| B -> A \subset B. Proof. by case/andP. Qed. Lemma normal_norm A B : A <| B -> B \subset 'N(A). Proof. by case/andP. Qed. Lemma normalS G H K : K \subset H -> H \subset G -> K <| G -> K <| H. Proof. by move=> sKH sHG /andP[_ nKG]; rewrite /(K <| _) sKH (subset_trans sHG). Qed. Lemma normal1 G : 1 <| G. Proof. by rewrite /normal sub1set group1 norms1. Qed. Lemma normal_refl G : G <| G. Proof. by rewrite /(G <| _) normG subxx. Qed. Lemma normalG G : G <| 'N(G). Proof. by rewrite /(G <| _) normG subxx. Qed. Lemma normalSG G H : H \subset G -> H <| 'N_G(H). Proof. by move=> sHG; rewrite /normal subsetI sHG normG subsetIr. Qed. Lemma normalJ A B x : (A :^ x <| B :^ x) = (A <| B). Proof. by rewrite /normal normJ !conjSg. Qed. Lemma normalM G A B : A <| G -> B <| G -> A * B <| G. Proof. by case/andP=> sAG nAG /andP[sBG nBG]; rewrite /normal mul_subG ?normsM. Qed. Lemma normalY G A B : A <| G -> B <| G -> A <*> B <| G. Proof. by case/andP=> sAG ? /andP[sBG ?]; rewrite /normal join_subG sAG sBG ?normsY. Qed. Lemma normalYl G H : (H <| H <*> G) = (G \subset 'N(H)). Proof. by rewrite /normal joing_subl join_subG normG. Qed. Lemma normalYr G H : (H <| G <*> H) = (G \subset 'N(H)). Proof. by rewrite joingC normalYl. Qed. Lemma normalI G A B : A <| G -> B <| G -> A :&: B <| G. Proof. by case/andP=> sAG nAG /andP[_ nBG]; rewrite /normal subIset ?sAG // normsI. Qed. Lemma norm_normalI G A : G \subset 'N(A) -> G :&: A <| G. Proof. by move=> nAG; rewrite /normal subsetIl normsI ?normG. Qed. Lemma normalGI G H A : H \subset G -> A <| G -> H :&: A <| H. Proof. by move=> sHG /andP[_ nAG]; apply: norm_normalI (subset_trans sHG nAG). Qed. Lemma normal_subnorm G H : (H <| 'N_G(H)) = (H \subset G). Proof. by rewrite /normal subsetIr subsetI normG !andbT. Qed. Lemma normalD1 A G : (A^# <| G) = (A <| G). Proof. by rewrite /normal normD1 subDset (setUidPr (sub1G G)). Qed. Lemma gcore_sub A G : gcore A G \subset A. Proof. by rewrite (bigcap_min 1) ?conjsg1. Qed. Lemma gcore_norm A G : G \subset 'N(gcore A G). Proof. apply/subsetP=> x Gx; rewrite inE; apply/bigcapsP=> y Gy. by rewrite sub_conjg -conjsgM bigcap_inf ?groupM ?groupV. Qed. Lemma gcore_normal A G : A \subset G -> gcore A G <| G. Proof. by move=> sAG; rewrite /normal gcore_norm (subset_trans (gcore_sub A G)). Qed. Lemma gcore_max A B G : B \subset A -> G \subset 'N(B) -> B \subset gcore A G. Proof. move=> sBA nBG; apply/bigcapsP=> y Gy. by rewrite -sub_conjgV (normsP nBG) ?groupV. Qed. Lemma sub_gcore A B G : G \subset 'N(B) -> (B \subset gcore A G) = (B \subset A). Proof. move=> nBG; apply/idP/idP=> [sBAG | sBA]; last exact: gcore_max. exact: subset_trans (gcore_sub A G). Qed. (* An elementary proof that subgroups of index 2 are normal; it is almost as *) (* short as the "advanced" proof using group actions; besides, the fact that *) (* the coset is equal to the complement is used in extremal.v. *) Lemma rcoset_index2 G H x : H \subset G -> #|G : H| = 2 -> x \in G :\: H -> H :* x = G :\: H. Proof. move=> sHG indexHG => /setDP[Gx notHx]; apply/eqP. rewrite eqEcard -(leq_add2l #|G :&: H|) cardsID -(LagrangeI G H) indexHG muln2. rewrite (setIidPr sHG) card_rcoset addnn leqnn andbT. apply/subsetP=> _ /rcosetP[y Hy ->]; apply/setDP. by rewrite !groupMl // (subsetP sHG). Qed. Lemma index2_normal G H : H \subset G -> #|G : H| = 2 -> H <| G. Proof. move=> sHG indexHG; rewrite /normal sHG; apply/subsetP=> x Gx. case Hx: (x \in H); first by rewrite inE conjGid. rewrite inE conjsgE mulgA -sub_rcosetV -invg_rcoset. by rewrite !(rcoset_index2 sHG) ?inE ?groupV ?Hx // invDg !invGid. Qed. Lemma cent1P x y : reflect (commute x y) (x \in 'C[y]). Proof. rewrite [x \in _]inE conjg_set1 sub1set !inE (sameP eqP conjg_fixP)commg1_sym. exact: commgP. Qed. Lemma cent1id x : x \in 'C[x]. Proof. exact/cent1P. Qed. Lemma cent1E x y : (x \in 'C[y]) = (x * y == y * x). Proof. by rewrite (sameP (cent1P x y) eqP). Qed. Lemma cent1C x y : (x \in 'C[y]) = (y \in 'C[x]). Proof. by rewrite !cent1E eq_sym. Qed. Canonical centraliser_group A : {group _} := Eval hnf in [group of 'C(A)]. Lemma cent_set1 x : 'C([set x]) = 'C[x]. Proof. by apply: big_pred1 => y /=; rewrite !inE. Qed. Lemma cent1J x y : 'C[x ^ y] = 'C[x] :^ y. Proof. by rewrite -conjg_set1 normJ. Qed. Lemma centP A x : reflect (centralises x A) (x \in 'C(A)). Proof. by apply: (iffP bigcapP) => cxA y /cxA/cent1P. Qed. Lemma centsP A B : reflect {in A, centralised B} (A \subset 'C(B)). Proof. by apply: (iffP subsetP) => cAB x /cAB/centP. Qed. Lemma centsC A B : (A \subset 'C(B)) = (B \subset 'C(A)). Proof. by apply/centsP/centsP=> cAB x ? y ?; rewrite /commute -cAB. Qed. Lemma cents1 A : A \subset 'C(1). Proof. by rewrite centsC sub1G. Qed. Lemma cent1T : 'C(1) = setT :> {set gT}. Proof. by apply/eqP; rewrite -subTset cents1. Qed. Lemma cent11T : 'C[1] = setT :> {set gT}. Proof. by rewrite -cent_set1 cent1T. Qed. Lemma cent_sub A : 'C(A) \subset 'N(A). Proof. apply/subsetP=> x /centP cAx; rewrite inE. by apply/subsetP=> _ /imsetP[y Ay ->]; rewrite /conjg -cAx ?mulKg. Qed. Lemma cents_norm A B : A \subset 'C(B) -> A \subset 'N(B). Proof. by move=> cAB; apply: subset_trans (cent_sub B). Qed. Lemma centC A B : A \subset 'C(B) -> commute A B. Proof. by move=> cAB; apply: normC (cents_norm cAB). Qed. Lemma cent_joinEl G H : G \subset 'C(H) -> G <*> H = G * H. Proof. by move=> cGH; apply: norm_joinEl (cents_norm cGH). Qed. Lemma cent_joinEr G H : H \subset 'C(G) -> G <*> H = G * H. Proof. by move=> cGH; apply: norm_joinEr (cents_norm cGH). Qed. Lemma centJ A x : 'C(A :^ x) = 'C(A) :^ x. Proof. apply/setP=> y; rewrite mem_conjg; apply/centP/centP=> cAy z Az. by apply: (conjg_inj x); rewrite 2!conjMg conjgKV cAy ?memJ_conjg. by apply: (conjg_inj x^-1); rewrite 2!conjMg cAy -?mem_conjg. Qed. Lemma cent_norm A : 'N(A) \subset 'N('C(A)). Proof. by apply/normsP=> x nCx; rewrite -centJ (normP nCx). Qed. Lemma norms_cent A B : A \subset 'N(B) -> A \subset 'N('C(B)). Proof. by move=> nBA; apply: subset_trans nBA (cent_norm B). Qed. Lemma cent_normal A : 'C(A) <| 'N(A). Proof. by rewrite /(_ <| _) cent_sub cent_norm. Qed. Lemma centS A B : B \subset A -> 'C(A) \subset 'C(B). Proof. by move=> sAB; rewrite centsC (subset_trans sAB) 1?centsC. Qed. Lemma centsS A B C : A \subset B -> C \subset 'C(B) -> C \subset 'C(A). Proof. by move=> sAB cCB; apply: subset_trans cCB (centS sAB). Qed. Lemma centSS A B C D : A \subset C -> B \subset D -> C \subset 'C(D) -> A \subset 'C(B). Proof. by move=> sAC sBD cCD; apply: subset_trans (centsS sBD cCD). Qed. Lemma centI A B : 'C(A) <*> 'C(B) \subset 'C(A :&: B). Proof. by rewrite gen_subG subUset !centS ?(subsetIl, subsetIr). Qed. Lemma centU A B : 'C(A :|: B) = 'C(A) :&: 'C(B). Proof. apply/eqP; rewrite eqEsubset subsetI 2?centS ?(subsetUl, subsetUr) //=. by rewrite centsC subUset -centsC subsetIl -centsC subsetIr. Qed. Lemma cent_gen A : 'C(<<A>>) = 'C(A). Proof. by apply/setP=> x; rewrite -!sub1set centsC gen_subG centsC. Qed. Lemma cent_cycle x : 'C(<[x]>) = 'C[x]. Proof. by rewrite cent_gen cent_set1. Qed. Lemma sub_cent1 A x : (A \subset 'C[x]) = (x \in 'C(A)). Proof. by rewrite -cent_cycle centsC cycle_subG. Qed. Lemma cents_cycle x y : commute x y -> <[x]> \subset 'C(<[y]>). Proof. by move=> cxy; rewrite cent_cycle cycle_subG; apply/cent1P. Qed. Lemma cycle_abelian x : abelian <[x]>. Proof. exact: cents_cycle. Qed. Lemma centY A B : 'C(A <*> B) = 'C(A) :&: 'C(B). Proof. by rewrite cent_gen centU. Qed. Lemma centM G H : 'C(G * H) = 'C(G) :&: 'C(H). Proof. by rewrite -cent_gen genM_join centY. Qed. Lemma cent_classP x G : reflect (x ^: G = [set x]) (x \in 'C(G)). Proof. apply: (iffP (centP _ _)) => [Cx | Cx1 y Gy]. apply/eqP; rewrite eqEsubset sub1set class_refl andbT. by apply/subsetP=> _ /imsetP[y Gy ->]; rewrite !inE conjgE Cx ?mulKg. by apply/commgP/conjg_fixP/set1P; rewrite -Cx1; apply/imsetP; exists y. Qed. Lemma commG1P A B : reflect ([~: A, B] = 1) (A \subset 'C(B)). Proof. apply: (iffP (centsP A B)) => [cAB | cAB1 x Ax y By]. apply/trivgP; rewrite gen_subG; apply/subsetP=> _ /imset2P[x y Ax Ay ->]. by rewrite inE; apply/commgP; apply: cAB. by apply/commgP; rewrite -in_set1 -[[set 1]]cAB1 mem_commg. Qed. Lemma abelianE A : abelian A = (A \subset 'C(A)). Proof. by []. Qed. Lemma abelian1 : abelian [1 gT]. Proof. exact: sub1G. Qed. Lemma abelianS A B : A \subset B -> abelian B -> abelian A. Proof. by move=> sAB; apply: centSS. Qed. Lemma abelianJ A x : abelian (A :^ x) = abelian A. Proof. by rewrite /abelian centJ conjSg. Qed. Lemma abelian_gen A : abelian <<A>> = abelian A. Proof. by rewrite /abelian cent_gen gen_subG. Qed. Lemma abelianY A B : abelian (A <*> B) = [&& abelian A, abelian B & B \subset 'C(A)]. Proof. rewrite /abelian join_subG /= centY !subsetI -!andbA; congr (_ && _). by rewrite centsC andbA andbb andbC. Qed. Lemma abelianM G H : abelian (G * H) = [&& abelian G, abelian H & H \subset 'C(G)]. Proof. by rewrite -abelian_gen genM_join abelianY. Qed. Section SubAbelian. Variable A B C : {set gT}. Hypothesis cAA : abelian A. Lemma sub_abelian_cent : C \subset A -> A \subset 'C(C). Proof. by move=> sCA; rewrite centsC (subset_trans sCA). Qed. Lemma sub_abelian_cent2 : B \subset A -> C \subset A -> B \subset 'C(C). Proof. by move=> sBA; move/sub_abelian_cent; apply: subset_trans. Qed. Lemma sub_abelian_norm : C \subset A -> A \subset 'N(C). Proof. by move=> sCA; rewrite cents_norm ?sub_abelian_cent. Qed. Lemma sub_abelian_normal : (C \subset A) = (C <| A). Proof. by rewrite /normal; case sHG: (C \subset A); rewrite // sub_abelian_norm. Qed. End SubAbelian. End Normaliser. Arguments normP {gT x A}. Arguments centP {gT A x}. Arguments normsP {gT A B}. Arguments cent1P {gT x y}. Arguments normalP {gT A B}. Arguments centsP {gT A B}. Arguments commG1P {gT A B}. Arguments normaliser_group _ _%_g. Arguments centraliser_group _ _%_g. Notation "''N' ( A )" := (normaliser_group A) : Group_scope. Notation "''C' ( A )" := (centraliser_group A) : Group_scope. Notation "''C' [ x ]" := (normaliser_group [set x%g]) : Group_scope. Notation "''N_' G ( A )" := (setI_group G 'N(A)) : Group_scope. Notation "''C_' G ( A )" := (setI_group G 'C(A)) : Group_scope. Notation "''C_' ( G ) ( A )" := (setI_group G 'C(A)) (only parsing) : Group_scope. Notation "''C_' G [ x ]" := (setI_group G 'C[x]) : Group_scope. Notation "''C_' ( G ) [ x ]" := (setI_group G 'C[x]) (only parsing) : Group_scope. #[global] Hint Extern 0 (is_true (_ \subset _)) => apply: normG : core. #[global] Hint Extern 0 (is_true (_ <| _)) => apply: normal_refl : core. Section MinMaxGroup. Variable gT : finGroupType. Implicit Types gP : pred {group gT}. Definition maxgroup A gP := maxset (fun A => group_set A && gP <<A>>%G) A. Definition mingroup A gP := minset (fun A => group_set A && gP <<A>>%G) A. Variable gP : pred {group gT}. Arguments gP _%_G. Lemma ex_maxgroup : (exists G, gP G) -> {G : {group gT} | maxgroup G gP}. Proof. move=> exP; have [A maxA]: {A | maxgroup A gP}. apply: ex_maxset; case: exP => G gPG. by exists (G : {set gT}); rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA). Qed. Lemma ex_mingroup : (exists G, gP G) -> {G : {group gT} | mingroup G gP}. Proof. move=> exP; have [A minA]: {A | mingroup A gP}. apply: ex_minset; case: exP => G gPG. by exists (G : {set gT}); rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp minA). Qed. Variable G : {group gT}. Lemma mingroupP : reflect (gP G /\ forall H, gP H -> H \subset G -> H :=: G) (mingroup G gP). Proof. apply: (iffP minsetP); rewrite /= groupP genGidG /= => [] [-> minG]. by split=> // H gPH sGH; apply: minG; rewrite // groupP genGidG. by split=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); apply: minG. Qed. Lemma maxgroupP : reflect (gP G /\ forall H, gP H -> G \subset H -> H :=: G) (maxgroup G gP). Proof. apply: (iffP maxsetP); rewrite /= groupP genGidG /= => [] [-> maxG]. by split=> // H gPH sGH; apply: maxG; rewrite // groupP genGidG. by split=> // A; case/andP=> gA gPA; rewrite -(gen_set_id gA); apply: maxG. Qed. Lemma maxgroupp : maxgroup G gP -> gP G. Proof. by case/maxgroupP. Qed. Lemma mingroupp : mingroup G gP -> gP G. Proof. by case/mingroupP. Qed. Hypothesis gPG : gP G. Lemma maxgroup_exists : {H : {group gT} | maxgroup H gP & G \subset H}. Proof. have [A maxA sGA]: {A | maxgroup A gP & G \subset A}. by apply: maxset_exists; rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (maxsetp maxA). Qed. Lemma mingroup_exists : {H : {group gT} | mingroup H gP & H \subset G}. Proof. have [A maxA sGA]: {A | mingroup A gP & A \subset G}. by apply: minset_exists; rewrite groupP genGidG. by exists <<A>>%G; rewrite /= gen_set_id; case/andP: (minsetp maxA). Qed. End MinMaxGroup. Arguments mingroup {gT} A%_g gP. Arguments maxgroup {gT} A%_g gP. Arguments mingroupP {gT gP G}. Arguments maxgroupP {gT gP G}. Notation "[ 'max' A 'of' G | gP ]" := (maxgroup A (fun G : {group _} => gP)) : group_scope. Notation "[ 'max' G | gP ]" := [max gval G of G | gP] : group_scope. Notation "[ 'max' A 'of' G | gP & gQ ]" := [max A of G | gP && gQ] : group_scope. Notation "[ 'max' G | gP & gQ ]" := [max G | gP && gQ] : group_scope. Notation "[ 'min' A 'of' G | gP ]" := (mingroup A (fun G : {group _} => gP)) : group_scope. Notation "[ 'min' G | gP ]" := [min gval G of G | gP] : group_scope. Notation "[ 'min' A 'of' G | gP & gQ ]" := [min A of G | gP && gQ] : group_scope. Notation "[ 'min' G | gP & gQ ]" := [min G | gP && gQ] : group_scope. HB.reexport.
Basic.lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth -/ import Mathlib.Topology.Algebra.Indicator import Mathlib.Topology.Bornology.BoundedOperation import Mathlib.Topology.ContinuousMap.Algebra /-! # Bounded continuous functions The type of bounded continuous functions taking values in a metric space, with the uniform distance. -/ assert_not_exists CStarRing noncomputable section open Topology Bornology NNReal UniformConvergence open Set Filter Metric Function universe u v w variable {F : Type*} {α : Type u} {β : Type v} {γ : Type w} /-- `α →ᵇ β` is the type of bounded continuous functions `α → β` from a topological space to a metric space. When possible, instead of parametrizing results over `(f : α →ᵇ β)`, you should parametrize over `(F : Type*) [BoundedContinuousMapClass F α β] (f : F)`. When you extend this structure, make sure to extend `BoundedContinuousMapClass`. -/ structure BoundedContinuousFunction (α : Type u) (β : Type v) [TopologicalSpace α] [PseudoMetricSpace β] : Type max u v extends ContinuousMap α β where map_bounded' : ∃ C, ∀ x y, dist (toFun x) (toFun y) ≤ C @[inherit_doc] scoped[BoundedContinuousFunction] infixr:25 " →ᵇ " => BoundedContinuousFunction section /-- `BoundedContinuousMapClass F α β` states that `F` is a type of bounded continuous maps. You should also extend this typeclass when you extend `BoundedContinuousFunction`. -/ class BoundedContinuousMapClass (F : Type*) (α β : outParam Type*) [TopologicalSpace α] [PseudoMetricSpace β] [FunLike F α β] : Prop extends ContinuousMapClass F α β where map_bounded (f : F) : ∃ C, ∀ x y, dist (f x) (f y) ≤ C end export BoundedContinuousMapClass (map_bounded) namespace BoundedContinuousFunction section Basics variable [TopologicalSpace α] [PseudoMetricSpace β] [PseudoMetricSpace γ] variable {f g : α →ᵇ β} {x : α} {C : ℝ} instance instFunLike : FunLike (α →ᵇ β) α β where coe f := f.toFun coe_injective' f g h := by obtain ⟨⟨_, _⟩, _⟩ := f obtain ⟨⟨_, _⟩, _⟩ := g congr instance instBoundedContinuousMapClass : BoundedContinuousMapClass (α →ᵇ β) α β where map_continuous f := f.continuous_toFun map_bounded f := f.map_bounded' instance instCoeTC [FunLike F α β] [BoundedContinuousMapClass F α β] : CoeTC F (α →ᵇ β) := ⟨fun f => { toFun := f continuous_toFun := map_continuous f map_bounded' := map_bounded f }⟩ @[simp] theorem coe_toContinuousMap (f : α →ᵇ β) : (f.toContinuousMap : α → β) = f := rfl /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def Simps.apply (h : α →ᵇ β) : α → β := h initialize_simps_projections BoundedContinuousFunction (toFun → apply) protected theorem bounded (f : α →ᵇ β) : ∃ C, ∀ x y : α, dist (f x) (f y) ≤ C := f.map_bounded' protected theorem continuous (f : α →ᵇ β) : Continuous f := f.toContinuousMap.continuous @[ext] theorem ext (h : ∀ x, f x = g x) : f = g := DFunLike.ext _ _ h theorem isBounded_range (f : α →ᵇ β) : IsBounded (range f) := isBounded_range_iff.2 f.bounded theorem isBounded_image (f : α →ᵇ β) (s : Set α) : IsBounded (f '' s) := f.isBounded_range.subset <| image_subset_range _ _ theorem eq_of_empty [h : IsEmpty α] (f g : α →ᵇ β) : f = g := ext <| h.elim /-- A continuous function with an explicit bound is a bounded continuous function. -/ def mkOfBound (f : C(α, β)) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨f, ⟨C, h⟩⟩ @[simp] theorem mkOfBound_coe {f} {C} {h} : (mkOfBound f C h : α → β) = (f : α → β) := rfl /-- A continuous function on a compact space is automatically a bounded continuous function. -/ def mkOfCompact [CompactSpace α] (f : C(α, β)) : α →ᵇ β := ⟨f, isBounded_range_iff.1 (isCompact_range f.continuous).isBounded⟩ @[simp] theorem mkOfCompact_apply [CompactSpace α] (f : C(α, β)) (a : α) : mkOfCompact f a = f a := rfl /-- If a function is bounded on a discrete space, it is automatically continuous, and therefore gives rise to an element of the type of bounded continuous functions. -/ @[simps] def mkOfDiscrete [DiscreteTopology α] (f : α → β) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β := ⟨⟨f, continuous_of_discreteTopology⟩, ⟨C, h⟩⟩ /-- The uniform distance between two bounded continuous functions. -/ instance instDist : Dist (α →ᵇ β) := ⟨fun f g => sInf { C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C }⟩ theorem dist_eq : dist f g = sInf { C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C } := rfl theorem dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C := by rcases isBounded_iff.1 (f.isBounded_range.union g.isBounded_range) with ⟨C, hC⟩ refine ⟨max 0 C, le_max_left _ _, fun x => (hC ?_ ?_).trans (le_max_right _ _)⟩ <;> [left; right] <;> apply mem_range_self /-- The pointwise distance is controlled by the distance between functions, by definition. -/ theorem dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g := le_csInf dist_set_exists fun _ hb => hb.2 x /- This lemma will be needed in the proof of the metric space instance, but it will become useless afterwards as it will be superseded by the general result that the distance is nonnegative in metric spaces. -/ private theorem dist_nonneg' : 0 ≤ dist f g := le_csInf dist_set_exists fun _ => And.left /-- The distance between two functions is controlled by the supremum of the pointwise distances. -/ theorem dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀ x : α, dist (f x) (g x) ≤ C := ⟨fun h x => le_trans (dist_coe_le_dist x) h, fun H => csInf_le ⟨0, fun _ => And.left⟩ ⟨C0, H⟩⟩ theorem dist_le_iff_of_nonempty [Nonempty α] : dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C := ⟨fun h x => le_trans (dist_coe_le_dist x) h, fun w => (dist_le (le_trans dist_nonneg (w (Nonempty.some ‹_›)))).mpr w⟩ theorem dist_lt_of_nonempty_compact [Nonempty α] [CompactSpace α] (w : ∀ x : α, dist (f x) (g x) < C) : dist f g < C := by have c : Continuous fun x => dist (f x) (g x) := by fun_prop obtain ⟨x, -, le⟩ := IsCompact.exists_isMaxOn isCompact_univ Set.univ_nonempty (Continuous.continuousOn c) exact lt_of_le_of_lt (dist_le_iff_of_nonempty.mpr fun y => le trivial) (w x) theorem dist_lt_iff_of_compact [CompactSpace α] (C0 : (0 : ℝ) < C) : dist f g < C ↔ ∀ x : α, dist (f x) (g x) < C := by fconstructor · intro w x exact lt_of_le_of_lt (dist_coe_le_dist x) w · by_cases h : Nonempty α · exact dist_lt_of_nonempty_compact · rintro - convert C0 apply le_antisymm _ dist_nonneg' rw [dist_eq] exact csInf_le ⟨0, fun C => And.left⟩ ⟨le_rfl, fun x => False.elim (h (Nonempty.intro x))⟩ theorem dist_lt_iff_of_nonempty_compact [Nonempty α] [CompactSpace α] : dist f g < C ↔ ∀ x : α, dist (f x) (g x) < C := ⟨fun w x => lt_of_le_of_lt (dist_coe_le_dist x) w, dist_lt_of_nonempty_compact⟩ /-- The type of bounded continuous functions, with the uniform distance, is a pseudometric space. -/ instance instPseudoMetricSpace : PseudoMetricSpace (α →ᵇ β) where dist_self f := le_antisymm ((dist_le le_rfl).2 fun x => by simp) dist_nonneg' dist_comm f g := by simp [dist_eq, dist_comm] dist_triangle _ _ _ := (dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 fun _ => le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) /-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/ instance instMetricSpace {β} [MetricSpace β] : MetricSpace (α →ᵇ β) where eq_of_dist_eq_zero hfg := by ext x exact eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg) theorem nndist_eq : nndist f g = sInf { C | ∀ x : α, nndist (f x) (g x) ≤ C } := Subtype.ext <| dist_eq.trans <| by rw [val_eq_coe, coe_sInf, coe_image] simp_rw [mem_setOf_eq, ← NNReal.coe_le_coe, coe_mk, exists_prop, coe_nndist] theorem nndist_set_exists : ∃ C, ∀ x : α, nndist (f x) (g x) ≤ C := Subtype.exists.mpr <| dist_set_exists.imp fun _ ⟨ha, h⟩ => ⟨ha, h⟩ theorem nndist_coe_le_nndist (x : α) : nndist (f x) (g x) ≤ nndist f g := dist_coe_le_dist x /-- On an empty space, bounded continuous functions are at distance 0. -/ theorem dist_zero_of_empty [IsEmpty α] : dist f g = 0 := by rw [(ext isEmptyElim : f = g), dist_self] theorem dist_eq_iSup : dist f g = ⨆ x : α, dist (f x) (g x) := by cases isEmpty_or_nonempty α · rw [iSup_of_empty', Real.sSup_empty, dist_zero_of_empty] refine (dist_le_iff_of_nonempty.mpr <| le_ciSup ?_).antisymm (ciSup_le dist_coe_le_dist) exact dist_set_exists.imp fun C hC => forall_mem_range.2 hC.2 theorem nndist_eq_iSup : nndist f g = ⨆ x : α, nndist (f x) (g x) := Subtype.ext <| dist_eq_iSup.trans <| by simp_rw [val_eq_coe, coe_iSup, coe_nndist] theorem edist_eq_iSup : edist f g = ⨆ x, edist (f x) (g x) := by simp_rw [edist_nndist, nndist_eq_iSup] refine ENNReal.coe_iSup ⟨nndist f g, ?_⟩ rintro - ⟨x, hx, rfl⟩ exact nndist_coe_le_nndist x theorem tendsto_iff_tendstoUniformly {ι : Type*} {F : ι → α →ᵇ β} {f : α →ᵇ β} {l : Filter ι} : Tendsto F l (𝓝 f) ↔ TendstoUniformly (fun i => F i) f l := Iff.intro (fun h => tendstoUniformly_iff.2 fun ε ε0 => (Metric.tendsto_nhds.mp h ε ε0).mp (Eventually.of_forall fun n hn x => lt_of_le_of_lt (dist_coe_le_dist x) (dist_comm (F n) f ▸ hn))) fun h => Metric.tendsto_nhds.mpr fun _ ε_pos => (h _ (dist_mem_uniformity <| half_pos ε_pos)).mp (Eventually.of_forall fun n hn => lt_of_le_of_lt ((dist_le (half_pos ε_pos).le).mpr fun x => dist_comm (f x) (F n x) ▸ le_of_lt (hn x)) (half_lt_self ε_pos)) /-- The topology on `α →ᵇ β` is exactly the topology induced by the natural map to `α →ᵤ β`. -/ theorem isInducing_coeFn : IsInducing (UniformFun.ofFun ∘ (⇑) : (α →ᵇ β) → α →ᵤ β) := by rw [isInducing_iff_nhds] refine fun f => eq_of_forall_le_iff fun l => ?_ rw [← tendsto_iff_comap, ← tendsto_id', tendsto_iff_tendstoUniformly, UniformFun.tendsto_iff_tendstoUniformly] simp [comp_def] -- TODO: upgrade to `IsUniformEmbedding` theorem isEmbedding_coeFn : IsEmbedding (UniformFun.ofFun ∘ (⇑) : (α →ᵇ β) → α →ᵤ β) := ⟨isInducing_coeFn, fun _ _ h => ext fun x => congr_fun h x⟩ variable (α) in /-- Constant as a continuous bounded function. -/ @[simps! -fullyApplied] def const (b : β) : α →ᵇ β := ⟨ContinuousMap.const α b, 0, by simp⟩ theorem const_apply' (a : α) (b : β) : (const α b : α → β) a = b := rfl /-- If the target space is inhabited, so is the space of bounded continuous functions. -/ instance [Inhabited β] : Inhabited (α →ᵇ β) := ⟨const α default⟩ theorem lipschitz_evalx (x : α) : LipschitzWith 1 fun f : α →ᵇ β => f x := LipschitzWith.mk_one fun _ _ => dist_coe_le_dist x theorem uniformContinuous_coe : @UniformContinuous (α →ᵇ β) (α → β) _ _ (⇑) := uniformContinuous_pi.2 fun x => (lipschitz_evalx x).uniformContinuous theorem continuous_coe : Continuous fun (f : α →ᵇ β) x => f x := UniformContinuous.continuous uniformContinuous_coe /-- When `x` is fixed, `(f : α →ᵇ β) ↦ f x` is continuous. -/ @[continuity] theorem continuous_eval_const {x : α} : Continuous fun f : α →ᵇ β => f x := (continuous_apply x).comp continuous_coe /-- The evaluation map is continuous, as a joint function of `u` and `x`. -/ @[continuity] theorem continuous_eval : Continuous fun p : (α →ᵇ β) × α => p.1 p.2 := (continuous_prod_of_continuous_lipschitzWith _ 1 fun f => f.continuous) <| lipschitz_evalx /-- Bounded continuous functions taking values in a complete space form a complete space. -/ instance instCompleteSpace [CompleteSpace β] : CompleteSpace (α →ᵇ β) := complete_of_cauchySeq_tendsto fun (f : ℕ → α →ᵇ β) (hf : CauchySeq f) => by /- We have to show that `f n` converges to a bounded continuous function. For this, we prove pointwise convergence to define the limit, then check it is a continuous bounded function, and then check the norm convergence. -/ rcases cauchySeq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩ have f_bdd := fun x n m N hn hm => le_trans (dist_coe_le_dist x) (b_bound n m N hn hm) have fx_cau : ∀ x, CauchySeq fun n => f n x := fun x => cauchySeq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩ choose F hF using fun x => cauchySeq_tendsto_of_complete (fx_cau x) /- `F : α → β`, `hF : ∀ (x : α), Tendsto (fun n ↦ ↑(f n) x) atTop (𝓝 (F x))` `F` is the desired limit function. Check that it is uniformly approximated by `f N`. -/ have fF_bdd : ∀ x N, dist (f N x) (F x) ≤ b N := fun x N => le_of_tendsto (tendsto_const_nhds.dist (hF x)) (Filter.eventually_atTop.2 ⟨N, fun n hn => f_bdd x N n N (le_refl N) hn⟩) refine ⟨⟨⟨F, ?_⟩, ?_⟩, ?_⟩ · -- Check that `F` is continuous, as a uniform limit of continuous functions have : TendstoUniformly (fun n x => f n x) F atTop := by refine Metric.tendstoUniformly_iff.2 fun ε ε0 => ?_ refine ((tendsto_order.1 b_lim).2 ε ε0).mono fun n hn x => ?_ rw [dist_comm] exact lt_of_le_of_lt (fF_bdd x n) hn exact this.continuous (Eventually.of_forall fun N => (f N).continuous) · -- Check that `F` is bounded rcases (f 0).bounded with ⟨C, hC⟩ refine ⟨C + (b 0 + b 0), fun x y => ?_⟩ calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) := dist_triangle4_left _ _ _ _ _ ≤ C + (b 0 + b 0) := add_le_add (hC x y) (add_le_add (fF_bdd x 0) (fF_bdd y 0)) · -- Check that `F` is close to `f N` in distance terms refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (fun _ => dist_nonneg) ?_ b_lim) exact fun N => (dist_le (b0 _)).2 fun x => fF_bdd x N /-- Composition of a bounded continuous function and a continuous function. -/ def compContinuous {δ : Type*} [TopologicalSpace δ] (f : α →ᵇ β) (g : C(δ, α)) : δ →ᵇ β where toContinuousMap := f.1.comp g map_bounded' := f.map_bounded'.imp fun _ hC _ _ => hC _ _ @[simp] theorem coe_compContinuous {δ : Type*} [TopologicalSpace δ] (f : α →ᵇ β) (g : C(δ, α)) : ⇑(f.compContinuous g) = f ∘ g := rfl @[simp] theorem compContinuous_apply {δ : Type*} [TopologicalSpace δ] (f : α →ᵇ β) (g : C(δ, α)) (x : δ) : f.compContinuous g x = f (g x) := rfl theorem lipschitz_compContinuous {δ : Type*} [TopologicalSpace δ] (g : C(δ, α)) : LipschitzWith 1 fun f : α →ᵇ β => f.compContinuous g := LipschitzWith.mk_one fun _ _ => (dist_le dist_nonneg).2 fun x => dist_coe_le_dist (g x) theorem continuous_compContinuous {δ : Type*} [TopologicalSpace δ] (g : C(δ, α)) : Continuous fun f : α →ᵇ β => f.compContinuous g := (lipschitz_compContinuous g).continuous /-- Restrict a bounded continuous function to a set. -/ def restrict (f : α →ᵇ β) (s : Set α) : s →ᵇ β := f.compContinuous <| (ContinuousMap.id _).restrict s @[simp] theorem coe_restrict (f : α →ᵇ β) (s : Set α) : ⇑(f.restrict s) = f ∘ (↑) := rfl @[simp] theorem restrict_apply (f : α →ᵇ β) (s : Set α) (x : s) : f.restrict s x = f x := rfl /-- Composition (in the target) of a bounded continuous function with a Lipschitz map again gives a bounded continuous function. -/ def comp (G : β → γ) {C : ℝ≥0} (H : LipschitzWith C G) (f : α →ᵇ β) : α →ᵇ γ := ⟨⟨fun x => G (f x), H.continuous.comp f.continuous⟩, let ⟨D, hD⟩ := f.bounded ⟨max C 0 * D, fun x y => calc dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) := H.dist_le_mul _ _ _ ≤ max C 0 * dist (f x) (f y) := by gcongr; apply le_max_left _ ≤ max C 0 * D := by gcongr; apply hD ⟩⟩ @[simp] theorem comp_apply (G : β → γ) {C : ℝ≥0} (H : LipschitzWith C G) (f : α →ᵇ β) (a : α) : (f.comp G H) a = G (f a) := rfl /-- The composition operator (in the target) with a Lipschitz map is Lipschitz. -/ theorem lipschitz_comp {G : β → γ} {C : ℝ≥0} (H : LipschitzWith C G) : LipschitzWith C (comp G H : (α →ᵇ β) → α →ᵇ γ) := LipschitzWith.of_dist_le_mul fun f g => (dist_le (mul_nonneg C.2 dist_nonneg)).2 fun x => calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) := H.dist_le_mul _ _ _ ≤ C * dist f g := by gcongr; apply dist_coe_le_dist /-- The composition operator (in the target) with a Lipschitz map is uniformly continuous. -/ theorem uniformContinuous_comp {G : β → γ} {C : ℝ≥0} (H : LipschitzWith C G) : UniformContinuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).uniformContinuous /-- The composition operator (in the target) with a Lipschitz map is continuous. -/ theorem continuous_comp {G : β → γ} {C : ℝ≥0} (H : LipschitzWith C G) : Continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) := (lipschitz_comp H).continuous /-- Restriction (in the target) of a bounded continuous function taking values in a subset. -/ def codRestrict (s : Set β) (f : α →ᵇ β) (H : ∀ x, f x ∈ s) : α →ᵇ s := ⟨⟨s.codRestrict f H, f.continuous.subtype_mk _⟩, f.bounded⟩ section Extend variable {δ : Type*} [TopologicalSpace δ] [DiscreteTopology δ] /-- A version of `Function.extend` for bounded continuous maps. We assume that the domain has discrete topology, so we only need to verify boundedness. -/ nonrec def extend (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : δ →ᵇ β where toFun := extend f g h continuous_toFun := continuous_of_discreteTopology map_bounded' := by rw [← isBounded_range_iff, range_extend f.injective] exact g.isBounded_range.union (h.isBounded_image _) @[simp] theorem extend_apply (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) (x : α) : extend f g h (f x) = g x := f.injective.extend_apply _ _ _ @[simp] nonrec theorem extend_comp (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h ∘ f = g := extend_comp f.injective _ _ nonrec theorem extend_apply' {f : α ↪ δ} {x : δ} (hx : x ∉ range f) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h x = h x := extend_apply' _ _ _ hx theorem extend_of_empty [IsEmpty α] (f : α ↪ δ) (g : α →ᵇ β) (h : δ →ᵇ β) : extend f g h = h := DFunLike.coe_injective <| Function.extend_of_isEmpty f g h @[simp] theorem dist_extend_extend (f : α ↪ δ) (g₁ g₂ : α →ᵇ β) (h₁ h₂ : δ →ᵇ β) : dist (g₁.extend f h₁) (g₂.extend f h₂) = max (dist g₁ g₂) (dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ)) := by refine le_antisymm ((dist_le <| le_max_iff.2 <| Or.inl dist_nonneg).2 fun x => ?_) (max_le ?_ ?_) · rcases em (∃ y, f y = x) with (⟨x, rfl⟩ | hx) · simp only [extend_apply] exact (dist_coe_le_dist x).trans (le_max_left _ _) · simp only [extend_apply' hx] lift x to ((range f)ᶜ : Set δ) using hx calc dist (h₁ x) (h₂ x) = dist (h₁.restrict (range f)ᶜ x) (h₂.restrict (range f)ᶜ x) := rfl _ ≤ dist (h₁.restrict (range f)ᶜ) (h₂.restrict (range f)ᶜ) := dist_coe_le_dist x _ ≤ _ := le_max_right _ _ · refine (dist_le dist_nonneg).2 fun x => ?_ rw [← extend_apply f g₁ h₁, ← extend_apply f g₂ h₂] exact dist_coe_le_dist _ · refine (dist_le dist_nonneg).2 fun x => ?_ calc dist (h₁ x) (h₂ x) = dist (extend f g₁ h₁ x) (extend f g₂ h₂ x) := by rw [extend_apply' x.coe_prop, extend_apply' x.coe_prop] _ ≤ _ := dist_coe_le_dist _ theorem isometry_extend (f : α ↪ δ) (h : δ →ᵇ β) : Isometry fun g : α →ᵇ β => extend f g h := Isometry.of_dist_eq fun g₁ g₂ => by simp end Extend /-- The indicator function of a clopen set, as a bounded continuous function. -/ @[simps] noncomputable def indicator (s : Set α) (hs : IsClopen s) : BoundedContinuousFunction α ℝ where toFun := s.indicator 1 continuous_toFun := continuous_indicator (by simp [hs]) <| continuous_const.continuousOn map_bounded' := ⟨1, fun x y ↦ by by_cases hx : x ∈ s <;> by_cases hy : y ∈ s <;> simp [hx, hy]⟩ end Basics section One variable [TopologicalSpace α] [PseudoMetricSpace β] [One β] @[to_additive] instance instOne : One (α →ᵇ β) := ⟨const α 1⟩ @[to_additive (attr := simp)] theorem coe_one : ((1 : α →ᵇ β) : α → β) = 1 := rfl @[to_additive (attr := simp)] theorem mkOfCompact_one [CompactSpace α] : mkOfCompact (1 : C(α, β)) = 1 := rfl @[to_additive] theorem forall_coe_one_iff_one (f : α →ᵇ β) : (∀ x, f x = 1) ↔ f = 1 := (@DFunLike.ext_iff _ _ _ _ f 1).symm @[to_additive (attr := simp)] theorem one_compContinuous [TopologicalSpace γ] (f : C(γ, α)) : (1 : α →ᵇ β).compContinuous f = 1 := rfl end One section mul variable {R : Type*} [TopologicalSpace α] [PseudoMetricSpace R] @[to_additive] instance instMul [Mul R] [BoundedMul R] [ContinuousMul R] : Mul (α →ᵇ R) where mul f g := { toFun := fun x ↦ f x * g x continuous_toFun := f.continuous.mul g.continuous map_bounded' := mul_bounded_of_bounded_of_bounded (map_bounded f) (map_bounded g) } @[to_additive (attr := simp)] theorem coe_mul [Mul R] [BoundedMul R] [ContinuousMul R] (f g : α →ᵇ R) : ⇑(f * g) = f * g := rfl @[to_additive] theorem mul_apply [Mul R] [BoundedMul R] [ContinuousMul R] (f g : α →ᵇ R) (x : α) : (f * g) x = f x * g x := rfl @[simp] theorem coe_nsmulRec [PseudoMetricSpace β] [AddMonoid β] [BoundedAdd β] [ContinuousAdd β] (f : α →ᵇ β) : ∀ n, ⇑(nsmulRec n f) = n • ⇑f | 0 => by rw [nsmulRec, zero_smul, coe_zero] | n + 1 => by rw [nsmulRec, succ_nsmul, coe_add, coe_nsmulRec _ n] instance instSMulNat [PseudoMetricSpace β] [AddMonoid β] [BoundedAdd β] [ContinuousAdd β] : SMul ℕ (α →ᵇ β) where smul n f := { toContinuousMap := n • f.toContinuousMap map_bounded' := by simpa [coe_nsmulRec] using (nsmulRec n f).map_bounded' } @[to_additive existing instSMulNat] instance instPow [Monoid R] [BoundedMul R] [ContinuousMul R] : Pow (α →ᵇ R) ℕ where pow f n := { toFun := fun x ↦ (f x) ^ n continuous_toFun := f.continuous.pow n map_bounded' := by obtain ⟨C, hC⟩ := Metric.isBounded_iff.mp <| isBounded_pow (isBounded_range f) n exact ⟨C, fun x y ↦ hC (by simp) (by simp)⟩ } @[to_additive] theorem coe_pow [Monoid R] [BoundedMul R] [ContinuousMul R] (n : ℕ) (f : α →ᵇ R) : ⇑(f ^ n) = (⇑f) ^ n := rfl @[to_additive (attr := simp)] theorem pow_apply [Monoid R] [BoundedMul R] [ContinuousMul R] (n : ℕ) (f : α →ᵇ R) (x : α) : (f ^ n) x = f x ^ n := rfl @[to_additive] instance instMonoid [Monoid R] [BoundedMul R] [ContinuousMul R] : Monoid (α →ᵇ R) := Injective.monoid _ DFunLike.coe_injective' rfl (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) @[to_additive] instance instCommMonoid [CommMonoid R] [BoundedMul R] [ContinuousMul R] : CommMonoid (α →ᵇ R) where __ := instMonoid mul_comm f g := by ext x; simp [mul_apply, mul_comm] @[to_additive] instance instMulOneClass [MulOneClass R] [BoundedMul R] [ContinuousMul R] : MulOneClass (α →ᵇ R) := DFunLike.coe_injective.mulOneClass _ coe_one coe_mul /-- Composition on the left by a (lipschitz-continuous) homomorphism of topological monoids, as a `MonoidHom`. Similar to `MonoidHom.compLeftContinuous`. -/ @[to_additive (attr := simps) /-- Composition on the left by a (lipschitz-continuous) homomorphism of topological `AddMonoid`s, as a `AddMonoidHom`. Similar to `AddMonoidHom.compLeftContinuous`. -/] protected def _root_.MonoidHom.compLeftContinuousBounded (α : Type*) [TopologicalSpace α] [PseudoMetricSpace β] [Monoid β] [BoundedMul β] [ContinuousMul β] [PseudoMetricSpace γ] [Monoid γ] [BoundedMul γ] [ContinuousMul γ] (g : β →* γ) {C : NNReal} (hg : LipschitzWith C g) : (α →ᵇ β) →* (α →ᵇ γ) where toFun f := f.comp g hg map_one' := ext fun _ => g.map_one map_mul' _ _ := ext fun _ => g.map_mul _ _ end mul section add variable [TopologicalSpace α] [PseudoMetricSpace β] variable {C : ℝ} @[simp] theorem mkOfCompact_add [CompactSpace α] [Add β] [BoundedAdd β] [ContinuousAdd β] (f g : C(α, β)) : mkOfCompact (f + g) = mkOfCompact f + mkOfCompact g := rfl theorem add_compContinuous [Add β] [BoundedAdd β] [ContinuousAdd β] [TopologicalSpace γ] (f g : α →ᵇ β) (h : C(γ, α)) : (g + f).compContinuous h = g.compContinuous h + f.compContinuous h := rfl /-- Coercion of a `NormedAddGroupHom` is an `AddMonoidHom`. Similar to `AddMonoidHom.coeFn`. -/ @[simps] def coeFnAddHom [AddMonoid β] [BoundedAdd β] [ContinuousAdd β] : (α →ᵇ β) →+ α → β where toFun := (⇑) map_zero' := coe_zero map_add' := coe_add variable (α β) /-- The additive map forgetting that a bounded continuous function is bounded. -/ @[simps] def toContinuousMapAddHom [AddMonoid β] [BoundedAdd β] [ContinuousAdd β] : (α →ᵇ β) →+ C(α, β) where toFun := toContinuousMap map_zero' := rfl map_add' := by intros ext simp end add section comm_add variable [TopologicalSpace α] variable [PseudoMetricSpace β] [AddCommMonoid β] [BoundedAdd β] [ContinuousAdd β] @[simp] theorem coe_sum {ι : Type*} (s : Finset ι) (f : ι → α →ᵇ β) : ⇑(∑ i ∈ s, f i) = ∑ i ∈ s, (f i : α → β) := map_sum coeFnAddHom f s theorem sum_apply {ι : Type*} (s : Finset ι) (f : ι → α →ᵇ β) (a : α) : (∑ i ∈ s, f i) a = ∑ i ∈ s, f i a := by simp end comm_add section LipschitzAdd /- In this section, if `β` is an `AddMonoid` whose addition operation is Lipschitz, then we show that the space of bounded continuous functions from `α` to `β` inherits a topological `AddMonoid` structure, by using pointwise operations and checking that they are compatible with the uniform distance. Implementation note: The material in this section could have been written for `LipschitzMul` and transported by `@[to_additive]`. We choose not to do this because this causes a few lemma names (for example, `coe_mul`) to conflict with later lemma names for normed rings; this is only a trivial inconvenience, but in any case there are no obvious applications of the multiplicative version. -/ variable [TopologicalSpace α] [PseudoMetricSpace β] [AddMonoid β] [LipschitzAdd β] variable (f g : α →ᵇ β) {x : α} {C : ℝ} instance instLipschitzAdd : LipschitzAdd (α →ᵇ β) where lipschitz_add := ⟨LipschitzAdd.C β, by have C_nonneg := (LipschitzAdd.C β).coe_nonneg rw [lipschitzWith_iff_dist_le_mul] rintro ⟨f₁, g₁⟩ ⟨f₂, g₂⟩ rw [dist_le (mul_nonneg C_nonneg dist_nonneg)] intro x refine le_trans (lipschitz_with_lipschitz_const_add ⟨f₁ x, g₁ x⟩ ⟨f₂ x, g₂ x⟩) ?_ gcongr apply max_le_max <;> exact dist_coe_le_dist x⟩ end LipschitzAdd section sub variable [TopologicalSpace α] variable {R : Type*} [PseudoMetricSpace R] [Sub R] [BoundedSub R] [ContinuousSub R] variable (f g : α →ᵇ R) /-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/ instance instSub : Sub (α →ᵇ R) where sub f g := { toFun := fun x ↦ (f x - g x), map_bounded' := sub_bounded_of_bounded_of_bounded f.map_bounded' g.map_bounded' } theorem sub_apply {x : α} : (f - g) x = f x - g x := rfl @[simp] theorem coe_sub : ⇑(f - g) = f - g := rfl end sub section casts variable [TopologicalSpace α] {β : Type*} [PseudoMetricSpace β] instance [NatCast β] : NatCast (α →ᵇ β) := ⟨fun n ↦ BoundedContinuousFunction.const _ n⟩ @[simp] theorem natCast_apply [NatCast β] (n : ℕ) (x : α) : (n : α →ᵇ β) x = n := rfl instance [IntCast β] : IntCast (α →ᵇ β) := ⟨fun m ↦ BoundedContinuousFunction.const _ m⟩ @[simp] theorem intCast_apply [IntCast β] (m : ℤ) (x : α) : (m : α →ᵇ β) x = m := rfl end casts instance instSemiring {R : Type*} [TopologicalSpace α] [PseudoMetricSpace R] [Semiring R] [BoundedMul R] [ContinuousMul R] [BoundedAdd R] [ContinuousAdd R] : Semiring (α →ᵇ R) := Injective.semiring _ DFunLike.coe_injective' rfl rfl (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) (fun _ _ ↦ rfl) (fun _ ↦ rfl) section IsBoundedSMul /-! ### `IsBoundedSMul` (in particular, topological module) structure In this section, if `β` is a metric space and a `𝕜`-module whose addition and scalar multiplication are compatible with the metric structure, then we show that the space of bounded continuous functions from `α` to `β` inherits a so-called `IsBoundedSMul` structure (in particular, a `ContinuousMul` structure, which is the mathlib formulation of being a topological module), by using pointwise operations and checking that they are compatible with the uniform distance. -/ variable {𝕜 : Type*} [PseudoMetricSpace 𝕜] [TopologicalSpace α] [PseudoMetricSpace β] section SMul variable [Zero 𝕜] [Zero β] [SMul 𝕜 β] [IsBoundedSMul 𝕜 β] instance instSMul : SMul 𝕜 (α →ᵇ β) where smul c f := { toContinuousMap := c • f.toContinuousMap map_bounded' := let ⟨b, hb⟩ := f.bounded ⟨dist c 0 * b, fun x y => by refine (dist_smul_pair c (f x) (f y)).trans ?_ gcongr apply hb⟩ } @[simp] theorem coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = fun x => c • f x := rfl theorem smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl instance instIsScalarTower {𝕜' : Type*} [PseudoMetricSpace 𝕜'] [Zero 𝕜'] [SMul 𝕜' β] [IsBoundedSMul 𝕜' β] [SMul 𝕜' 𝕜] [IsScalarTower 𝕜' 𝕜 β] : IsScalarTower 𝕜' 𝕜 (α →ᵇ β) where smul_assoc _ _ _ := ext fun _ ↦ smul_assoc .. instance instSMulCommClass {𝕜' : Type*} [PseudoMetricSpace 𝕜'] [Zero 𝕜'] [SMul 𝕜' β] [IsBoundedSMul 𝕜' β] [SMulCommClass 𝕜' 𝕜 β] : SMulCommClass 𝕜' 𝕜 (α →ᵇ β) where smul_comm _ _ _ := ext fun _ ↦ smul_comm .. instance instIsCentralScalar [SMul 𝕜ᵐᵒᵖ β] [IsCentralScalar 𝕜 β] : IsCentralScalar 𝕜 (α →ᵇ β) where op_smul_eq_smul _ _ := ext fun _ => op_smul_eq_smul _ _ instance instIsBoundedSMul : IsBoundedSMul 𝕜 (α →ᵇ β) where dist_smul_pair' c f₁ f₂ := by rw [dist_le (mul_nonneg dist_nonneg dist_nonneg)] intro x refine (dist_smul_pair c (f₁ x) (f₂ x)).trans ?_ gcongr apply dist_coe_le_dist dist_pair_smul' c₁ c₂ f := by rw [dist_le (by positivity)] intro x refine (dist_pair_smul c₁ c₂ (f x)).trans ?_ gcongr apply dist_coe_le_dist (g := 0) end SMul section MulAction variable [MonoidWithZero 𝕜] [Zero β] [MulAction 𝕜 β] [IsBoundedSMul 𝕜 β] instance instMulAction : MulAction 𝕜 (α →ᵇ β) := DFunLike.coe_injective.mulAction _ coe_smul end MulAction section DistribMulAction variable [MonoidWithZero 𝕜] [AddMonoid β] [DistribMulAction 𝕜 β] [IsBoundedSMul 𝕜 β] variable [BoundedAdd β] [ContinuousAdd β] instance instDistribMulAction : DistribMulAction 𝕜 (α →ᵇ β) := DFunLike.coe_injective.distribMulAction ⟨⟨_, coe_zero⟩, coe_add⟩ coe_smul end DistribMulAction section Module variable [Semiring 𝕜] [AddCommMonoid β] [Module 𝕜 β] [IsBoundedSMul 𝕜 β] variable {f g : α →ᵇ β} {x : α} {C : ℝ} variable [BoundedAdd β] [ContinuousAdd β] instance instModule : Module 𝕜 (α →ᵇ β) := DFunLike.coe_injective.module _ ⟨⟨_, coe_zero⟩, coe_add⟩ coe_smul variable (𝕜) /-- The evaluation at a point, as a continuous linear map from `α →ᵇ β` to `β`. -/ @[simps] def evalCLM (x : α) : (α →ᵇ β) →L[𝕜] β where toFun f := f x map_add' _ _ := add_apply _ _ _ map_smul' _ _ := smul_apply _ _ _ variable (α β) /-- The linear map forgetting that a bounded continuous function is bounded. -/ @[simps] def toContinuousMapLinearMap : (α →ᵇ β) →ₗ[𝕜] C(α, β) where toFun := toContinuousMap map_smul' _ _ := rfl map_add' _ _ := rfl end Module end IsBoundedSMul theorem NNReal.upper_bound {α : Type*} [TopologicalSpace α] (f : α →ᵇ ℝ≥0) (x : α) : f x ≤ nndist f 0 := by have key : nndist (f x) ((0 : α →ᵇ ℝ≥0) x) ≤ nndist f 0 := @dist_coe_le_dist α ℝ≥0 _ _ f 0 x simp only [coe_zero, Pi.zero_apply] at key rwa [NNReal.nndist_zero_eq_val' (f x)] at key end BoundedContinuousFunction
interactiveUnfold.lean
/- Copyright (c) 2024 Jovan Gerbscheid. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jovan Gerbscheid -/ import Mathlib /-! The `unfold?` tactic is used interactively, so it is tricky to test directly. In order to test it, we use the `#unfold?` command. -/ /-- info: Unfolds for 0: · ↑0 · ↑0 · Rat.ofInt ↑0 -/ #guard_msgs in #unfold? (0 : Rat) /-- info: Unfolds for -42: · Int.negOfNat 42 · Int.negSucc 41 -/ #guard_msgs in #unfold? -42 -- Rat.mk is private, so it doesn't show up here /-- info: Unfolds for 42: · ↑42 · ↑42 · Rat.ofInt ↑42 -/ #guard_msgs in #unfold? (42 : ℚ) /-- info: Unfolds for 1 + 1: · Nat.add 1 1 · 2 -/ #guard_msgs in #unfold? 1 + 1 /-- info: Unfolds for 5 / 3: · Nat.div 5 3 · 1 -/ #guard_msgs in #unfold? 5 / 3 /-- info: Unfolds for 1 + 1: · Ordinal.type (Sum.Lex EmptyRelation EmptyRelation) · ⟦{ α := PUnit.{u_1 + 1} ⊕ PUnit.{u_1 + 1}, r := Sum.Lex EmptyRelation EmptyRelation, wo := ⋯ }⟧ · Quot.mk ⇑Ordinal.isEquivalent { α := PUnit.{u_1 + 1} ⊕ PUnit.{u_1 + 1}, r := Sum.Lex EmptyRelation EmptyRelation, wo := ⋯ } -/ #guard_msgs in #unfold? (1 : Ordinal) + 1 /-- info: Unfolds for 3 ∈ {1, 2, 3}: · {1, 2, 3}.Mem 3 · {1, 2, 3} 3 · Set.insert 1 {2, 3} 3 · {b | b = 1 ∨ b ∈ {2, 3}} 3 · 3 = 1 ∨ 3 ∈ {2, 3} -/ #guard_msgs in #unfold? 3 ∈ ({1, 2, 3} : Set ℕ) /-- info: Unfolds for Function.Injective fun x => x: · ∀ ⦃a₁ a₂ : ℕ⦄, (fun x => x) a₁ = (fun x => x) a₂ → a₁ = a₂ -/ #guard_msgs in #unfold? Function.Injective (fun x : Nat => x) variable (A B : Set Nat) (n : Nat) /-- info: Unfolds for 1 ∈ A ∪ B: · (A ∪ B).Mem 1 · (A ∪ B) 1 · A.union B 1 · {a | a ∈ A ∨ a ∈ B} 1 · 1 ∈ A ∨ 1 ∈ B -/ #guard_msgs in #unfold? 1 ∈ A ∪ B /-- info: Unfolds for (fun x => x) (1 + 1): · 1 + 1 · Nat.add 1 1 · 2 -/ #guard_msgs in #unfold? (fun x => x) (1 + 1) /-- info: Unfolds for fun x => id x: · id · fun a => a -/ #guard_msgs in #unfold? fun x => id x
Hom.lean
/- Copyright (c) 2022 Alex J. Best, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Yaël Dillies -/ import Mathlib.Algebra.Order.Archimedean.Basic import Mathlib.Algebra.Order.Hom.Ring /-! ### Uniqueness of ring homomorphisms to archimedean fields. There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. Reciprocally, such an ordered ring homomorphism exists when the codomain is further conditionally complete. -/ assert_not_exists Finset variable {α β : Type*} /-- There is at most one ordered ring homomorphism from a linear ordered field to an archimedean linear ordered field. -/ instance OrderRingHom.subsingleton [Field α] [LinearOrder α] [Field β] [LinearOrder β] [IsStrictOrderedRing β] [Archimedean β] : Subsingleton (α →+*o β) := ⟨fun f g => by ext x by_contra! h' : f x ≠ g x wlog h : f x < g x with h₂ · exact h₂ g f x (Ne.symm h') (h'.lt_or_gt.resolve_left h) obtain ⟨q, hf, hg⟩ := exists_rat_btwn h rw [← map_ratCast f] at hf rw [← map_ratCast g] at hg exact (lt_asymm ((OrderHomClass.mono g).reflect_lt hg) <| (OrderHomClass.mono f).reflect_lt hf).elim⟩ /-- There is at most one ordered ring isomorphism between a linear ordered field and an archimedean linear ordered field. -/ instance OrderRingIso.subsingleton_right [Field α] [LinearOrder α] [Field β] [LinearOrder β] [IsStrictOrderedRing β] [Archimedean β] : Subsingleton (α ≃+*o β) := OrderRingIso.toOrderRingHom_injective.subsingleton /-- There is at most one ordered ring isomorphism between an archimedean linear ordered field and a linear ordered field. -/ instance OrderRingIso.subsingleton_left [Field α] [LinearOrder α] [IsStrictOrderedRing α] [Archimedean α] [Field β] [LinearOrder β] : Subsingleton (α ≃+*o β) := OrderRingIso.symm_bijective.injective.subsingleton
AtomM.lean
/- Copyright (c) 2023 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Init import Lean.Meta.Tactic.Simp.Types import Qq /-! # A monad for tracking and deduplicating atoms This monad is used by tactics like `ring` and `abel` to keep uninterpreted atoms in a consistent order, and also to allow unifying atoms up to a specified transparency mode. Note: this can become very expensive because it is using `isDefEq`. For performance reasons, consider whether `Lean.Meta.Canonicalizer.canon` can be used instead. After canonicalizing, a `HashMap Expr Nat` suffices to keep track of previously seen atoms, and is much faster as it uses `Expr` equality rather than `isDefEq`. -/ namespace Mathlib.Tactic open Lean Meta /-- The context (read-only state) of the `AtomM` monad. -/ structure AtomM.Context where /-- The reducibility setting for definitional equality of atoms -/ red : TransparencyMode /-- A simplification to apply to atomic expressions when they are encountered, before interning them in the atom list. -/ evalAtom : Expr → MetaM Simp.Result := fun e ↦ pure { expr := e } deriving Inhabited /-- The mutable state of the `AtomM` monad. -/ structure AtomM.State where /-- The list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ atoms : Array Expr := #[] /-- The monad that `ring` works in. This is only used for collecting atoms. -/ abbrev AtomM := ReaderT AtomM.Context <| StateRefT AtomM.State MetaM /-- Run a computation in the `AtomM` monad. -/ def AtomM.run {α : Type} (red : TransparencyMode) (m : AtomM α) (evalAtom : Expr → MetaM Simp.Result := fun e ↦ pure { expr := e }) : MetaM α := (m { red, evalAtom }).run' {} /-- A safe version of `isDefEq` that doesn't throw errors. We use it to avoid "unknown free variable '_fvar.102937'" errors when there may be out-of-scope free variables. TODO: don't catch any other errors -/ def isDefEqSafe (a b : Expr) : MetaM Bool := try isDefEq a b catch _ => pure false /-- If an atomic expression has already been encountered, get the index and the stored form of the atom (which will be defeq at the specified transparency, but not necessarily syntactically equal). If the atomic expression has *not* already been encountered, store it in the list of atoms, and return the new index (and the stored form of the atom, which will be itself). In a normalizing tactic, the expression returned by `addAtom` should be considered the normal form. -/ def AtomM.addAtom (e : Expr) : AtomM (Nat × Expr) := do let c ← get for h : i in [:c.atoms.size] do if ← withTransparency (← read).red <| isDefEqSafe e c.atoms[i] then return (i, c.atoms[i]) modifyGet fun c ↦ ((c.atoms.size, e), { c with atoms := c.atoms.push e }) open Qq in /-- If an atomic expression has already been encountered, get the index and the stored form of the atom (which will be defeq at the specified transparency, but not necessarily syntactically equal). If the atomic expression has *not* already been encountered, store it in the list of atoms, and return the new index (and the stored form of the atom, which will be itself). In a normalizing tactic, the expression returned by `addAtomQ` should be considered the normal form. This is a strongly-typed version of `AtomM.addAtom` for code using `Qq`. -/ def AtomM.addAtomQ {u : Level} {α : Q(Type u)} (e : Q($α)) : AtomM (Nat × {e' : Q($α) // $e =Q $e'}) := do let (n, e') ← AtomM.addAtom e return (n, ⟨e', ⟨⟩⟩) end Mathlib.Tactic
Circuit.lean
/- Copyright (c) 2025 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Data.Matroid.Closure /-! # Matroid IsCircuits A 'Circuit' of a matroid `M` is a minimal set `C` that is dependent in `M`. A matroid is determined by its set of circuits, and often the circuits offer a more compact description of a matroid than the collection of independent sets or bases. In matroids arising from graphs, circuits correspond to graphical cycles. # Main Declarations * `Matroid.IsCircuit M C` means that `C` is minimally dependent in `M`. * For an `Indep`endent set `I` whose closure contains an element `e ∉ I`, `Matroid.fundCircuit M e I` is the unique circuit contained in `insert e I`. * `Matroid.Indep.fundCircuit_isCircuit` states that `Matroid.fundCircuit M e I` is indeed a circuit. * `Matroid.IsCircuit.eq_fundCircuit_of_subset` states that `Matroid.fundCircuit M e I` is the unique circuit contained in `insert e I`. * `Matroid.dep_iff_superset_isCircuit` states that the dependent subsets of the ground set are precisely those that contain a circuit. * `Matroid.ext_isCircuit` : a matroid is determined by its collection of circuits. * `Matroid.IsCircuit.strong_multi_elimination` : the strong circuit elimination rule for an infinite collection of circuits. * `Matroid.IsCircuit.strong_elimination` : the strong circuit elimination rule for two circuits. * `Matroid.finitary_iff_forall_isCircuit_finite` : finitary matroids are precisely those whose circuits are all finite. * `Matroid.IsCocircuit M C` means that `C` is minimally dependent in `M✶`, or equivalently that `M.E \ C` is a hyperplane of `M`. * `Matroid.fundCocircuit M B e` is the unique cocircuit that intersects the base `B` precisely in the element `e`. * `Matroid.IsBase.mem_fundCocircuit_iff_mem_fundCircuit` : `e` is in the fundamental circuit for `B` and `f` iff `f` is in the fundamental cocircuit for `B` and `e`. # Implementation Details Since `Matroid.fundCircuit M e I` is only sensible if `I` is independent and `e ∈ M.closure I \ I`, to avoid hypotheses being explicitly included in the definition, junk values need to be chosen if either hypothesis fails. The definition is chosen so that the junk values satisfy `M.fundCircuit e I = {e}` for `e ∈ I` or `e ∉ M.E` and `M.fundCircuit e I = insert e I` if `e ∈ M.E \ M.closure I`. These make the useful statement `e ∈ M.fundCircuit e I ⊆ insert e I` true unconditionally. -/ variable {α : Type*} {M : Matroid α} {C C' I X Y R : Set α} {e f x y : α} open Set namespace Matroid /-- `M.IsCircuit C` means that `C` is a minimal dependent set in `M`. -/ def IsCircuit (M : Matroid α) := Minimal M.Dep @[deprecated (since := "2025-02-14")] alias Circuit := IsCircuit lemma isCircuit_def : M.IsCircuit C ↔ Minimal M.Dep C := Iff.rfl lemma IsCircuit.dep (hC : M.IsCircuit C) : M.Dep C := hC.prop lemma IsCircuit.not_indep (hC : M.IsCircuit C) : ¬ M.Indep C := hC.dep.not_indep lemma IsCircuit.minimal (hC : M.IsCircuit C) : Minimal M.Dep C := hC @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsCircuit.subset_ground (hC : M.IsCircuit C) : C ⊆ M.E := hC.dep.subset_ground lemma IsCircuit.nonempty (hC : M.IsCircuit C) : C.Nonempty := hC.dep.nonempty lemma empty_not_isCircuit (M : Matroid α) : ¬M.IsCircuit ∅ := fun h ↦ by simpa using h.nonempty lemma isCircuit_iff : M.IsCircuit C ↔ M.Dep C ∧ ∀ ⦃D⦄, M.Dep D → D ⊆ C → D = C := by simp_rw [isCircuit_def, minimal_subset_iff, eq_comm (a := C)] lemma IsCircuit.ssubset_indep (hC : M.IsCircuit C) (hXC : X ⊂ C) : M.Indep X := by rw [← not_dep_iff (hXC.subset.trans hC.subset_ground)] exact fun h ↦ hXC.ne ((isCircuit_iff.1 hC).2 h hXC.subset) lemma IsCircuit.minimal_not_indep (hC : M.IsCircuit C) : Minimal (¬ M.Indep ·) C := by simp_rw [minimal_iff_forall_ssubset, and_iff_right hC.not_indep, not_not] exact fun ⦃t⦄ a ↦ ssubset_indep hC a lemma isCircuit_iff_minimal_not_indep (hCE : C ⊆ M.E) : M.IsCircuit C ↔ Minimal (¬ M.Indep ·) C := ⟨IsCircuit.minimal_not_indep, fun h ↦ ⟨(not_indep_iff hCE).1 h.prop, fun _ hJ hJC ↦ (h.eq_of_superset hJ.not_indep hJC).le⟩⟩ lemma IsCircuit.diff_singleton_indep (hC : M.IsCircuit C) (he : e ∈ C) : M.Indep (C \ {e}) := hC.ssubset_indep (diff_singleton_ssubset.2 he) lemma isCircuit_iff_forall_ssubset : M.IsCircuit C ↔ M.Dep C ∧ ∀ ⦃I⦄, I ⊂ C → M.Indep I := by rw [IsCircuit, minimal_iff_forall_ssubset, and_congr_right_iff] exact fun h ↦ ⟨fun h' I hIC ↦ ((not_dep_iff (hIC.subset.trans h.subset_ground)).1 (h' hIC)), fun h I hIC ↦ (h hIC).not_dep⟩ lemma isCircuit_antichain : IsAntichain (· ⊆ ·) (setOf M.IsCircuit) := fun _ hC _ hC' hne hss ↦ hne <| (IsCircuit.minimal hC').eq_of_subset hC.dep hss lemma IsCircuit.eq_of_not_indep_subset (hC : M.IsCircuit C) (hX : ¬ M.Indep X) (hXC : X ⊆ C) : X = C := eq_of_le_of_not_lt hXC (hX ∘ hC.ssubset_indep) lemma IsCircuit.eq_of_dep_subset (hC : M.IsCircuit C) (hX : M.Dep X) (hXC : X ⊆ C) : X = C := hC.eq_of_not_indep_subset hX.not_indep hXC lemma IsCircuit.not_ssubset (hC : M.IsCircuit C) (hC' : M.IsCircuit C') : ¬C' ⊂ C := fun h' ↦ h'.ne (hC.eq_of_dep_subset hC'.dep h'.subset) lemma IsCircuit.eq_of_subset_isCircuit (hC : M.IsCircuit C) (hC' : M.IsCircuit C') (h : C ⊆ C') : C = C' := hC'.eq_of_dep_subset hC.dep h lemma IsCircuit.eq_of_superset_isCircuit (hC : M.IsCircuit C) (hC' : M.IsCircuit C') (h : C' ⊆ C) : C = C' := (hC'.eq_of_subset_isCircuit hC h).symm lemma isCircuit_iff_dep_forall_diff_singleton_indep : M.IsCircuit C ↔ M.Dep C ∧ ∀ e ∈ C, M.Indep (C \ {e}) := by wlog hCE : C ⊆ M.E · exact iff_of_false (hCE ∘ IsCircuit.subset_ground) (fun h ↦ hCE h.1.subset_ground) simp [isCircuit_iff_minimal_not_indep hCE, ← not_indep_iff hCE, minimal_iff_forall_diff_singleton (P := (¬ M.Indep ·)) (fun _ _ hY hYX hX ↦ hY <| hX.subset hYX)] /-! ### Independence and bases -/ lemma Indep.insert_isCircuit_of_forall (hI : M.Indep I) (heI : e ∉ I) (he : e ∈ M.closure I) (h : ∀ f ∈ I, e ∉ M.closure (I \ {f})) : M.IsCircuit (insert e I) := by rw [isCircuit_iff_dep_forall_diff_singleton_indep, hI.insert_dep_iff, and_iff_right ⟨he, heI⟩] rintro f (rfl | hfI) · simpa [heI] rw [← insert_diff_singleton_comm (by rintro rfl; contradiction), (hI.diff _).insert_indep_iff_of_notMem (by simp [heI])] exact ⟨mem_ground_of_mem_closure he, h f hfI⟩ lemma Indep.insert_isCircuit_of_forall_of_nontrivial (hI : M.Indep I) (hInt : I.Nontrivial) (he : e ∈ M.closure I) (h : ∀ f ∈ I, e ∉ M.closure (I \ {f})) : M.IsCircuit (insert e I) := by refine hI.insert_isCircuit_of_forall (fun heI ↦ ?_) he h obtain ⟨f, hf, hne⟩ := hInt.exists_ne e exact h f hf (mem_closure_of_mem' _ (by simp [heI, hne.symm])) lemma IsCircuit.diff_singleton_isBasis (hC : M.IsCircuit C) (he : e ∈ C) : M.IsBasis (C \ {e}) C := by nth_rw 2 [← insert_eq_of_mem he] rw [← insert_diff_singleton, (hC.diff_singleton_indep he).isBasis_insert_iff, insert_diff_singleton, insert_eq_of_mem he] exact Or.inl hC.dep lemma IsCircuit.isBasis_iff_eq_diff_singleton (hC : M.IsCircuit C) : M.IsBasis I C ↔ ∃ e ∈ C, I = C \ {e} := by refine ⟨fun h ↦ ?_, ?_⟩ · obtain ⟨e, he⟩ := exists_of_ssubset (h.subset.ssubset_of_ne (by rintro rfl; exact hC.dep.not_indep h.indep)) exact ⟨e, he.1, h.eq_of_subset_indep (hC.diff_singleton_indep he.1) (subset_diff_singleton h.subset he.2) diff_subset⟩ rintro ⟨e, he, rfl⟩ exact hC.diff_singleton_isBasis he lemma IsCircuit.isBasis_iff_insert_eq (hC : M.IsCircuit C) : M.IsBasis I C ↔ ∃ e ∈ C \ I, C = insert e I := by rw [hC.isBasis_iff_eq_diff_singleton] refine ⟨fun ⟨e, he, hI⟩ ↦ ⟨e, ⟨he, fun heI ↦ (hI.subset heI).2 rfl⟩, ?_⟩, fun ⟨e, he, hC⟩ ↦ ⟨e, he.1, ?_⟩⟩ · rw [hI, insert_diff_singleton, insert_eq_of_mem he] rw [hC, insert_diff_self_of_notMem he.2] /-! ### Restriction -/ lemma IsCircuit.isCircuit_restrict_of_subset (hC : M.IsCircuit C) (hCR : C ⊆ R) : (M ↾ R).IsCircuit C := by simp_rw [isCircuit_iff, restrict_dep_iff, dep_iff, and_imp] at * exact ⟨⟨hC.1.1, hCR⟩, fun I hI _ hIC ↦ hC.2 hI (hIC.trans hC.1.2) hIC⟩ lemma restrict_isCircuit_iff (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).IsCircuit C ↔ M.IsCircuit C ∧ C ⊆ R := by refine ⟨?_, fun h ↦ h.1.isCircuit_restrict_of_subset h.2⟩ simp_rw [isCircuit_iff, restrict_dep_iff, and_imp, dep_iff] exact fun hC hCR h ↦ ⟨⟨⟨hC,hCR.trans hR⟩,fun I hI hIC ↦ h hI.1 (hIC.trans hCR) hIC⟩,hCR⟩ /-! ### Fundamental IsCircuits -/ /-- For an independent set `I` and some `e ∈ M.closure I \ I`, `M.fundCircuit e I` is the unique circuit contained in `insert e I`. For the fact that this is a circuit, see `Matroid.Indep.fundCircuit_isCircuit`, and the fact that it is unique, see `Matroid.IsCircuit.eq_fundCircuit_of_subset`. Has the junk value `{e}` if `e ∈ I` or `e ∉ M.E`, and `insert e I` if `e ∈ M.E \ M.closure I`. -/ def fundCircuit (M : Matroid α) (e : α) (I : Set α) : Set α := insert e (I ∩ ⋂₀ {J | J ⊆ I ∧ M.closure {e} ⊆ M.closure J}) lemma fundCircuit_eq_sInter (he : e ∈ M.closure I) : M.fundCircuit e I = insert e (⋂₀ {J | J ⊆ I ∧ e ∈ M.closure J}) := by rw [fundCircuit] simp_rw [closure_subset_closure_iff_subset_closure (show {e} ⊆ M.E by simpa using mem_ground_of_mem_closure he), singleton_subset_iff] rw [inter_eq_self_of_subset_right (sInter_subset_of_mem (by simpa))] lemma fundCircuit_subset_insert (M : Matroid α) (e : α) (I : Set α) : M.fundCircuit e I ⊆ insert e I := insert_subset_insert inter_subset_left lemma fundCircuit_subset_ground (he : e ∈ M.E) (hI : I ⊆ M.E := by aesop_mat) : M.fundCircuit e I ⊆ M.E := (M.fundCircuit_subset_insert e I).trans (insert_subset he hI) lemma mem_fundCircuit (M : Matroid α) (e : α) (I : Set α) : e ∈ fundCircuit M e I := mem_insert .. lemma fundCircuit_diff_eq_inter (M : Matroid α) (heI : e ∉ I) : (M.fundCircuit e I) \ {e} = (M.fundCircuit e I) ∩ I := (subset_inter diff_subset (by simp [fundCircuit_subset_insert])).antisymm (subset_diff_singleton inter_subset_left (by simp [heI])) /-- The fundamental isCircuit of `e` and `X` has the junk value `{e}` if `e ∈ X` -/ lemma fundCircuit_eq_of_mem (heX : e ∈ X) : M.fundCircuit e X = {e} := by suffices h : ∀ a ∈ X, (∀ t ⊆ X, M.closure {e} ⊆ M.closure t → a ∈ t) → a = e by simpa [subset_antisymm_iff, fundCircuit] exact fun b hbX h ↦ h _ (singleton_subset_iff.2 heX) Subset.rfl lemma fundCircuit_eq_of_notMem_ground (heX : e ∉ M.E) : M.fundCircuit e X = {e} := by suffices h : ∀ a ∈ X, (∀ t ⊆ X, M.closure {e} ⊆ M.closure t → a ∈ t) → a = e by simpa [subset_antisymm_iff, fundCircuit] simp_rw [← M.closure_inter_ground {e}, singleton_inter_eq_empty.2 heX] exact fun a haX h ↦ by simpa using h ∅ (empty_subset X) rfl.subset @[deprecated (since := "2025-05-23")] alias fundCircuit_eq_of_not_mem_ground := fundCircuit_eq_of_notMem_ground lemma Indep.fundCircuit_isCircuit (hI : M.Indep I) (hecl : e ∈ M.closure I) (heI : e ∉ I) : M.IsCircuit (M.fundCircuit e I) := by have aux : ⋂₀ {J | J ⊆ I ∧ e ∈ M.closure J} ⊆ I := sInter_subset_of_mem (by simpa) rw [fundCircuit_eq_sInter hecl] refine (hI.subset aux).insert_isCircuit_of_forall ?_ ?_ ?_ · simp [show ∃ x ⊆ I, e ∈ M.closure x ∧ e ∉ x from ⟨I, by simp [hecl, heI]⟩] · rw [hI.closure_sInter_eq_biInter_closure_of_forall_subset ⟨I, by simpa⟩ (by simp +contextual)] simp simp only [mem_sInter, mem_setOf_eq, and_imp] exact fun f hf hecl ↦ (hf _ (diff_subset.trans aux) hecl).2 rfl lemma Indep.mem_fundCircuit_iff (hI : M.Indep I) (hecl : e ∈ M.closure I) (heI : e ∉ I) : x ∈ M.fundCircuit e I ↔ M.Indep (insert e I \ {x}) := by obtain rfl | hne := eq_or_ne x e · simp [hI.diff, mem_fundCircuit] suffices (∀ t ⊆ I, e ∈ M.closure t → x ∈ t) ↔ e ∉ M.closure (I \ {x}) by simpa [fundCircuit_eq_sInter hecl, hne, ← insert_diff_singleton_comm hne.symm, (hI.diff _).insert_indep_iff, mem_ground_of_mem_closure hecl, heI] refine ⟨fun h hecl ↦ (h _ diff_subset hecl).2 rfl, fun h J hJ heJ ↦ by_contra fun hxJ ↦ h ?_⟩ exact M.closure_subset_closure (subset_diff_singleton hJ hxJ) heJ lemma IsBase.fundCircuit_isCircuit {B : Set α} (hB : M.IsBase B) (hxE : x ∈ M.E) (hxB : x ∉ B) : M.IsCircuit (M.fundCircuit x B) := hB.indep.fundCircuit_isCircuit (by rwa [hB.closure_eq]) hxB /-- For `I` independent, `M.fundCircuit e I` is the only circuit contained in `insert e I`. -/ lemma IsCircuit.eq_fundCircuit_of_subset (hC : M.IsCircuit C) (hI : M.Indep I) (hCs : C ⊆ insert e I) : C = M.fundCircuit e I := by obtain hCI | ⟨heC, hCeI⟩ := subset_insert_iff.1 hCs · exact (hC.not_indep (hI.subset hCI)).elim suffices hss : M.fundCircuit e I ⊆ C by refine hC.eq_of_superset_isCircuit (hI.fundCircuit_isCircuit ?_ fun heI ↦ ?_) hss · rw [hI.mem_closure_iff] exact .inl (hC.dep.superset hCs (insert_subset (hC.subset_ground heC) hI.subset_ground)) exact hC.not_indep (hI.subset (hCs.trans (by simp [heI]))) have heCcl := (hC.diff_singleton_isBasis heC).subset_closure heC have heI : e ∈ M.closure I := M.closure_subset_closure hCeI heCcl rw [fundCircuit_eq_sInter heI] refine insert_subset heC <| (sInter_subset_of_mem (t := C \ {e}) ?_).trans diff_subset exact ⟨hCeI, heCcl⟩ lemma fundCircuit_restrict {R : Set α} (hIR : I ⊆ R) (heR : e ∈ R) (hR : R ⊆ M.E) : (M ↾ R).fundCircuit e I = M.fundCircuit e I := by simp_rw [fundCircuit, M.restrict_closure_eq (R := R) (X := {e}) (by simpa)] apply subset_antisymm · gcongr 5 with J hJI; intro heJ simp only [restrict_closure_eq'] refine (inter_subset_inter_left _ ?_).trans subset_union_left rwa [inter_eq_self_of_subset_left (hJI.trans hIR)] gcongr 5 with J hJI; intro heJ refine closure_subset_closure_of_subset_closure ?_ rw [restrict_closure_eq _ (hJI.trans hIR) hR] at heJ simp only [subset_inter_iff, inter_subset_right, and_true] at heJ exact subset_trans (by simpa [M.mem_closure_of_mem' (mem_singleton e) (hR heR)]) heJ @[simp] lemma fundCircuit_restrict_univ (M : Matroid α) : (M ↾ univ).fundCircuit e I = M.fundCircuit e I := by have aux (A B) : M.closure A ⊆ B ∪ univ \ M.E ↔ M.closure A ⊆ B := by refine ⟨fun h ↦ ?_, fun h ↦ h.trans subset_union_left⟩ refine (subset_inter h (M.closure_subset_ground A)).trans ?_ simp [union_inter_distrib_right] simp [fundCircuit, aux] /-! ### Dependence -/ lemma Dep.exists_isCircuit_subset (hX : M.Dep X) : ∃ C, C ⊆ X ∧ M.IsCircuit C := by obtain ⟨I, hI⟩ := M.exists_isBasis X obtain ⟨e, heX, heI⟩ := exists_of_ssubset (hI.subset.ssubset_of_ne (by rintro rfl; exact hI.indep.not_dep hX)) exact ⟨M.fundCircuit e I, (M.fundCircuit_subset_insert e I).trans (insert_subset heX hI.subset), hI.indep.fundCircuit_isCircuit (hI.subset_closure heX) heI⟩ lemma dep_iff_superset_isCircuit (hX : X ⊆ M.E := by aesop_mat) : M.Dep X ↔ ∃ C, C ⊆ X ∧ M.IsCircuit C := ⟨Dep.exists_isCircuit_subset, fun ⟨C, hCX, hC⟩ ↦ hC.dep.superset hCX⟩ /-- A version of `Matroid.dep_iff_superset_isCircuit` that has the supportedness hypothesis as part of the equivalence, rather than a hypothesis. -/ lemma dep_iff_superset_isCircuit' : M.Dep X ↔ (∃ C, C ⊆ X ∧ M.IsCircuit C) ∧ X ⊆ M.E := ⟨fun h ↦ ⟨h.exists_isCircuit_subset, h.subset_ground⟩, fun ⟨⟨C, hCX, hC⟩, h⟩ ↦ hC.dep.superset hCX⟩ /-- A version of `Matroid.indep_iff_forall_subset_not_isCircuit` that has the supportedness hypothesis as part of the equivalence, rather than a hypothesis. -/ lemma indep_iff_forall_subset_not_isCircuit' : M.Indep I ↔ (∀ C, C ⊆ I → ¬M.IsCircuit C) ∧ I ⊆ M.E := by simp_rw [indep_iff_not_dep, dep_iff_superset_isCircuit'] aesop lemma indep_iff_forall_subset_not_isCircuit (hI : I ⊆ M.E := by aesop_mat) : M.Indep I ↔ ∀ C, C ⊆ I → ¬M.IsCircuit C := by rw [indep_iff_forall_subset_not_isCircuit', and_iff_left hI] /-! ### Closure -/ lemma IsCircuit.closure_diff_singleton_eq (hC : M.IsCircuit C) (e : α) : M.closure (C \ {e}) = M.closure C := (em (e ∈ C)).elim (fun he ↦ by rw [(hC.diff_singleton_isBasis he).closure_eq_closure]) (fun he ↦ by rw [diff_singleton_eq_self he]) lemma IsCircuit.subset_closure_diff_singleton (hC : M.IsCircuit C) (e : α) : C ⊆ M.closure (C \ {e}) := by rw [hC.closure_diff_singleton_eq] exact M.subset_closure _ hC.subset_ground lemma IsCircuit.mem_closure_diff_singleton_of_mem (hC : M.IsCircuit C) (heC : e ∈ C) : e ∈ M.closure (C \ {e}) := hC.subset_closure_diff_singleton e heC lemma exists_isCircuit_of_mem_closure (he : e ∈ M.closure X) (heX : e ∉ X) : ∃ C ⊆ insert e X, M.IsCircuit C ∧ e ∈ C := let ⟨I, hI⟩ := M.exists_isBasis' X ⟨_, (fundCircuit_subset_insert ..).trans (insert_subset_insert hI.subset), hI.indep.fundCircuit_isCircuit (by rwa [hI.closure_eq_closure]) (notMem_subset hI.subset heX), M.mem_fundCircuit e I⟩ lemma mem_closure_iff_exists_isCircuit (he : e ∉ X) : e ∈ M.closure X ↔ ∃ C ⊆ insert e X, M.IsCircuit C ∧ e ∈ C := ⟨fun h ↦ exists_isCircuit_of_mem_closure h he, fun ⟨C, hCX, hC, heC⟩ ↦ mem_of_mem_of_subset (hC.mem_closure_diff_singleton_of_mem heC) (M.closure_subset_closure (by simpa))⟩ /-! ### Extensionality -/ lemma ext_isCircuit {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h : ∀ ⦃C⦄, C ⊆ M₁.E → (M₁.IsCircuit C ↔ M₂.IsCircuit C)) : M₁ = M₂ := by have h' {C} : M₁.IsCircuit C ↔ M₂.IsCircuit C := (em (C ⊆ M₁.E)).elim (h (C := C)) (fun hC ↦ iff_of_false (mt IsCircuit.subset_ground hC) (mt IsCircuit.subset_ground fun hss ↦ hC (hss.trans_eq hE.symm))) refine ext_indep hE fun I hI ↦ ?_ simp_rw [indep_iff_forall_subset_not_isCircuit hI, h', indep_iff_forall_subset_not_isCircuit (hI.trans_eq hE)] /-- A stronger version of `Matroid.ext_isCircuit`: two matroids on the same ground set are equal if no circuit of one is independent in the other. -/ lemma ext_isCircuit_not_indep {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (h₁ : ∀ C, M₁.IsCircuit C → ¬ M₂.Indep C) (h₂ : ∀ C, M₂.IsCircuit C → ¬ M₁.Indep C) : M₁ = M₂ := by refine ext_isCircuit hE fun C hCE ↦ ⟨fun hC ↦ ?_, fun hC ↦ ?_⟩ · obtain ⟨C', hC'C, hC'⟩ := ((not_indep_iff (by rwa [← hE])).1 (h₁ C hC)).exists_isCircuit_subset rwa [← hC.eq_of_not_indep_subset (h₂ C' hC') hC'C] obtain ⟨C', hC'C, hC'⟩ := ((not_indep_iff hCE).1 (h₂ C hC)).exists_isCircuit_subset rwa [← hC.eq_of_not_indep_subset (h₁ C' hC') hC'C] lemma ext_iff_isCircuit {M₁ M₂ : Matroid α} : M₁ = M₂ ↔ M₁.E = M₂.E ∧ ∀ C, M₁.IsCircuit C ↔ M₂.IsCircuit C := ⟨fun h ↦ by simp [h], fun h ↦ ext_isCircuit h.1 fun C hC ↦ h.2 (C := C)⟩ section Elimination /-! ### Circuit Elimination -/ variable {ι : Type*} {J C₀ C₁ C₂ : Set α} /-- A version of `Matroid.IsCircuit.strong_multi_elimination` that is phrased using insertion. -/ lemma IsCircuit.strong_multi_elimination_insert (x : ι → α) (I : ι → Set α) (z : α) (hxI : ∀ i, x i ∉ I i) (hC : ∀ i, M.IsCircuit (insert (x i) (I i))) (hJx : M.IsCircuit (J ∪ range x)) (hzJ : z ∈ J) (hzI : ∀ i, z ∉ I i) : ∃ C' ⊆ J ∪ ⋃ i, I i, M.IsCircuit C' ∧ z ∈ C' := by -- we may assume that `ι` is nonempty, and it suffices to show that -- `z` is spanned by the union of the `I` and `J \ {z}`. obtain hι | hι := isEmpty_or_nonempty ι · exact ⟨J, by simp, by simpa [range_eq_empty] using hJx, hzJ⟩ suffices hcl : z ∈ M.closure ((⋃ i, I i) ∪ (J \ {z})) by rw [mem_closure_iff_exists_isCircuit (by simp [hzI])] at hcl obtain ⟨C', hC'ss, hC', hzC'⟩ := hcl refine ⟨C', ?_, hC', hzC'⟩ rwa [union_comm, ← insert_union, insert_diff_singleton, insert_eq_of_mem hzJ] at hC'ss have hC' (i) : M.closure (I i) = M.closure (insert (x i) (I i)) := by simpa [diff_singleton_eq_self (hxI _)] using (hC i).closure_diff_singleton_eq (x i) -- This is true because each `I i` spans `x i` and `(range x) ∪ (J \ {z})` spans `z`. rw [closure_union_congr_left <| closure_iUnion_congr _ _ hC', iUnion_insert_eq_range_union_iUnion, union_right_comm] refine mem_of_mem_of_subset (hJx.mem_closure_diff_singleton_of_mem (.inl hzJ)) (M.closure_subset_closure (subset_trans ?_ subset_union_left)) rw [union_diff_distrib, union_comm] exact union_subset_union_left _ diff_subset /-- A generalization of the strong circuit elimination axiom `Matroid.IsCircuit.strong_elimination` to an infinite collection of circuits. It states that, given a circuit `C₀`, a arbitrary collection `C : ι → Set α` of circuits, an element `x i` of `C₀ ∩ C i` for each `i`, and an element `z ∈ C₀` outside all the `C i`, the union of `C₀` and the `C i` contains a circuit containing `z` but none of the `x i`. This is one of the axioms when defining infinite matroids via circuits. TODO : A similar statement will hold even when all mentions of `z` are removed. -/ lemma IsCircuit.strong_multi_elimination (hC₀ : M.IsCircuit C₀) (x : ι → α) (C : ι → Set α) (z : α) (hC : ∀ i, M.IsCircuit (C i)) (h_mem_C₀ : ∀ i, x i ∈ C₀) (h_mem : ∀ i, x i ∈ C i) (h_unique : ∀ ⦃i i'⦄, x i ∈ C i' → i = i') (hzC₀ : z ∈ C₀) (hzC : ∀ i, z ∉ C i) : ∃ C' ⊆ (C₀ ∪ ⋃ i, C i) \ range x, M.IsCircuit C' ∧ z ∈ C' := by have hwin := IsCircuit.strong_multi_elimination_insert (M := M) x (fun i ↦ (C i \ {x i})) (J := C₀ \ range x) (z := z) (by simp) (fun i ↦ ?_) ?_ ⟨hzC₀, ?_⟩ ?_ · obtain ⟨C', hC'ss, hC', hzC'⟩ := hwin refine ⟨C', hC'ss.trans ?_, hC', hzC'⟩ refine union_subset (diff_subset_diff_left subset_union_left) (iUnion_subset fun i ↦ subset_diff.2 ⟨diff_subset.trans (subset_union_of_subset_right (subset_iUnion ..) _), ?_⟩) rw [disjoint_iff_forall_ne] rintro _ he _ ⟨j, hj, rfl⟩ rfl obtain rfl : j = i := h_unique he.1 simp at he · simpa [insert_eq_of_mem (h_mem i)] using hC i · rwa [diff_union_self, union_eq_self_of_subset_right] rintro _ ⟨i, hi, rfl⟩ exact h_mem_C₀ i · rintro ⟨i, hi, rfl⟩ exact hzC _ (h_mem i) simp only [mem_diff, mem_singleton_iff, not_and, not_not] exact fun i hzi ↦ (hzC i hzi).elim /-- A version of `Circuit.strong_multi_elimination` where the collection of circuits is a `Set (Set α)` and the distinguished elements are a `Set α`, rather than both being indexed. -/ lemma IsCircuit.strong_multi_elimination_set (hC₀ : M.IsCircuit C₀) (X : Set α) (S : Set (Set α)) (z : α) (hCS : ∀ C ∈ S, M.IsCircuit C) (hXC₀ : X ⊆ C₀) (hX : ∀ x ∈ X, ∃ C ∈ S, C ∩ X = {x}) (hzC₀ : z ∈ C₀) (hz : ∀ C ∈ S, z ∉ C) : ∃ C' ⊆ (C₀ ∪ ⋃₀ S) \ X, M.IsCircuit C' ∧ z ∈ C' := by choose! C hC using hX simp only [forall_and] at hC have hwin := hC₀.strong_multi_elimination (fun x : X ↦ x) (fun x ↦ C x) z ?_ ?_ ?_ ?_ hzC₀ ?_ · obtain ⟨C', hC'ss, hC', hz⟩ := hwin refine ⟨C', hC'ss.trans (diff_subset_diff (union_subset_union_right _ ?_) (by simp)), hC', hz⟩ simpa using fun e heX ↦ (subset_sUnion_of_mem (hC.1 e heX)) · simpa using fun e heX ↦ hCS _ <| hC.1 e heX · simpa using fun e heX ↦ hXC₀ heX · simp only [Subtype.forall, ← singleton_subset_iff (s := C _)] exact fun e heX ↦ by simp [← hC.2 e heX] · simp only [Subtype.forall, Subtype.mk.injEq] refine fun e heX f hfX hef ↦ ?_ simpa [hC.2 f hfX] using subset_inter (singleton_subset_iff.2 hef) (singleton_subset_iff.2 heX) simpa using fun e heX heC ↦ hz _ (hC.1 e heX) heC /-- The strong isCircuit elimination axiom. For any pair of distinct circuits `C₁, C₂` and all `e ∈ C₁ ∩ C₂` and `f ∈ C₁ \ C₂`, there is a circuit `C` with `f ∈ C ⊆ (C₁ ∪ C₂) \ {e}`. -/ lemma IsCircuit.strong_elimination (hC₁ : M.IsCircuit C₁) (hC₂ : M.IsCircuit C₂) (heC₁ : e ∈ C₁) (heC₂ : e ∈ C₂) (hfC₁ : f ∈ C₁) (hfC₂ : f ∉ C₂) : ∃ C ⊆ (C₁ ∪ C₂) \ {e}, M.IsCircuit C ∧ f ∈ C := by obtain ⟨C, hCs, hC, hfC⟩ := hC₁.strong_multi_elimination (fun i : Unit ↦ e) (fun _ ↦ C₂) f (by simpa) (by simpa) (by simpa) (by simp) (by simpa) (by simpa) exact ⟨C, hCs.trans (diff_subset_diff (by simp) (by simp)), hC, hfC⟩ /-- The circuit elimination axiom : for any pair of distinct circuits `C₁, C₂` and any `e`, some circuit is contained in `(C₁ ∪ C₂) \ {e}`. This is one of the axioms when defining a finitary matroid via circuits; as an axiom, it is usually stated with the extra assumption that `e ∈ C₁ ∩ C₂`. -/ lemma IsCircuit.elimination (hC₁ : M.IsCircuit C₁) (hC₂ : M.IsCircuit C₂) (h : C₁ ≠ C₂) (e : α) : ∃ C ⊆ (C₁ ∪ C₂) \ {e}, M.IsCircuit C := by have hnss : ¬ (C₁ ⊆ C₂) := fun hss ↦ h <| hC₁.eq_of_subset_isCircuit hC₂ hss obtain ⟨f, hf₁, hf₂⟩ := not_subset.1 hnss by_cases he₁ : e ∈ C₁ · by_cases he₂ : e ∈ C₂ · obtain ⟨C, hC, hC', -⟩ := hC₁.strong_elimination hC₂ he₁ he₂ hf₁ hf₂ exact ⟨C, hC, hC'⟩ exact ⟨C₂, subset_diff_singleton subset_union_right he₂, hC₂⟩ exact ⟨C₁, subset_diff_singleton subset_union_left he₁, hC₁⟩ end Elimination /-! ### Finitary Matroids -/ section Finitary lemma IsCircuit.finite [Finitary M] (hC : M.IsCircuit C) : C.Finite := by have hi := hC.dep.not_indep rw [indep_iff_forall_finite_subset_indep] at hi; push_neg at hi obtain ⟨J, hJC, hJfin, hJ⟩ := hi rwa [← hC.eq_of_not_indep_subset hJ hJC] lemma finitary_iff_forall_isCircuit_finite : M.Finitary ↔ ∀ C, M.IsCircuit C → C.Finite := by refine ⟨fun _ _ ↦ IsCircuit.finite, fun h ↦ ⟨fun I hI ↦ indep_iff_not_dep.2 ⟨fun hd ↦ ?_,fun x hx ↦ ?_⟩⟩⟩ · obtain ⟨C, hCI, hC⟩ := hd.exists_isCircuit_subset exact hC.dep.not_indep <| hI _ hCI (h C hC) simpa using (hI {x} (by simpa) (finite_singleton _)).subset_ground /-- In a finitary matroid, every element spanned by a set `X` is in fact spanned by a finite independent subset of `X`. -/ lemma exists_mem_finite_closure_of_mem_closure [M.Finitary] (he : e ∈ M.closure X) : ∃ I ⊆ X, I.Finite ∧ M.Indep I ∧ e ∈ M.closure I := by by_cases heY : e ∈ X · obtain ⟨J, hJ⟩ := M.exists_isBasis {e} exact ⟨J, hJ.subset.trans (by simpa), (finite_singleton e).subset hJ.subset, hJ.indep, by simpa using hJ.subset_closure⟩ obtain ⟨C, hCs, hC, heC⟩ := exists_isCircuit_of_mem_closure he heY exact ⟨C \ {e}, by simpa, hC.finite.diff, hC.diff_singleton_indep heC, hC.mem_closure_diff_singleton_of_mem heC⟩ /-- In a finitary matroid, each finite set `X` spanned by a set `Y` is in fact spanned by a finite independent subset of `Y`. -/ lemma exists_subset_finite_closure_of_subset_closure [M.Finitary] (hX : X.Finite) (hXY : X ⊆ M.closure Y) : ∃ I ⊆ Y, I.Finite ∧ M.Indep I ∧ X ⊆ M.closure I := by suffices aux : ∃ T ⊆ Y, T.Finite ∧ X ⊆ M.closure T by obtain ⟨T, hT, hTfin, hXT⟩ := aux obtain ⟨I, hI⟩ := M.exists_isBasis' T exact ⟨_, hI.subset.trans hT, hTfin.subset hI.subset, hI.indep, by rwa [hI.closure_eq_closure]⟩ refine Finite.induction_on_subset X hX ⟨∅, by simp⟩ (fun {e Z} heX _ heZ ⟨T, hTY, hTfin, hT⟩ ↦ ?_) obtain ⟨S, hSY, hSfin, -, heS⟩ := exists_mem_finite_closure_of_mem_closure (hXY heX) exact ⟨S ∪ T, union_subset hSY hTY, hSfin.union hTfin, insert_subset (M.closure_mono subset_union_left heS) (hT.trans (M.closure_mono subset_union_right))⟩ end Finitary /-! ### IsCocircuits -/ section IsCocircuit variable {K B : Set α} /-- A cocircuit is a circuit of the dual matroid, or equivalently the complement of a hyperplane. -/ abbrev IsCocircuit (M : Matroid α) (K : Set α) : Prop := M✶.IsCircuit K lemma isCocircuit_def : M.IsCocircuit K ↔ M✶.IsCircuit K := Iff.rfl lemma IsCocircuit.isCircuit (hK : M.IsCocircuit K) : M✶.IsCircuit K := hK lemma IsCircuit.isCocircuit (hC : M.IsCircuit C) : M✶.IsCocircuit C := by rwa [isCocircuit_def, dual_dual] @[aesop unsafe 10% (rule_sets := [Matroid])] lemma IsCocircuit.subset_ground (hC : M.IsCocircuit C) : C ⊆ M.E := hC.isCircuit.subset_ground @[simp] lemma dual_isCocircuit_iff : M✶.IsCocircuit C ↔ M.IsCircuit C := by rw [isCocircuit_def, dual_dual] lemma coindep_iff_forall_subset_not_isCocircuit : M.Coindep X ↔ (∀ K, K ⊆ X → ¬M.IsCocircuit K) ∧ X ⊆ M.E := indep_iff_forall_subset_not_isCircuit' /-- A cocircuit is a minimal set that intersects every base. -/ lemma isCocircuit_iff_minimal : M.IsCocircuit K ↔ Minimal (fun X ↦ ∀ B, M.IsBase B → (X ∩ B).Nonempty) K := by have aux : M✶.Dep = fun X ↦ (∀ B, M.IsBase B → (X ∩ B).Nonempty) ∧ X ⊆ M.E := by ext; apply dual_dep_iff_forall rw [isCocircuit_def, isCircuit_def, aux, iff_comm] refine minimal_iff_minimal_of_imp_of_forall (fun _ h ↦ h.1) fun X hX ↦ ⟨X ∩ M.E, inter_subset_left, fun B hB ↦ ?_, inter_subset_right⟩ rw [inter_assoc, inter_eq_self_of_subset_right hB.subset_ground] exact hX B hB /-- A cocircuit is a minimal set whose complement is nonspanning. -/ lemma isCocircuit_iff_minimal_compl_nonspanning : M.IsCocircuit K ↔ Minimal (fun X ↦ ¬ M.Spanning (M.E \ X)) K := by convert isCocircuit_iff_minimal with K simp_rw [spanning_iff_exists_isBase_subset (S := M.E \ K), not_exists, subset_diff, not_and, not_disjoint_iff_nonempty_inter, ← and_imp, and_iff_left_of_imp IsBase.subset_ground, inter_comm K] /-- For an element `e` of a base `B`, the complement of the closure of `B \ {e}` is a cocircuit. -/ lemma IsBase.compl_closure_diff_singleton_isCocircuit (hB : M.IsBase B) (he : e ∈ B) : M.IsCocircuit (M.E \ M.closure (B \ {e})) := by rw [isCocircuit_iff_minimal_compl_nonspanning, minimal_subset_iff, diff_diff_cancel_left (M.closure_subset_ground _), closure_spanning_iff (diff_subset.trans hB.subset_ground)] have hB' := (isBase_iff_minimal_spanning.1 hB) refine ⟨fun hsp ↦ hB'.notMem_of_prop_diff_singleton hsp he, fun X hX hXss ↦ hXss.antisymm' ?_⟩ rw [diff_subset_comm] refine fun f hf ↦ by_contra fun fcl ↦ hX ?_ rw [subset_diff] at hXss suffices hsp : M.IsBase (insert f (B \ {e})) by refine hsp.spanning.superset <| insert_subset hf <| (M.subset_closure _ (diff_subset.trans hB.subset_ground)).trans ?_ rw [subset_diff, and_iff_left hXss.2.symm] apply closure_subset_ground exact hB.exchange_base_of_notMem_closure he fcl /-- A version of `Matroid.isCocircuit_iff_minimal_compl_nonspanning` with a support assumption in the minimality. -/ lemma isCocircuit_iff_minimal_compl_nonspanning' : M.IsCocircuit K ↔ Minimal (fun X ↦ ¬ M.Spanning (M.E \ X) ∧ X ⊆ M.E) K := by rw [isCocircuit_iff_minimal_compl_nonspanning] exact minimal_iff_minimal_of_imp_of_forall (fun _ h ↦ h.1) (fun X hX ↦ ⟨X ∩ M.E, inter_subset_left, by rwa [diff_inter_self_eq_diff], inter_subset_right⟩) /-- A cocircuit and a circuit cannot meet in exactly one element. -/ lemma IsCircuit.inter_isCocircuit_ne_singleton (hC : M.IsCircuit C) (hK : M.IsCocircuit K) : C ∩ K ≠ {e} := by intro he have heC : e ∈ C := (he.symm.subset rfl).1 simp_rw [isCocircuit_iff_minimal_compl_nonspanning, minimal_iff_forall_ssubset, not_not] at hK have' hKe := hK.2 (t := K \ {e}) (diff_singleton_ssubset.2 (he.symm.subset rfl).2) apply hK.1 rw [spanning_iff_ground_subset_closure] nth_rw 1 [← hKe.closure_eq, diff_diff_eq_sdiff_union] · refine (M.closure_subset_closure (subset_union_left (t := C))).trans ?_ rw [union_assoc, singleton_union, insert_eq_of_mem heC, ← closure_union_congr_right (hC.closure_diff_singleton_eq e), union_eq_self_of_subset_right] rw [← he, diff_self_inter] exact diff_subset_diff_left hC.subset_ground rw [← he] exact inter_subset_left.trans hC.subset_ground lemma IsCircuit.isCocircuit_inter_nontrivial (hC : M.IsCircuit C) (hK : M.IsCocircuit K) (hCK : (C ∩ K).Nonempty) : (C ∩ K).Nontrivial := by obtain ⟨e, heCK⟩ := hCK rw [nontrivial_iff_ne_singleton heCK] exact hC.inter_isCocircuit_ne_singleton hK lemma IsCircuit.isCocircuit_disjoint_or_nontrivial_inter (hC : M.IsCircuit C) (hK : M.IsCocircuit K) : Disjoint C K ∨ (C ∩ K).Nontrivial := by rw [or_iff_not_imp_left, disjoint_iff_inter_eq_empty, ← ne_eq, ← nonempty_iff_ne_empty] exact hC.isCocircuit_inter_nontrivial hK lemma dual_rankPos_iff_exists_isCircuit : M✶.RankPos ↔ ∃ C, M.IsCircuit C := by rw [rankPos_iff, dual_isBase_iff, diff_empty, not_iff_comm, not_exists, ← ground_indep_iff_isBase, indep_iff_forall_subset_not_isCircuit] exact ⟨fun h C _ ↦ h C, fun h C hC ↦ h C hC.subset_ground hC⟩ lemma IsCircuit.dual_rankPos (hC : M.IsCircuit C) : M✶.RankPos := dual_rankPos_iff_exists_isCircuit.mpr ⟨C, hC⟩ lemma exists_isCircuit [RankPos M✶] : ∃ C, M.IsCircuit C := dual_rankPos_iff_exists_isCircuit.1 (by assumption) lemma rankPos_iff_exists_isCocircuit : M.RankPos ↔ ∃ K, M.IsCocircuit K := by rw [← dual_dual M, dual_rankPos_iff_exists_isCircuit, dual_dual M] /-- The fundamental cocircuit for `B` and `e`: that is, the unique cocircuit `K` of `M` for which `K ∩ B = {e}`. Should be used when `B` is a base and `e ∈ B`. Has the junk value `{e}` if `e ∉ B` or `e ∉ M.E`. -/ def fundCocircuit (M : Matroid α) (e : α) (B : Set α) := M✶.fundCircuit e (M✶.E \ B) lemma fundCocircuit_isCocircuit (he : e ∈ B) (hB : M.IsBase B) : M.IsCocircuit <| M.fundCocircuit e B := by apply hB.compl_isBase_dual.indep.fundCircuit_isCircuit _ (by simp [he]) rw [hB.compl_isBase_dual.closure_eq, dual_ground] exact hB.subset_ground he lemma mem_fundCocircuit (M : Matroid α) (e : α) (B : Set α) : e ∈ M.fundCocircuit e B := mem_insert _ _ lemma fundCocircuit_subset_insert_compl (M : Matroid α) (e : α) (B : Set α) : M.fundCocircuit e B ⊆ insert e (M.E \ B) := fundCircuit_subset_insert .. lemma fundCocircuit_inter_eq (M : Matroid α) {B : Set α} (he : e ∈ B) : (M.fundCocircuit e B) ∩ B = {e} := by refine subset_antisymm ?_ (singleton_subset_iff.2 ⟨M.mem_fundCocircuit _ _, he⟩) refine (inter_subset_inter_left _ (M.fundCocircuit_subset_insert_compl _ _)).trans ?_ simp +contextual /-- The fundamental cocircuit of `X` and `e` has the junk value `{e}` if `e ∉ M.E` -/ lemma fundCocircuit_eq_of_notMem_ground (X : Set α) (he : e ∉ M.E) : M.fundCocircuit e X = {e} := by rwa [fundCocircuit, fundCircuit_eq_of_notMem_ground] @[deprecated (since := "2025-05-23")] alias fundCocircuit_eq_of_not_mem_ground := fundCocircuit_eq_of_notMem_ground /-- The fundamental cocircuit of `X` and `e` has the junk value `{e}` if `e ∉ X` -/ lemma fundCocircuit_eq_of_notMem (M : Matroid α) (heX : e ∉ X) : M.fundCocircuit e X = {e} := by by_cases he : e ∈ M.E · rw [fundCocircuit, fundCircuit_eq_of_mem] exact ⟨he, heX⟩ rw [fundCocircuit_eq_of_notMem_ground _ he] @[deprecated (since := "2025-05-23")] alias fundCocircuit_eq_of_not_mem := fundCocircuit_eq_of_notMem /-- For every element `e` of an independent set `I`, there is a cocircuit whose intersection with `I` is `{e}`. -/ lemma Indep.exists_isCocircuit_inter_eq_mem (hI : M.Indep I) (heI : e ∈ I) : ∃ K, M.IsCocircuit K ∧ K ∩ I = {e} := by obtain ⟨B, hB, hIB⟩ := hI.exists_isBase_superset refine ⟨M.fundCocircuit e B, fundCocircuit_isCocircuit (hIB heI) hB, ?_⟩ rw [subset_antisymm_iff, subset_inter_iff, singleton_subset_iff, and_iff_right (mem_fundCocircuit _ _ _), singleton_subset_iff, and_iff_left heI, ← M.fundCocircuit_inter_eq (hIB heI)] exact inter_subset_inter_right _ hIB /-- Fundamental circuits and cocircuits of a base `B` play dual roles; `e` belongs to the fundamental cocircuit for `B` and `f` if and only if `f` belongs to the fundamental circuit for `e` and `B`. This statement isn't so reasonable unless `f ∈ B` and `e ∉ B`, but holds due to junk values even without these assumptions. -/ lemma IsBase.mem_fundCocircuit_iff_mem_fundCircuit {e f : α} (hB : M.IsBase B) : e ∈ M.fundCocircuit f B ↔ f ∈ M.fundCircuit e B := by -- By symmetry and duality, it suffices to show the implication in one direction. suffices aux : ∀ {N : Matroid α} {B' : Set α} (hB' : N.IsBase B') {e f}, e ∈ N.fundCocircuit f B' → f ∈ N.fundCircuit e B' from ⟨fun h ↦ aux hB h , fun h ↦ aux hB.compl_isBase_dual <| by simpa [fundCocircuit, inter_eq_self_of_subset_right hB.subset_ground]⟩ clear! B M e f intro M B hB e f he -- discharge the various degenerate cases. obtain rfl | hne := eq_or_ne e f · simp [mem_fundCircuit] have hB' : M✶.IsBase (M✶.E \ B) := hB.compl_isBase_dual obtain hfE | hfE := em' <| f ∈ M.E · rw [fundCocircuit, fundCircuit_eq_of_notMem_ground (by simpa)] at he contradiction obtain hfB | hfB := em' <| f ∈ B · rw [fundCocircuit, fundCircuit_eq_of_mem (by simp [hfE, hfB])] at he contradiction obtain ⟨heE, heB⟩ : e ∈ M.E \ B := by simpa [hne] using (M.fundCocircuit_subset_insert_compl f B) he -- Use basis exchange to argue the equivalence. rw [fundCocircuit, hB'.indep.mem_fundCircuit_iff (by rwa [hB'.closure_eq]) (by simp [hfB])] at he rw [hB.indep.mem_fundCircuit_iff (by rwa [hB.closure_eq]) heB] have hB' : M.IsBase (M.E \ (insert f (M✶.E \ B) \ {e})) := (hB'.exchange_isBase_of_indep' ⟨heE, heB⟩ (by simp [hfE, hfB]) he).compl_isBase_of_dual refine hB'.indep.subset ?_ simp only [dual_ground, diff_singleton_subset_iff] rw [diff_diff_right, inter_eq_self_of_subset_right (by simpa), union_singleton, insert_comm, ← union_singleton (s := M.E \ B), ← diff_diff, diff_diff_cancel_left hB.subset_ground] simp [hfB] end IsCocircuit end Matroid
div.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq. (******************************************************************************) (* This file deals with divisibility for natural numbers. *) (* It contains the definitions of: *) (* edivn m d == the pair composed of the quotient and remainder *) (* of the Euclidean division of m by d. *) (* m %/ d == quotient of the Euclidean division of m by d. *) (* m %% d == remainder of the Euclidean division of m by d. *) (* m = n %[mod d] <-> m equals n modulo d. *) (* m == n %[mod d] <=> m equals n modulo d (boolean version). *) (* m <> n %[mod d] <-> m differs from n modulo d. *) (* m != n %[mod d] <=> m differs from n modulo d (boolean version). *) (* d %| m <=> d divides m. *) (* gcdn m n == the GCD of m and n. *) (* egcdn m n == the extended GCD (Bezout coefficient pair) of m and n. *) (* If egcdn m n = (u, v), then gcdn m n = m * u - n * v. *) (* lcmn m n == the LCM of m and n. *) (* coprime m n <=> m and n are coprime (:= gcdn m n == 1). *) (* chinese m n r s == witness of the chinese remainder theorem. *) (* We adjoin an m to operator suffixes to indicate a nested %% (modn), as in *) (* modnDml : m %% d + n = m + n %[mod d]. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (** Euclidean division *) Definition edivn_rec d := fix loop m q := if m - d is m'.+1 then loop m' q.+1 else (q, m). Definition edivn m d := if d > 0 then edivn_rec d.-1 m 0 else (0, m). Variant edivn_spec m d : nat * nat -> Type := EdivnSpec q r of m = q * d + r & (d > 0) ==> (r < d) : edivn_spec m d (q, r). Lemma edivnP m d : edivn_spec m d (edivn m d). Proof. rewrite -[m in edivn_spec m]/(0 * d + m) /edivn; case: d => //= d. elim/ltn_ind: m 0 => -[|m] IHm q //=; rewrite subn_if_gt. case: ltnP => // le_dm; rewrite -[in m.+1](subnKC le_dm) -addSn. by rewrite addnA -mulSnr; apply/IHm/leq_subr. Qed. Lemma edivn_eq d q r : r < d -> edivn (q * d + r) d = (q, r). Proof. move=> lt_rd; have d_gt0: 0 < d by apply: leq_trans lt_rd. case: edivnP lt_rd => q' r'; rewrite d_gt0 /=. wlog: q q' r r' / q <= q' by case/orP: (leq_total q q'); last symmetry; eauto. have [||-> _ /addnI ->] //= := ltngtP q q'. rewrite -(leq_pmul2r d_gt0) => /leq_add lt_qr _ eq_qr _ /lt_qr {lt_qr}. by rewrite addnS ltnNge mulSn -addnA eq_qr addnCA addnA leq_addr. Qed. Definition divn m d := (edivn m d).1. Notation "m %/ d" := (divn m d) : nat_scope. (* We redefine modn so that it is structurally decreasing. *) Definition modn_rec d := fix loop m := if m - d is m'.+1 then loop m' else m. Definition modn m d := if d > 0 then modn_rec d.-1 m else m. Notation "m %% d" := (modn m d) : nat_scope. Notation "m = n %[mod d ]" := (m %% d = n %% d) : nat_scope. Notation "m == n %[mod d ]" := (m %% d == n %% d) : nat_scope. Notation "m <> n %[mod d ]" := (m %% d <> n %% d) : nat_scope. Notation "m != n %[mod d ]" := (m %% d != n %% d) : nat_scope. Lemma modn_def m d : m %% d = (edivn m d).2. Proof. case: d => //= d; rewrite /modn /edivn /=; elim/ltn_ind: m 0 => -[|m] IHm q //=. by rewrite !subn_if_gt; case: (d <= m) => //; apply/IHm/leq_subr. Qed. Lemma edivn_def m d : edivn m d = (m %/ d, m %% d). Proof. by rewrite /divn modn_def; case: (edivn m d). Qed. Lemma divn_eq m d : m = m %/ d * d + m %% d. Proof. by rewrite /divn modn_def; case: edivnP. Qed. Lemma div0n d : 0 %/ d = 0. Proof. by case: d. Qed. Lemma divn0 m : m %/ 0 = 0. Proof. by []. Qed. Lemma mod0n d : 0 %% d = 0. Proof. by case: d. Qed. Lemma modn0 m : m %% 0 = m. Proof. by []. Qed. Lemma divn_small m d : m < d -> m %/ d = 0. Proof. by move=> lt_md; rewrite /divn (edivn_eq 0). Qed. Lemma divnMDl q m d : 0 < d -> (q * d + m) %/ d = q + m %/ d. Proof. move=> d_gt0; rewrite [in LHS](divn_eq m d) addnA -mulnDl. by rewrite /divn edivn_eq // modn_def; case: edivnP; rewrite d_gt0. Qed. Lemma mulnK m d : 0 < d -> m * d %/ d = m. Proof. by move=> d_gt0; rewrite -[m * d]addn0 divnMDl // div0n addn0. Qed. Lemma mulKn m d : 0 < d -> d * m %/ d = m. Proof. by move=> d_gt0; rewrite mulnC mulnK. Qed. Lemma expnB p m n : p > 0 -> m >= n -> p ^ (m - n) = p ^ m %/ p ^ n. Proof. by move=> p_gt0 /subnK-Dm; rewrite -[in RHS]Dm expnD mulnK // expn_gt0 p_gt0. Qed. Lemma modn1 m : m %% 1 = 0. Proof. by rewrite modn_def; case: edivnP => ? []. Qed. Lemma divn1 m : m %/ 1 = m. Proof. by rewrite [RHS](@divn_eq m 1) // modn1 addn0 muln1. Qed. Lemma divnn d : d %/ d = (0 < d). Proof. by case: d => // d; rewrite -[n in n %/ _]muln1 mulKn. Qed. Lemma divnMl p m d : p > 0 -> p * m %/ (p * d) = m %/ d. Proof. move=> p_gt0; have [->|d_gt0] := posnP d; first by rewrite muln0. rewrite [RHS]/divn; case: edivnP; rewrite d_gt0 /= => q r ->{m} lt_rd. rewrite mulnDr mulnCA divnMDl; last by rewrite muln_gt0 p_gt0. by rewrite addnC divn_small // ltn_pmul2l. Qed. Arguments divnMl [p m d]. Lemma divnMr p m d : p > 0 -> m * p %/ (d * p) = m %/ d. Proof. by move=> p_gt0; rewrite -!(mulnC p) divnMl. Qed. Arguments divnMr [p m d]. Lemma ltn_mod m d : (m %% d < d) = (0 < d). Proof. by case: d => // d; rewrite modn_def; case: edivnP. Qed. Lemma ltn_pmod m d : 0 < d -> m %% d < d. Proof. by rewrite ltn_mod. Qed. Lemma leq_divM m d : m %/ d * d <= m. Proof. by rewrite [leqRHS](divn_eq m d) leq_addr. Qed. #[deprecated(since="mathcomp 2.4.0", note="Renamed to leq_divM.")] Notation leq_trunc_div := leq_divM. Lemma leq_mod m d : m %% d <= m. Proof. by rewrite [leqRHS](divn_eq m d) leq_addl. Qed. Lemma leq_div m d : m %/ d <= m. Proof. by case: d => // d; apply: leq_trans (leq_pmulr _ _) (leq_divM _ _). Qed. Lemma ltn_ceil m d : 0 < d -> m < (m %/ d).+1 * d. Proof. by move=> d_gt0; rewrite [in m.+1](divn_eq m d) -addnS mulSnr leq_add2l ltn_mod. Qed. Lemma ltn_divLR m n d : d > 0 -> (m %/ d < n) = (m < n * d). Proof. move=> d_gt0; apply/idP/idP. by rewrite -(leq_pmul2r d_gt0); apply: leq_trans (ltn_ceil _ _). rewrite !ltnNge -(@leq_pmul2r d n) //; apply: contra => le_nd_floor. exact: leq_trans le_nd_floor (leq_divM _ _). Qed. Lemma leq_divRL m n d : d > 0 -> (m <= n %/ d) = (m * d <= n). Proof. by move=> d_gt0; rewrite leqNgt ltn_divLR // -leqNgt. Qed. Lemma ltn_Pdiv m d : 1 < d -> 0 < m -> m %/ d < m. Proof. by move=> d_gt1 m_gt0; rewrite ltn_divLR ?ltn_Pmulr // ltnW. Qed. Lemma divn_gt0 d m : 0 < d -> (0 < m %/ d) = (d <= m). Proof. by move=> d_gt0; rewrite leq_divRL ?mul1n. Qed. Lemma leq_div2r d m n : m <= n -> m %/ d <= n %/ d. Proof. have [-> //| d_gt0 le_mn] := posnP d. by rewrite leq_divRL // (leq_trans _ le_mn) -?leq_divRL. Qed. Lemma leq_div2l m d e : 0 < d -> d <= e -> m %/ e <= m %/ d. Proof. move/leq_divRL=> -> le_de. by apply: leq_trans (leq_divM m e); apply: leq_mul. Qed. Lemma edivnD m n d (offset := m %% d + n %% d >= d) : 0 < d -> edivn (m + n) d = (m %/ d + n %/ d + offset, m %% d + n %% d - offset * d). Proof. rewrite {}/offset; case: d => // d _; rewrite /divn !modn_def. case: (edivnP m d.+1) (edivnP n d.+1) => [/= q r -> r_lt] [/= p s -> s_lt]. rewrite addnACA -mulnDl; have [r_le s_le] := (ltnW r_lt, ltnW s_lt). have [d_ge|d_lt] := leqP; first by rewrite addn0 mul0n subn0 edivn_eq. rewrite addn1 mul1n -[in LHS](subnKC d_lt) addnA -mulSnr edivn_eq//. by rewrite ltn_subLR// -addnS leq_add. Qed. Lemma divnD m n d : 0 < d -> (m + n) %/ d = (m %/ d) + (n %/ d) + (m %% d + n %% d >= d). Proof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed. Lemma modnD m n d : 0 < d -> (m + n) %% d = m %% d + n %% d - (m %% d + n %% d >= d) * d. Proof. by move=> /(@edivnD m n); rewrite edivn_def => -[]. Qed. Lemma leqDmod m n d : 0 < d -> (d <= m %% d + n %% d) = ((m + n) %% d < n %% d). Proof. move=> d_gt0; rewrite modnD//. have [d_le|_] := leqP d; last by rewrite subn0 ltnNge leq_addl. by rewrite -(ltn_add2r d) mul1n (subnK d_le) addnC ltn_add2l ltn_pmod. Qed. Lemma divnB n m d : 0 < d -> (m - n) %/ d = (m %/ d) - (n %/ d) - (m %% d < n %% d). Proof. move=> d_gt0; have [mn|/ltnW nm] := leqP m n. by rewrite (eqP mn) (eqP (leq_div2r _ _)) ?div0n. by rewrite -[in m %/ d](subnK nm) divnD// addnAC addnK leqDmod ?subnK ?addnK. Qed. Lemma modnB m n d : 0 < d -> n <= m -> (m - n) %% d = (m %% d < n %% d) * d + m %% d - n %% d. Proof. move=> d_gt0 nm; rewrite -[in m %% _](subnK nm) -leqDmod// modnD//. have [d_le|_] := leqP d; last by rewrite mul0n add0n subn0 addnK. by rewrite mul1n addnBA// addnC !addnK. Qed. Lemma edivnB m n d (offset := m %% d < n %% d) : 0 < d -> n <= m -> edivn (m - n) d = (m %/ d - n %/ d - offset, offset * d + m %% d - n %% d). Proof. by move=> d_gt0 le_nm; rewrite edivn_def divnB// modnB. Qed. Lemma leq_divDl p m n : (m + n) %/ p <= m %/ p + n %/ p + 1. Proof. by have [->//|p_gt0] := posnP p; rewrite divnD// !leq_add// leq_b1. Qed. Lemma geq_divBl k m p : k %/ p - m %/ p <= (k - m) %/ p + 1. Proof. rewrite leq_subLR addnA; apply: leq_trans (leq_divDl _ _ _). by rewrite -maxnE leq_div2r ?leq_maxr. Qed. Lemma divnMA m n p : m %/ (n * p) = m %/ n %/ p. Proof. case: n p => [|n] [|p]; rewrite ?muln0 ?div0n //. rewrite [in RHS](divn_eq m (n.+1 * p.+1)) mulnA mulnAC !divnMDl //. by rewrite [_ %/ p.+1]divn_small ?addn0 // ltn_divLR // mulnC ltn_mod. Qed. Lemma divnAC m n p : m %/ n %/ p = m %/ p %/ n. Proof. by rewrite -!divnMA mulnC. Qed. Lemma modn_small m d : m < d -> m %% d = m. Proof. by move=> lt_md; rewrite [RHS](divn_eq m d) divn_small. Qed. Lemma modn_mod m d : m %% d = m %[mod d]. Proof. by case: d => // d; apply: modn_small; rewrite ltn_mod. Qed. Lemma modnMDl p m d : p * d + m = m %[mod d]. Proof. have [->|d_gt0] := posnP d; first by rewrite muln0. by rewrite [in LHS](divn_eq m d) addnA -mulnDl modn_def edivn_eq // ltn_mod. Qed. Lemma muln_modr p m d : p * (m %% d) = (p * m) %% (p * d). Proof. have [->//|p_gt0] := posnP p; apply: (@addnI (p * (m %/ d * d))). by rewrite -mulnDr -divn_eq mulnCA -(divnMl p_gt0) -divn_eq. Qed. Lemma muln_modl p m d : (m %% d) * p = (m * p) %% (d * p). Proof. by rewrite -!(mulnC p); apply: muln_modr. Qed. Lemma modn_divl m n d : (m %/ d) %% n = m %% (n * d) %/ d. Proof. case: d n => [|d] [|n] //; rewrite [in LHS]/divn [in LHS]modn_def. case: (edivnP m d.+1) edivnP => [/= _ r -> le_rd] [/= q s -> le_sn]. rewrite mulnDl -mulnA -addnA modnMDl modn_small ?divnMDl ?divn_small ?addn0//. by rewrite mulSnr -addnS leq_add ?leq_mul2r. Qed. Lemma modnDl m d : d + m = m %[mod d]. Proof. by rewrite -[m %% _](modnMDl 1) mul1n. Qed. Lemma modnDr m d : m + d = m %[mod d]. Proof. by rewrite addnC modnDl. Qed. Lemma modnn d : d %% d = 0. Proof. by rewrite [d %% d](modnDr 0) mod0n. Qed. Lemma modnMl p d : p * d %% d = 0. Proof. by rewrite -[p * d]addn0 modnMDl mod0n. Qed. Lemma modnMr p d : d * p %% d = 0. Proof. by rewrite mulnC modnMl. Qed. Lemma modnDml m n d : m %% d + n = m + n %[mod d]. Proof. by rewrite [in RHS](divn_eq m d) -addnA modnMDl. Qed. Lemma modnDmr m n d : m + n %% d = m + n %[mod d]. Proof. by rewrite !(addnC m) modnDml. Qed. Lemma modnDm m n d : m %% d + n %% d = m + n %[mod d]. Proof. by rewrite modnDml modnDmr. Qed. Lemma eqn_modDl p m n d : (p + m == p + n %[mod d]) = (m == n %[mod d]). Proof. case: d => [|d]; first by rewrite !modn0 eqn_add2l. apply/eqP/eqP=> eq_mn; last by rewrite -modnDmr eq_mn modnDmr. rewrite -(modnMDl p m) -(modnMDl p n) !mulnSr -!addnA. by rewrite -modnDmr eq_mn modnDmr. Qed. Lemma eqn_modDr p m n d : (m + p == n + p %[mod d]) = (m == n %[mod d]). Proof. by rewrite -!(addnC p) eqn_modDl. Qed. Lemma modnMml m n d : m %% d * n = m * n %[mod d]. Proof. by rewrite [in RHS](divn_eq m d) mulnDl mulnAC modnMDl. Qed. Lemma modnMmr m n d : m * (n %% d) = m * n %[mod d]. Proof. by rewrite !(mulnC m) modnMml. Qed. Lemma modnMm m n d : m %% d * (n %% d) = m * n %[mod d]. Proof. by rewrite modnMml modnMmr. Qed. Lemma modn2 m : m %% 2 = odd m. Proof. by elim: m => //= m IHm; rewrite -addn1 -modnDml IHm; case odd. Qed. Lemma divn2 m : m %/ 2 = m./2. Proof. by rewrite [in RHS](divn_eq m 2) modn2 muln2 addnC half_bit_double. Qed. Lemma odd_mod m d : odd d = false -> odd (m %% d) = odd m. Proof. by move=> d_even; rewrite [in RHS](divn_eq m d) oddD oddM d_even andbF. Qed. Lemma modnXm m n a : (a %% n) ^ m = a ^ m %[mod n]. Proof. by elim: m => // m IHm; rewrite !expnS -modnMmr IHm modnMml modnMmr. Qed. Lemma modnMDXl p m n d : (p * d + m) ^ n = m ^ n %[mod d]. Proof. by elim: n => // n IH; rewrite !expnS -modnMm IH modnMDl modnMm. Qed. (** Divisibility **) Definition dvdn d m := m %% d == 0. Notation "m %| d" := (dvdn m d) : nat_scope. Lemma dvdnP d m : reflect (exists k, m = k * d) (d %| m). Proof. apply: (iffP eqP) => [md0 | [k ->]]; last by rewrite modnMl. by exists (m %/ d); rewrite [LHS](divn_eq m d) md0 addn0. Qed. Arguments dvdnP {d m}. Lemma dvdn0 d : d %| 0. Proof. by case: d. Qed. Lemma dvd0n n : (0 %| n) = (n == 0). Proof. by case: n. Qed. Lemma dvdn1 d : (d %| 1) = (d == 1). Proof. by case: d => [|[|d]] //; rewrite /dvdn modn_small. Qed. Lemma dvd1n m : 1 %| m. Proof. by rewrite /dvdn modn1. Qed. Lemma dvdn_gt0 d m : m > 0 -> d %| m -> d > 0. Proof. by case: d => // /prednK <-. Qed. Lemma dvdnn m : m %| m. Proof. by rewrite /dvdn modnn. Qed. Lemma dvdn_mull d m n : d %| n -> d %| m * n. Proof. by case/dvdnP=> n' ->; rewrite /dvdn mulnA modnMl. Qed. Lemma dvdn_mulr d m n : d %| m -> d %| m * n. Proof. by move=> d_m; rewrite mulnC dvdn_mull. Qed. #[global] Hint Resolve dvdn0 dvd1n dvdnn dvdn_mull dvdn_mulr : core. Lemma dvdn_mul d1 d2 m1 m2 : d1 %| m1 -> d2 %| m2 -> d1 * d2 %| m1 * m2. Proof. by move=> /dvdnP[q1 ->] /dvdnP[q2 ->]; rewrite mulnCA -mulnA 2?dvdn_mull. Qed. Lemma dvdn_trans n d m : d %| n -> n %| m -> d %| m. Proof. by move=> d_dv_n /dvdnP[n1 ->]; apply: dvdn_mull. Qed. Lemma dvdn_eq d m : (d %| m) = (m %/ d * d == m). Proof. apply/eqP/eqP=> [modm0 | <-]; last exact: modnMl. by rewrite [RHS](divn_eq m d) modm0 addn0. Qed. Lemma dvdn2 n : (2 %| n) = ~~ odd n. Proof. by rewrite /dvdn modn2; case (odd n). Qed. Lemma dvdn_odd m n : m %| n -> odd n -> odd m. Proof. by move=> m_dv_n; apply: contraTT; rewrite -!dvdn2 => /dvdn_trans->. Qed. Lemma divnK d m : d %| m -> m %/ d * d = m. Proof. by rewrite dvdn_eq; move/eqP. Qed. Lemma leq_divLR d m n : d %| m -> (m %/ d <= n) = (m <= n * d). Proof. by case: d m => [|d] [|m] ///divnK=> {2}<-; rewrite leq_pmul2r. Qed. Lemma ltn_divRL d m n : d %| m -> (n < m %/ d) = (n * d < m). Proof. by move=> dv_d_m; rewrite !ltnNge leq_divLR. Qed. Lemma eqn_div d m n : d > 0 -> d %| m -> (n == m %/ d) = (n * d == m). Proof. by move=> d_gt0 dv_d_m; rewrite -(eqn_pmul2r d_gt0) divnK. Qed. Lemma eqn_mul d m n : d > 0 -> d %| m -> (m == n * d) = (m %/ d == n). Proof. by move=> d_gt0 dv_d_m; rewrite eq_sym -eqn_div // eq_sym. Qed. Lemma divn_mulAC d m n : d %| m -> m %/ d * n = m * n %/ d. Proof. case: d m => [[] //| d m] dv_d_m; apply/eqP. by rewrite eqn_div ?dvdn_mulr // mulnAC divnK. Qed. Lemma muln_divA d m n : d %| n -> m * (n %/ d) = m * n %/ d. Proof. by move=> dv_d_m; rewrite !(mulnC m) divn_mulAC. Qed. Lemma muln_divCA d m n : d %| m -> d %| n -> m * (n %/ d) = n * (m %/ d). Proof. by move=> dv_d_m dv_d_n; rewrite mulnC divn_mulAC ?muln_divA. Qed. Lemma divnA m n p : p %| n -> m %/ (n %/ p) = m * p %/ n. Proof. by case: p => [|p] dv_n; rewrite -[in RHS](divnK dv_n) // divnMr. Qed. Lemma modn_dvdm m n d : d %| m -> n %% m = n %[mod d]. Proof. by case/dvdnP=> q def_m; rewrite [in RHS](divn_eq n m) def_m mulnA modnMDl. Qed. Lemma dvdn_leq d m : 0 < m -> d %| m -> d <= m. Proof. by move=> m_gt0 /dvdnP[[|k] Dm]; rewrite Dm // leq_addr in m_gt0 *. Qed. Lemma gtnNdvd n d : 0 < n -> n < d -> (d %| n) = false. Proof. by move=> n_gt0 lt_nd; rewrite /dvdn eqn0Ngt modn_small ?n_gt0. Qed. Lemma eqn_dvd m n : (m == n) = (m %| n) && (n %| m). Proof. case: m n => [|m] [|n] //; apply/idP/andP => [/eqP -> //| []]. by rewrite eqn_leq => Hmn Hnm; do 2 rewrite dvdn_leq //. Qed. Lemma dvdn_pmul2l p d m : 0 < p -> (p * d %| p * m) = (d %| m). Proof. by case: p => // p _; rewrite /dvdn -muln_modr // muln_eq0. Qed. Arguments dvdn_pmul2l [p d m]. Lemma dvdn_pmul2r p d m : 0 < p -> (d * p %| m * p) = (d %| m). Proof. by move=> p_gt0; rewrite -!(mulnC p) dvdn_pmul2l. Qed. Arguments dvdn_pmul2r [p d m]. Lemma dvdn_divLR p d m : 0 < p -> p %| d -> (d %/ p %| m) = (d %| m * p). Proof. by move=> /(@dvdn_pmul2r p _ m) <- /divnK->. Qed. Lemma dvdn_divRL p d m : p %| m -> (d %| m %/ p) = (d * p %| m). Proof. have [-> | /(@dvdn_pmul2r p d) <- /divnK-> //] := posnP p. by rewrite divn0 muln0 dvdn0. Qed. Lemma dvdn_div d m : d %| m -> m %/ d %| m. Proof. by move/divnK=> {2}<-; apply: dvdn_mulr. Qed. Lemma dvdn_exp2l p m n : m <= n -> p ^ m %| p ^ n. Proof. by move/subnK <-; rewrite expnD dvdn_mull. Qed. Lemma dvdn_Pexp2l p m n : p > 1 -> (p ^ m %| p ^ n) = (m <= n). Proof. move=> p_gt1; case: leqP => [|gt_n_m]; first exact: dvdn_exp2l. by rewrite gtnNdvd ?ltn_exp2l ?expn_gt0 // ltnW. Qed. Lemma dvdn_exp2r m n k : m %| n -> m ^ k %| n ^ k. Proof. by case/dvdnP=> q ->; rewrite expnMn dvdn_mull. Qed. Lemma divn_modl m n d : d %| n -> (m %% n) %/ d = (m %/ d) %% (n %/ d). Proof. by move=> dvd_dn; rewrite modn_divl divnK. Qed. Lemma dvdn_addr m d n : d %| m -> (d %| m + n) = (d %| n). Proof. by case/dvdnP=> q ->; rewrite /dvdn modnMDl. Qed. Lemma dvdn_addl n d m : d %| n -> (d %| m + n) = (d %| m). Proof. by rewrite addnC; apply: dvdn_addr. Qed. Lemma dvdn_add d m n : d %| m -> d %| n -> d %| m + n. Proof. by move/dvdn_addr->. Qed. Lemma dvdn_add_eq d m n : d %| m + n -> (d %| m) = (d %| n). Proof. by move=> dv_d_mn; apply/idP/idP => [/dvdn_addr | /dvdn_addl] <-. Qed. Lemma dvdn_subr d m n : n <= m -> d %| m -> (d %| m - n) = (d %| n). Proof. by move=> le_n_m dv_d_m; apply: dvdn_add_eq; rewrite subnK. Qed. Lemma dvdn_subl d m n : n <= m -> d %| n -> (d %| m - n) = (d %| m). Proof. by move=> le_n_m dv_d_m; rewrite -(dvdn_addl _ dv_d_m) subnK. Qed. Lemma dvdn_sub d m n : d %| m -> d %| n -> d %| m - n. Proof. by case: (leqP n m) => [le_nm /dvdn_subr <- // | /ltnW/eqnP ->]; rewrite dvdn0. Qed. Lemma dvdn_exp k d m : 0 < k -> d %| m -> d %| (m ^ k). Proof. by case: k => // k _ d_dv_m; rewrite expnS dvdn_mulr. Qed. Lemma dvdn_fact m n : 0 < m <= n -> m %| n`!. Proof. case: m => //= m; elim: n => //= n IHn; rewrite ltnS. have [/IHn/dvdn_mull->||-> _] // := ltngtP m n; exact: dvdn_mulr. Qed. #[global] Hint Resolve dvdn_add dvdn_sub dvdn_exp : core. Lemma eqn_mod_dvd d m n : n <= m -> (m == n %[mod d]) = (d %| m - n). Proof. by move/subnK=> Dm; rewrite -[n in LHS]add0n -[in LHS]Dm eqn_modDr mod0n. Qed. Lemma divnDMl q m d : 0 < d -> (m + q * d) %/ d = (m %/ d) + q. Proof. by move=> d_gt0; rewrite addnC divnMDl// addnC. Qed. Lemma divnMBl q m d : 0 < d -> (q * d - m) %/ d = q - (m %/ d) - (~~ (d %| m)). Proof. by move=> d_gt0; rewrite divnB// mulnK// modnMl lt0n. Qed. Lemma divnBMl q m d : (m - q * d) %/ d = (m %/ d) - q. Proof. by case: d => [|d]//=; rewrite divnB// mulnK// modnMl ltn0 subn0. Qed. Lemma divnDl m n d : d %| m -> (m + n) %/ d = m %/ d + n %/ d. Proof. by case: d => // d /divnK-Dm; rewrite -[in LHS]Dm divnMDl. Qed. Lemma divnDr m n d : d %| n -> (m + n) %/ d = m %/ d + n %/ d. Proof. by move=> dv_n; rewrite addnC divnDl // addnC. Qed. Lemma divnBl m n d : d %| m -> (m - n) %/ d = m %/ d - (n %/ d) - (~~ (d %| n)). Proof. by case: d => [|d] // /divnK-Dm; rewrite -[in LHS]Dm divnMBl. Qed. Lemma divnBr m n d : d %| n -> (m - n) %/ d = m %/ d - n %/ d. Proof. by case: d => [|d]// /divnK-Dm; rewrite -[in LHS]Dm divnBMl. Qed. Lemma edivnS m d : 0 < d -> edivn m.+1 d = if d %| m.+1 then ((m %/ d).+1, 0) else (m %/ d, (m %% d).+1). Proof. case: d => [|[|d]] //= _; first by rewrite edivn_def modn1 dvd1n !divn1. rewrite -addn1 /dvdn modn_def edivnD//= (@modn_small 1)// (@divn_small 1)//. rewrite addn1 addn0 ltnS; have [||<-] := ltngtP d.+1. - by rewrite ltnNge -ltnS ltn_pmod. - by rewrite addn0 mul0n subn0. - by rewrite addn1 mul1n subnn. Qed. Lemma modnS m d : m.+1 %% d = if d %| m.+1 then 0 else (m %% d).+1. Proof. by case: d => [|d]//; rewrite modn_def edivnS//; case: ifP. Qed. Lemma divnS m d : 0 < d -> m.+1 %/ d = (d %| m.+1) + m %/ d. Proof. by move=> d_gt0; rewrite /divn edivnS//; case: ifP. Qed. Lemma divn_pred m d : m.-1 %/ d = (m %/ d) - (d %| m). Proof. by case: d m => [|d] [|m]; rewrite ?divn1 ?dvd1n ?subn1//= divnS// addnC addnK. Qed. Lemma modn_pred m d : d != 1 -> 0 < m -> m.-1 %% d = if d %| m then d.-1 else (m %% d).-1. Proof. rewrite -subn1; case: d m => [|[|d]] [|m]//= _ _. by rewrite ?modn1 ?dvd1n ?modn0 ?subn1. rewrite modnB// (@modn_small 1)// [_ < _]leqn0 /dvdn mulnbl/= subn1. by case: eqP => // ->; rewrite addn0. Qed. Lemma edivn_pred m d : d != 1 -> 0 < m -> edivn m.-1 d = if d %| m then ((m %/ d).-1, d.-1) else (m %/ d, (m %% d).-1). Proof. move=> d_neq1 m_gt0; rewrite edivn_def divn_pred modn_pred//. by case: ifP; rewrite ?subn0 ?subn1. Qed. (***********************************************************************) (* A function that computes the gcd of 2 numbers *) (***********************************************************************) Fixpoint gcdn m n := let n' := n %% m in if n' is 0 then m else if m - n'.-1 is m'.+1 then gcdn (m' %% n') n' else n'. Arguments gcdn : simpl never. Lemma gcdnE m n : gcdn m n = if m == 0 then n else gcdn (n %% m) m. Proof. elim/ltn_ind: m n => -[|m] IHm [|n] //=; rewrite /gcdn -/gcdn. case def_p: (_ %% _) => // [p]. have{def_p} lt_pm: p.+1 < m.+1 by rewrite -def_p ltn_pmod. rewrite {}IHm // subn_if_gt ltnW //=; congr gcdn. by rewrite -(subnK (ltnW lt_pm)) modnDr. Qed. Lemma gcdnn : idempotent_op gcdn. Proof. by case=> // n; rewrite gcdnE modnn. Qed. Lemma gcdnC : commutative gcdn. Proof. move=> m n; wlog lt_nm: m n / n < m by have [? ->|? <-|-> //] := ltngtP n m. by rewrite gcdnE -[in m == 0](ltn_predK lt_nm) modn_small. Qed. Lemma gcd0n : left_id 0 gcdn. Proof. by case. Qed. Lemma gcdn0 : right_id 0 gcdn. Proof. by case. Qed. Lemma gcd1n : left_zero 1 gcdn. Proof. by move=> n; rewrite gcdnE modn1. Qed. Lemma gcdn1 : right_zero 1 gcdn. Proof. by move=> n; rewrite gcdnC gcd1n. Qed. Lemma dvdn_gcdr m n : gcdn m n %| n. Proof. elim/ltn_ind: m n => -[|m] IHm [|n] //=. rewrite gcdnE; case def_p: (_ %% _) => [|p]; first by rewrite /dvdn def_p. have lt_pm: p < m by rewrite -ltnS -def_p ltn_pmod. rewrite /= (divn_eq n.+1 m.+1) def_p dvdn_addr ?dvdn_mull //; last exact: IHm. by rewrite gcdnE /= IHm // (ltn_trans (ltn_pmod _ _)). Qed. Lemma dvdn_gcdl m n : gcdn m n %| m. Proof. by rewrite gcdnC dvdn_gcdr. Qed. Lemma gcdn_gt0 m n : (0 < gcdn m n) = (0 < m) || (0 < n). Proof. by case: m n => [|m] [|n] //; apply: (@dvdn_gt0 _ m.+1) => //; apply: dvdn_gcdl. Qed. Lemma gcdnMDl k m n : gcdn m (k * m + n) = gcdn m n. Proof. by rewrite !(gcdnE m) modnMDl mulnC; case: m. Qed. Lemma gcdnDl m n : gcdn m (m + n) = gcdn m n. Proof. by rewrite -[m in m + n]mul1n gcdnMDl. Qed. Lemma gcdnDr m n : gcdn m (n + m) = gcdn m n. Proof. by rewrite addnC gcdnDl. Qed. Lemma gcdnMl n m : gcdn n (m * n) = n. Proof. by case: n => [|n]; rewrite gcdnE modnMl // muln0. Qed. Lemma gcdnMr n m : gcdn n (n * m) = n. Proof. by rewrite mulnC gcdnMl. Qed. Lemma gcdn_idPl {m n} : reflect (gcdn m n = m) (m %| n). Proof. by apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (gcdnMl, dvdn_gcdr). Qed. Lemma gcdn_idPr {m n} : reflect (gcdn m n = n) (n %| m). Proof. by rewrite gcdnC; apply: gcdn_idPl. Qed. Lemma expn_min e m n : e ^ minn m n = gcdn (e ^ m) (e ^ n). Proof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /gcdn_idPl; rewrite gcdnC. Qed. Lemma gcdn_modr m n : gcdn m (n %% m) = gcdn m n. Proof. by rewrite [in RHS](divn_eq n m) gcdnMDl. Qed. Lemma gcdn_modl m n : gcdn (m %% n) n = gcdn m n. Proof. by rewrite !(gcdnC _ n) gcdn_modr. Qed. (* Extended gcd, which computes Bezout coefficients. *) Fixpoint Bezout_rec km kn qs := if qs is q :: qs' then Bezout_rec kn (NatTrec.add_mul q kn km) qs' else (km, kn). Fixpoint egcdn_rec m n s qs := if s is s'.+1 then let: (q, r) := edivn m n in if r > 0 then egcdn_rec n r s' (q :: qs) else if odd (size qs) then qs else q.-1 :: qs else [::0]. Definition egcdn m n := Bezout_rec 0 1 (egcdn_rec m n n [::]). Variant egcdn_spec m n : nat * nat -> Type := EgcdnSpec km kn of km * m = kn * n + gcdn m n & kn * gcdn m n < m : egcdn_spec m n (km, kn). Lemma egcd0n n : egcdn 0 n = (1, 0). Proof. by case: n. Qed. Lemma egcdnP m n : m > 0 -> egcdn_spec m n (egcdn m n). Proof. have [-> /= | n_gt0 m_gt0] := posnP n; first by split; rewrite // mul1n gcdn0. rewrite /egcdn; set s := (s in egcdn_rec _ _ s); pose bz := Bezout_rec n m [::]. have: n < s.+1 by []; move defSpec: (egcdn_spec bz.2 bz.1) s => Spec s. elim: s => [[]|s IHs] //= in n m (qs := [::]) bz defSpec n_gt0 m_gt0 *. case: edivnP => q r def_m; rewrite n_gt0 ltnS /= => lt_rn le_ns1. case: posnP => [r0 {s le_ns1 IHs lt_rn}|r_gt0]; last first. by apply: IHs => //=; [rewrite natTrecE -def_m | rewrite (leq_trans lt_rn)]. rewrite {r}r0 addn0 in def_m; set b := odd _; pose d := gcdn m n. pose km := ~~ b : nat; pose kn := if b then 1 else q.-1. rewrite [bz in Spec bz](_ : _ = Bezout_rec km kn qs); last first. by rewrite /kn /km; case: (b) => //=; rewrite natTrecE addn0 muln1. have def_d: d = n by rewrite /d def_m gcdnC gcdnE modnMl gcd0n -[n]prednK. have: km * m + 2 * b * d = kn * n + d. rewrite {}/kn {}/km def_m def_d -mulSnr; case: b; rewrite //= addn0 mul1n. by rewrite prednK //; apply: dvdn_gt0 m_gt0 _; rewrite def_m dvdn_mulr. have{def_m}: kn * d <= m. have q_gt0 : 0 < q by rewrite def_m muln_gt0 n_gt0 ?andbT in m_gt0. by rewrite /kn; case b; rewrite def_d def_m leq_pmul2r // leq_pred. have{def_d}: km * d <= n by rewrite -[n]mul1n def_d leq_pmul2r // leq_b1. move: km {q}kn m_gt0 n_gt0 defSpec; rewrite {}/b {}/d {}/bz. elim: qs m n => [|q qs IHq] n r kn kr n_gt0 r_gt0 /=. set d := gcdn n r; rewrite mul0n addn0 => <- le_kn_r _ def_d; split=> //. have d_gt0: 0 < d by rewrite gcdn_gt0 n_gt0. have /ltn_pmul2l<-: 0 < kn by rewrite -(ltn_pmul2r n_gt0) def_d ltn_addl. by rewrite def_d -addn1 leq_add // mulnCA leq_mul2l le_kn_r orbT. rewrite !natTrecE; set m := _ + r; set km := _ + kn; pose d := gcdn m n. have ->: gcdn n r = d by rewrite [d]gcdnC gcdnMDl. have m_gt0: 0 < m by rewrite addn_gt0 r_gt0 orbT. have d_gt0: 0 < d by rewrite gcdn_gt0 m_gt0. move=> {}/IHq IHq le_kn_r le_kr_n def_d; apply: IHq => //; rewrite -/d. by rewrite mulnDl leq_add // -mulnA leq_mul2l le_kr_n orbT. apply: (@addIn d); rewrite mulnDr -addnA addnACA -def_d addnACA mulnA. rewrite -!mulnDl -mulnDr -addnA [kr * _]mulnC; congr addn. by rewrite addnC addn_negb muln1 mul2n addnn. Qed. Lemma Bezoutl m n : m > 0 -> {a | a < m & m %| gcdn m n + a * n}. Proof. move=> m_gt0; case: (egcdnP n m_gt0) => km kn def_d lt_kn_m. exists kn; last by rewrite addnC -def_d dvdn_mull. apply: leq_ltn_trans lt_kn_m. by rewrite -{1}[kn]muln1 leq_mul2l gcdn_gt0 m_gt0 orbT. Qed. Lemma Bezoutr m n : n > 0 -> {a | a < n & n %| gcdn m n + a * m}. Proof. by rewrite gcdnC; apply: Bezoutl. Qed. (* Back to the gcd. *) Lemma dvdn_gcd p m n : p %| gcdn m n = (p %| m) && (p %| n). Proof. apply/idP/andP=> [dv_pmn | [dv_pm dv_pn]]. by rewrite !(dvdn_trans dv_pmn) ?dvdn_gcdl ?dvdn_gcdr. have [->|n_gt0] := posnP n; first by rewrite gcdn0. case: (Bezoutr m n_gt0) => // km _ /(dvdn_trans dv_pn). by rewrite dvdn_addl // dvdn_mull. Qed. Lemma gcdnAC : right_commutative gcdn. Proof. suffices dvd m n p: gcdn (gcdn m n) p %| gcdn (gcdn m p) n. by move=> m n p; apply/eqP; rewrite eqn_dvd !dvd. rewrite !dvdn_gcd dvdn_gcdr. by rewrite !(dvdn_trans (dvdn_gcdl _ p)) ?dvdn_gcdl ?dvdn_gcdr. Qed. Lemma gcdnA : associative gcdn. Proof. by move=> m n p; rewrite !(gcdnC m) gcdnAC. Qed. Lemma gcdnCA : left_commutative gcdn. Proof. by move=> m n p; rewrite !gcdnA (gcdnC m). Qed. Lemma gcdnACA : interchange gcdn gcdn. Proof. by move=> m n p q; rewrite -!gcdnA (gcdnCA n). Qed. Lemma muln_gcdr : right_distributive muln gcdn. Proof. move=> p m n; have [-> //|p_gt0] := posnP p. elim/ltn_ind: m n => m IHm n; rewrite gcdnE [RHS]gcdnE muln_eq0 (gtn_eqF p_gt0). by case: posnP => // m_gt0; rewrite -muln_modr //=; apply/IHm/ltn_pmod. Qed. Lemma muln_gcdl : left_distributive muln gcdn. Proof. by move=> m n p; rewrite -!(mulnC p) muln_gcdr. Qed. Lemma gcdn_def d m n : d %| m -> d %| n -> (forall d', d' %| m -> d' %| n -> d' %| d) -> gcdn m n = d. Proof. move=> dv_dm dv_dn gdv_d; apply/eqP. by rewrite eqn_dvd dvdn_gcd dv_dm dv_dn gdv_d ?dvdn_gcdl ?dvdn_gcdr. Qed. Lemma muln_divCA_gcd n m : n * (m %/ gcdn n m) = m * (n %/ gcdn n m). Proof. by rewrite muln_divCA ?dvdn_gcdl ?dvdn_gcdr. Qed. (* We derive the lcm directly. *) Definition lcmn m n := m * n %/ gcdn m n. Lemma lcmnC : commutative lcmn. Proof. by move=> m n; rewrite /lcmn mulnC gcdnC. Qed. Lemma lcm0n : left_zero 0 lcmn. Proof. by move=> n; apply: div0n. Qed. Lemma lcmn0 : right_zero 0 lcmn. Proof. by move=> n; rewrite lcmnC lcm0n. Qed. Lemma lcm1n : left_id 1 lcmn. Proof. by move=> n; rewrite /lcmn gcd1n mul1n divn1. Qed. Lemma lcmn1 : right_id 1 lcmn. Proof. by move=> n; rewrite lcmnC lcm1n. Qed. Lemma muln_lcm_gcd m n : lcmn m n * gcdn m n = m * n. Proof. by apply/eqP; rewrite divnK ?dvdn_mull ?dvdn_gcdr. Qed. Lemma lcmn_gt0 m n : (0 < lcmn m n) = (0 < m) && (0 < n). Proof. by rewrite -muln_gt0 ltn_divRL ?dvdn_mull ?dvdn_gcdr. Qed. Lemma muln_lcmr : right_distributive muln lcmn. Proof. case=> // m n p; rewrite /lcmn -muln_gcdr -!mulnA divnMl // mulnCA. by rewrite muln_divA ?dvdn_mull ?dvdn_gcdr. Qed. Lemma muln_lcml : left_distributive muln lcmn. Proof. by move=> m n p; rewrite -!(mulnC p) muln_lcmr. Qed. Lemma lcmnA : associative lcmn. Proof. move=> m n p; rewrite [LHS]/lcmn [RHS]/lcmn mulnC. rewrite !divn_mulAC ?dvdn_mull ?dvdn_gcdr // -!divnMA ?dvdn_mulr ?dvdn_gcdl //. rewrite mulnC mulnA !muln_gcdr; congr (_ %/ _). by rewrite ![_ * lcmn _ _]mulnC !muln_lcm_gcd !muln_gcdl -!(mulnC m) gcdnA. Qed. Lemma lcmnCA : left_commutative lcmn. Proof. by move=> m n p; rewrite !lcmnA (lcmnC m). Qed. Lemma lcmnAC : right_commutative lcmn. Proof. by move=> m n p; rewrite -!lcmnA (lcmnC n). Qed. Lemma lcmnACA : interchange lcmn lcmn. Proof. by move=> m n p q; rewrite -!lcmnA (lcmnCA n). Qed. Lemma dvdn_lcml d1 d2 : d1 %| lcmn d1 d2. Proof. by rewrite /lcmn -muln_divA ?dvdn_gcdr ?dvdn_mulr. Qed. Lemma dvdn_lcmr d1 d2 : d2 %| lcmn d1 d2. Proof. by rewrite lcmnC dvdn_lcml. Qed. Lemma dvdn_lcm d1 d2 m : lcmn d1 d2 %| m = (d1 %| m) && (d2 %| m). Proof. case: d1 d2 => [|d1] [|d2]; try by case: m => [|m]; rewrite ?lcmn0 ?andbF. rewrite -(@dvdn_pmul2r (gcdn d1.+1 d2.+1)) ?gcdn_gt0 // muln_lcm_gcd. by rewrite muln_gcdr dvdn_gcd {1}mulnC andbC !dvdn_pmul2r. Qed. Lemma lcmnMl m n : lcmn m (m * n) = m * n. Proof. by case: m => // m; rewrite /lcmn gcdnMr mulKn. Qed. Lemma lcmnMr m n : lcmn n (m * n) = m * n. Proof. by rewrite mulnC lcmnMl. Qed. Lemma lcmn_idPr {m n} : reflect (lcmn m n = n) (m %| n). Proof. by apply: (iffP idP) => [/dvdnP[q ->] | <-]; rewrite (lcmnMr, dvdn_lcml). Qed. Lemma lcmn_idPl {m n} : reflect (lcmn m n = m) (n %| m). Proof. by rewrite lcmnC; apply: lcmn_idPr. Qed. Lemma expn_max e m n : e ^ maxn m n = lcmn (e ^ m) (e ^ n). Proof. by case: leqP => [|/ltnW] /(dvdn_exp2l e) /lcmn_idPl; rewrite lcmnC. Qed. (* Coprime factors *) Definition coprime m n := gcdn m n == 1. Lemma coprime1n n : coprime 1 n. Proof. by rewrite /coprime gcd1n. Qed. Lemma coprimen1 n : coprime n 1. Proof. by rewrite /coprime gcdn1. Qed. Lemma coprime_sym m n : coprime m n = coprime n m. Proof. by rewrite /coprime gcdnC. Qed. Lemma coprime_modl m n : coprime (m %% n) n = coprime m n. Proof. by rewrite /coprime gcdn_modl. Qed. Lemma coprime_modr m n : coprime m (n %% m) = coprime m n. Proof. by rewrite /coprime gcdn_modr. Qed. Lemma coprime2n n : coprime 2 n = odd n. Proof. by rewrite -coprime_modr modn2; case: (odd n). Qed. Lemma coprimen2 n : coprime n 2 = odd n. Proof. by rewrite coprime_sym coprime2n. Qed. Lemma coprimeSn n : coprime n.+1 n. Proof. by rewrite -coprime_modl (modnDr 1) coprime_modl coprime1n. Qed. Lemma coprimenS n : coprime n n.+1. Proof. by rewrite coprime_sym coprimeSn. Qed. Lemma coprimePn n : n > 0 -> coprime n.-1 n. Proof. by case: n => // n _; rewrite coprimenS. Qed. Lemma coprimenP n : n > 0 -> coprime n n.-1. Proof. by case: n => // n _; rewrite coprimeSn. Qed. Lemma coprimeP n m : n > 0 -> reflect (exists u, u.1 * n - u.2 * m = 1) (coprime n m). Proof. move=> n_gt0; apply: (iffP eqP) => [<-| [[kn km] /= kn_km_1]]. by have [kn km kg _] := egcdnP m n_gt0; exists (kn, km); rewrite kg addKn. apply gcdn_def; rewrite ?dvd1n // => d dv_d_n dv_d_m. by rewrite -kn_km_1 dvdn_subr ?dvdn_mull // ltnW // -subn_gt0 kn_km_1. Qed. Lemma modn_coprime k n : 0 < k -> (exists u, (k * u) %% n = 1) -> coprime k n. Proof. move=> k_gt0 [u Hu]; apply/coprimeP=> //. by exists (u, k * u %/ n); rewrite /= mulnC {1}(divn_eq (k * u) n) addKn. Qed. Lemma Gauss_dvd m n p : coprime m n -> (m * n %| p) = (m %| p) && (n %| p). Proof. by move=> co_mn; rewrite -muln_lcm_gcd (eqnP co_mn) muln1 dvdn_lcm. Qed. Lemma Gauss_dvdr m n p : coprime m n -> (m %| n * p) = (m %| p). Proof. case: n => [|n] co_mn; first by case: m co_mn => [|[]] // _; rewrite !dvd1n. by symmetry; rewrite mulnC -(@dvdn_pmul2r n.+1) ?Gauss_dvd // andbC dvdn_mull. Qed. Lemma Gauss_dvdl m n p : coprime m p -> (m %| n * p) = (m %| n). Proof. by rewrite mulnC; apply: Gauss_dvdr. Qed. Lemma dvdn_double_leq m n : m %| n -> odd m -> ~~ odd n -> 0 < n -> m.*2 <= n. Proof. move=> m_dv_n odd_m even_n n_gt0. by rewrite -muln2 dvdn_leq // Gauss_dvd ?coprimen2 ?m_dv_n ?dvdn2. Qed. Lemma dvdn_double_ltn m n : m %| n.-1 -> odd m -> odd n -> 1 < n -> m.*2 < n. Proof. by case: n => //; apply: dvdn_double_leq. Qed. Lemma Gauss_gcdr p m n : coprime p m -> gcdn p (m * n) = gcdn p n. Proof. move=> co_pm; apply/eqP; rewrite eqn_dvd !dvdn_gcd !dvdn_gcdl /=. rewrite andbC dvdn_mull ?dvdn_gcdr //= -(@Gauss_dvdr _ m) ?dvdn_gcdr //. by rewrite /coprime gcdnAC (eqnP co_pm) gcd1n. Qed. Lemma Gauss_gcdl p m n : coprime p n -> gcdn p (m * n) = gcdn p m. Proof. by move=> co_pn; rewrite mulnC Gauss_gcdr. Qed. Lemma coprimeMr p m n : coprime p (m * n) = coprime p m && coprime p n. Proof. case co_pm: (coprime p m) => /=; first by rewrite /coprime Gauss_gcdr. apply/eqP=> co_p_mn; case/eqnP: co_pm; apply gcdn_def => // d dv_dp dv_dm. by rewrite -co_p_mn dvdn_gcd dv_dp dvdn_mulr. Qed. Lemma coprimeMl p m n : coprime (m * n) p = coprime m p && coprime n p. Proof. by rewrite -!(coprime_sym p) coprimeMr. Qed. Lemma coprime_pexpl k m n : 0 < k -> coprime (m ^ k) n = coprime m n. Proof. case: k => // k _; elim: k => [|k IHk]; first by rewrite expn1. by rewrite expnS coprimeMl -IHk; case coprime. Qed. Lemma coprime_pexpr k m n : 0 < k -> coprime m (n ^ k) = coprime m n. Proof. by move=> k_gt0; rewrite !(coprime_sym m) coprime_pexpl. Qed. Lemma coprimeXl k m n : coprime m n -> coprime (m ^ k) n. Proof. by case: k => [|k] co_pm; rewrite ?coprime1n // coprime_pexpl. Qed. Lemma coprimeXr k m n : coprime m n -> coprime m (n ^ k). Proof. by rewrite !(coprime_sym m); apply: coprimeXl. Qed. Lemma coprime_dvdl m n p : m %| n -> coprime n p -> coprime m p. Proof. by case/dvdnP=> d ->; rewrite coprimeMl => /andP[]. Qed. Lemma coprime_dvdr m n p : m %| n -> coprime p n -> coprime p m. Proof. by rewrite !(coprime_sym p); apply: coprime_dvdl. Qed. Lemma coprime_egcdn n m : n > 0 -> coprime (egcdn n m).1 (egcdn n m).2. Proof. move=> n_gt0; case: (egcdnP m n_gt0) => kn km /= /eqP. have [/dvdnP[u defn] /dvdnP[v defm]] := (dvdn_gcdl n m, dvdn_gcdr n m). rewrite -[gcdn n m]mul1n {1}defm {1}defn !mulnA -mulnDl addnC. rewrite eqn_pmul2r ?gcdn_gt0 ?n_gt0 //; case: kn => // kn /eqP def_knu _. by apply/coprimeP=> //; exists (u, v); rewrite mulnC def_knu mulnC addnK. Qed. Lemma dvdn_pexp2r m n k : k > 0 -> (m ^ k %| n ^ k) = (m %| n). Proof. move=> k_gt0; apply/idP/idP=> [dv_mn_k|]; last exact: dvdn_exp2r. have [->|n_gt0] := posnP n; first by rewrite dvdn0. have [n' def_n] := dvdnP (dvdn_gcdr m n); set d := gcdn m n in def_n. have [m' def_m] := dvdnP (dvdn_gcdl m n); rewrite -/d in def_m. have d_gt0: d > 0 by rewrite gcdn_gt0 n_gt0 orbT. rewrite def_m def_n !expnMn dvdn_pmul2r ?expn_gt0 ?d_gt0 // in dv_mn_k. have: coprime (m' ^ k) (n' ^ k). rewrite coprime_pexpl // coprime_pexpr // /coprime -(eqn_pmul2r d_gt0) mul1n. by rewrite muln_gcdl -def_m -def_n. rewrite /coprime -gcdn_modr (eqnP dv_mn_k) gcdn0 -(exp1n k). by rewrite (inj_eq (expIn k_gt0)) def_m; move/eqP->; rewrite mul1n dvdn_gcdr. Qed. Section Chinese. (***********************************************************************) (* The chinese remainder theorem *) (***********************************************************************) Variables m1 m2 : nat. Hypothesis co_m12 : coprime m1 m2. Lemma chinese_remainder x y : (x == y %[mod m1 * m2]) = (x == y %[mod m1]) && (x == y %[mod m2]). Proof. wlog le_yx : x y / y <= x; last by rewrite !eqn_mod_dvd // Gauss_dvd. by have [?|/ltnW ?] := leqP y x; last rewrite !(eq_sym (x %% _)); apply. Qed. (***********************************************************************) (* A function that solves the chinese remainder problem *) (***********************************************************************) Definition chinese r1 r2 := r1 * m2 * (egcdn m2 m1).1 + r2 * m1 * (egcdn m1 m2).1. Lemma chinese_modl r1 r2 : chinese r1 r2 = r1 %[mod m1]. Proof. rewrite /chinese; case: (posnP m2) co_m12 => [-> /eqnP | m2_gt0 _]. by rewrite gcdn0 => ->; rewrite !modn1. case: egcdnP => // k2 k1 def_m1 _. rewrite mulnAC -mulnA def_m1 gcdnC (eqnP co_m12) mulnDr mulnA muln1. by rewrite addnAC (mulnAC _ m1) -mulnDl modnMDl. Qed. Lemma chinese_modr r1 r2 : chinese r1 r2 = r2 %[mod m2]. Proof. rewrite /chinese; case: (posnP m1) co_m12 => [-> /eqnP | m1_gt0 _]. by rewrite gcd0n => ->; rewrite !modn1. case: (egcdnP m2) => // k1 k2 def_m2 _. rewrite addnC mulnAC -mulnA def_m2 (eqnP co_m12) mulnDr mulnA muln1. by rewrite addnAC (mulnAC _ m2) -mulnDl modnMDl. Qed. Lemma chinese_mod x : x = chinese (x %% m1) (x %% m2) %[mod m1 * m2]. Proof. apply/eqP; rewrite chinese_remainder //. by rewrite chinese_modl chinese_modr !modn_mod !eqxx. Qed. End Chinese.
DischargerAsTactic.lean
/- Copyright (c) 2023 Alex J. Best. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best -/ import Mathlib.Init import Lean.Elab.Tactic.Basic import Lean.Meta.Tactic.Simp.Rewrite import Batteries.Tactic.Exact /-! ## Dischargers for `simp` to tactics This file defines a wrapper for `Simp.Discharger`s as regular tactics, that allows them to be used via the tactic frontend of `simp` via `simp (discharger := wrapSimpDischarger my_discharger)`. -/ open Lean Meta Elab Tactic /-- Wrap an simp discharger (a function `Expr → SimpM (Option Expr)`) as a tactic, so that it can be passed as an argument to `simp (discharger := foo)`. This is inverse to `mkDischargeWrapper`. -/ def wrapSimpDischarger (dis : Simp.Discharge) : TacticM Unit := do let eS : Lean.Meta.Simp.State := {} let eC : Lean.Meta.Simp.Context := ← Simp.mkContext {} let eM : Lean.Meta.Simp.Methods := {} let (some a, _) ← liftM <| StateRefT'.run (ReaderT.run (ReaderT.run (dis <| ← getMainTarget) eM.toMethodsRef) eC) eS | failure (← getMainGoal).assignIfDefEq a
GroupLieAlgebra.lean
/- Copyright (c) 2024 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Algebra.Lie.Basic import Mathlib.Geometry.Manifold.Algebra.LieGroup import Mathlib.Geometry.Manifold.VectorField.LieBracket /-! # The Lie algebra of a Lie group Given a Lie group, we define `GroupLieAlgebra I G` as its tangent space at the identity, and we endow it with a Lie bracket, as follows. Given two vectors `v, w : GroupLieAlgebra I G`, consider the associated left-invariant vector fields `mulInvariantVectorField v` (given at a point `g` by the image of `v` under the derivative of left-multiplication by `g`) and `mulInvariantVectorField w`. Then take their Lie bracket at the identity: this is by definition the bracket of `v` and `w`. Due to general properties of the Lie bracket of vector fields, this gives a Lie algebra structure on `GroupLieAlgebra I G`. Note that one can also define a Lie algebra on the space of left-invariant derivations on `C^∞` functions (see `LeftInvariantDerivation.instLieAlgebra`). For finite-dimensional `C^∞` real manifolds, this space of derivations can be canonically identified with the tangent space, and we recover the same Lie algebra structure (TODO: prove this). In other smoothness classes or on other fields, this identification is not always true, though, so the derivations point of view does not work in these settings. Therefore, the point of view in the current file is more general, and should be favored when possible. The standing assumption in this file is that the group is `C^n` for `n = minSmoothness 𝕜 3`, i.e., it is `C^3` over `ℝ` or `ℂ`, and analytic otherwise. -/ noncomputable section section LieGroup open Bundle Filter Function Set open scoped Manifold variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] {H : Type*} [TopologicalSpace H] {E : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] {I : ModelWithCorners 𝕜 E H} {G : Type*} [TopologicalSpace G] [ChartedSpace H G] [Group G] variable (I G) in /-- The Lie algebra of a Lie group, i.e., its tangent space at the identity. We use the word `GroupLieAlgebra` instead of `LieAlgebra` as the latter is taken as a generic class. -/ @[to_additive /-- The Lie algebra of an additive Lie group, i.e., its tangent space at zero. We use the word `AddGroupLieAlgebra` instead of `LieAlgebra` as the latter is taken as a generic class. -/] abbrev GroupLieAlgebra : Type _ := TangentSpace I (1 : G) /-- The invariant vector field associated to a vector `v` in the Lie alebra. At a point `g`, it is given by the image of `v` under left-multiplication by `g`. -/ @[to_additive /-- The invariant vector field associated to a vector `v` in the Lie alebra. At a point `g`, it is given by the image of `v` under left-addition by `g`. -/] noncomputable def mulInvariantVectorField (v : GroupLieAlgebra I G) (g : G) : TangentSpace I g := mfderiv I I (g * ·) (1 : G) v @[to_additive] lemma mulInvariantVectorField_add (v w : GroupLieAlgebra I G) : mulInvariantVectorField (v + w) = mulInvariantVectorField v + mulInvariantVectorField w := by ext g simp [mulInvariantVectorField] /- `to_additive` fails on the next lemma, as it tries to additivize `smul` while it shouldn't. Therefore, we state and prove by hand the additive version. -/ lemma addInvariantVectorField_smul {G : Type*} [TopologicalSpace G] [ChartedSpace H G] [AddGroup G] (c : 𝕜) (v : AddGroupLieAlgebra I G) : addInvariantVectorField (c • v) = c • addInvariantVectorField v := by ext g simp [addInvariantVectorField] lemma mulInvariantVectorField_smul (c : 𝕜) (v : GroupLieAlgebra I G) : mulInvariantVectorField (c • v) = c • mulInvariantVectorField v := by ext g simp [mulInvariantVectorField] open VectorField /-- The Lie bracket of two vectors `v` and `w` in the Lie algebra of a Lie group is obtained by taking the Lie bracket of the associated invariant vector fields, at the identity. -/ @[to_additive /-- The Lie bracket of two vectors `v` and `w` in the Lie algebra of an additive Lie group is obtained by taking the Lie bracket of the associated invariant vector fields, at zero. -/] noncomputable instance : Bracket (GroupLieAlgebra I G) (GroupLieAlgebra I G) where bracket v w := mlieBracket I (mulInvariantVectorField v) (mulInvariantVectorField w) (1 : G) @[to_additive] lemma GroupLieAlgebra.bracket_def (v w : GroupLieAlgebra I G) : ⁅v, w⁆ = mlieBracket I (mulInvariantVectorField v) (mulInvariantVectorField w) (1 : G) := rfl variable [LieGroup I (minSmoothness 𝕜 3) G] @[to_additive (attr := simp)] lemma inverse_mfderiv_mul_left {g h : G} : (mfderiv I I (fun b ↦ g * b) h).inverse = mfderiv I I (fun b ↦ g⁻¹ * b) (g * h) := by have M : 1 ≤ minSmoothness 𝕜 3 := le_trans (by simp) le_minSmoothness have A : mfderiv I I ((fun x ↦ g⁻¹ * x) ∘ (fun x ↦ g * x)) h = ContinuousLinearMap.id _ _ := by have : (fun x ↦ g⁻¹ * x) ∘ (fun x ↦ g * x) = id := by ext x; simp rw [this, id_eq, mfderiv_id] rw [mfderiv_comp (I' := I) _ (contMDiff_mul_left.contMDiffAt.mdifferentiableAt M) (contMDiff_mul_left.contMDiffAt.mdifferentiableAt M)] at A have A' : mfderiv I I ((fun x ↦ g * x) ∘ (fun x ↦ g⁻¹ * x)) (g * h) = ContinuousLinearMap.id _ _ := by have : (fun x ↦ g * x) ∘ (fun x ↦ g⁻¹ * x) = id := by ext x; simp rw [this, id_eq, mfderiv_id] rw [mfderiv_comp (I' := I) _ (contMDiff_mul_left.contMDiffAt.mdifferentiableAt M) (contMDiff_mul_left.contMDiffAt.mdifferentiableAt M), inv_mul_cancel_left g h] at A' exact ContinuousLinearMap.inverse_eq A' A /-- Invariant vector fields are invariant under pullbacks. -/ @[to_additive /-- Invariant vector fields are invariant under pullbacks. -/] lemma mpullback_mulInvariantVectorField (g : G) (v : GroupLieAlgebra I G) : mpullback I I (g * ·) (mulInvariantVectorField v) = mulInvariantVectorField v := by have M : 1 ≤ minSmoothness 𝕜 3 := le_trans (by simp) le_minSmoothness ext h simp only [mpullback, inverse_mfderiv_mul_left, mulInvariantVectorField] have D : (fun x ↦ h * x) = (fun b ↦ g⁻¹ * b) ∘ (fun x ↦ g * h * x) := by ext x; simp only [comp_apply]; group rw [D, mfderiv_comp (I' := I)] · congr 2 simp · exact contMDiff_mul_left.contMDiffAt.mdifferentiableAt M · exact contMDiff_mul_left.contMDiffAt.mdifferentiableAt M @[to_additive] lemma mulInvariantVectorField_eq_mpullback (g : G) (V : Π (g : G), TangentSpace I g) : mulInvariantVectorField (V 1) g = mpullback I I (g ⁻¹ * ·) V g := by have A : 1 = g⁻¹ * g := by simp simp only [mulInvariantVectorField, mpullback, inverse_mfderiv_mul_left] congr simp @[to_additive] theorem contMDiff_mulInvariantVectorField (v : GroupLieAlgebra I G) : ContMDiff I I.tangent (minSmoothness 𝕜 2) (fun (g : G) ↦ (mulInvariantVectorField v g : TangentBundle I G)) := by /- We will write the desired map as a composition of obviously smooth maps. The derivative of the product `P : (g, h) ↦ g * h` is given by `DP (g, h) ⬝ (u, v) = DL_g v + DR_h u`, where `L_g` and `R_h` are respectively left and right multiplication by `g` and `h`. As `P` is smooth, so is `DP`. Consider the map `F₁ : M → T (M × M)` mapping `g` to `(0, v) ∈ T_(g, e) (M × M)`. Then the composition of `DP` with `F₁` maps `g` to `DL_g v ∈ T_g M`, thanks to the above formula. This is the desired invariant vector field. Since both `DP` and `F₁` are smooth, their composition is smooth as desired. There is a small abuse of notation in the above argument, where we have identified `T (M × M)` and `TM × TM`. In the formal proof, we need to introduce this identification, called `F₂` below, which is also already known to be smooth. -/ have M : 1 ≤ minSmoothness 𝕜 3 := le_trans (by simp) le_minSmoothness have A : minSmoothness 𝕜 2 + 1 = minSmoothness 𝕜 3 := by rw [← minSmoothness_add] norm_num let fg : G → TangentBundle I G := fun g ↦ TotalSpace.mk' E g 0 have sfg : ContMDiff I I.tangent (minSmoothness 𝕜 2) fg := contMDiff_zeroSection _ _ let fv : G → TangentBundle I G := fun _ ↦ TotalSpace.mk' E 1 v have sfv : ContMDiff I I.tangent (minSmoothness 𝕜 2) fv := contMDiff_const let F₁ : G → (TangentBundle I G × TangentBundle I G) := fun g ↦ (fg g, fv g) have S₁ : ContMDiff I (I.tangent.prod I.tangent) (minSmoothness 𝕜 2) F₁ := ContMDiff.prodMk sfg sfv let F₂ : (TangentBundle I G × TangentBundle I G) → TangentBundle (I.prod I) (G × G) := (equivTangentBundleProd I G I G).symm have S₂ : ContMDiff (I.tangent.prod I.tangent) (I.prod I).tangent (minSmoothness 𝕜 2) F₂ := contMDiff_equivTangentBundleProd_symm let F₃ : TangentBundle (I.prod I) (G × G) → TangentBundle I G := tangentMap (I.prod I) I (fun (p : G × G) ↦ p.1 * p.2) have S₃ : ContMDiff (I.prod I).tangent I.tangent (minSmoothness 𝕜 2) F₃ := by apply ContMDiff.contMDiff_tangentMap _ (m := minSmoothness 𝕜 2) le_rfl rw [A] exact contMDiff_mul I (minSmoothness 𝕜 3) let S := (S₃.comp S₂).comp S₁ convert S with g · simp [F₁, F₂, F₃, fg, fv] · simp only [comp_apply, tangentMap, F₃, F₂, F₁, fg, fv] rw [mfderiv_prod_eq_add_apply ((contMDiff_mul I (minSmoothness 𝕜 3)).mdifferentiableAt M)] simp [mulInvariantVectorField] @[to_additive] theorem contMDiffAt_mulInvariantVectorField (v : GroupLieAlgebra I G) {g : G} : ContMDiffAt I I.tangent (minSmoothness 𝕜 2) (fun (g : G) ↦ (mulInvariantVectorField v g : TangentBundle I G)) g := (contMDiff_mulInvariantVectorField v).contMDiffAt @[to_additive] theorem mdifferentiable_mulInvariantVectorField (v : GroupLieAlgebra I G) : MDifferentiable I I.tangent (fun (g : G) ↦ (mulInvariantVectorField v g : TangentBundle I G)) := (contMDiff_mulInvariantVectorField v).mdifferentiable (le_trans (by simp) le_minSmoothness) @[to_additive] theorem mdifferentiableAt_mulInvariantVectorField (v : GroupLieAlgebra I G) {g : G} : MDifferentiableAt I I.tangent (fun (g : G) ↦ (mulInvariantVectorField v g : TangentBundle I G)) g := (contMDiffAt_mulInvariantVectorField v).mdifferentiableAt (le_trans (by simp) le_minSmoothness) open VectorField variable [CompleteSpace E] /-- The invariant vector field associated to the value at the identity of the Lie bracket of two invariant vector fields, is everywhere the Lie bracket of the invariant vector fields. -/ @[to_additive /-- The invariant vector field associated to the value at zero of the Lie bracket of two invariant vector fields, is everywhere the Lie bracket of the invariant vector fields. -/] lemma mulInvariantVector_mlieBracket (v w : GroupLieAlgebra I G) : mulInvariantVectorField (mlieBracket I (mulInvariantVectorField v) (mulInvariantVectorField w) 1) = mlieBracket I (mulInvariantVectorField v) (mulInvariantVectorField w) := by ext g rw [mulInvariantVectorField_eq_mpullback, mpullback_mlieBracket (n := minSmoothness 𝕜 3), mpullback_mulInvariantVectorField, mpullback_mulInvariantVectorField] · exact mdifferentiableAt_mulInvariantVectorField _ · exact mdifferentiableAt_mulInvariantVectorField _ · exact contMDiffAt_mul_left · exact minSmoothness_monotone (by norm_cast) /-- The tangent space at the identity of a Lie group is a Lie ring, for the bracket given by the Lie bracket of invariant vector fields. -/ @[to_additive /-- The tangent space at the identity of an additive Lie group is a Lie ring, for the bracket given by the Lie bracket of invariant vector fields. -/] noncomputable instance : LieRing (GroupLieAlgebra I G) where add_lie u v w := by simp only [GroupLieAlgebra.bracket_def, mulInvariantVectorField_add] rw [mlieBracket_add_left] · exact mdifferentiableAt_mulInvariantVectorField _ · exact mdifferentiableAt_mulInvariantVectorField _ lie_add u v w := by simp only [GroupLieAlgebra.bracket_def, mulInvariantVectorField_add] rw [mlieBracket_add_right] · exact mdifferentiableAt_mulInvariantVectorField _ · exact mdifferentiableAt_mulInvariantVectorField _ lie_self v := by simp [GroupLieAlgebra.bracket_def] leibniz_lie u v w := by simp only [GroupLieAlgebra.bracket_def, mulInvariantVector_mlieBracket] apply leibniz_identity_mlieBracket_apply <;> exact contMDiff_mulInvariantVectorField _ _ /- `to_additive` fails on the next instance, as it tries to additivize `smul` while it shouldn't. Therefore, we state and prove by hand the additive version. -/ /-- The tangent space at the identity of an additive Lie group is a Lie algebra, for the bracket given by the Lie bracket of invariant vector fields. -/ noncomputable instance instLieAlgebraAddGroupLieAlgebra {G : Type*} [TopologicalSpace G] [ChartedSpace H G] [AddGroup G] [LieAddGroup I (minSmoothness 𝕜 3) G] : LieAlgebra 𝕜 (AddGroupLieAlgebra I G) where lie_smul c v w := by simp only [AddGroupLieAlgebra.bracket_def, addInvariantVectorField_smul] rw [mlieBracket_const_smul_right] exact mdifferentiableAt_addInvariantVectorField _ /-- The tangent space at the identity of a Lie group is a Lie algebra, for the bracket given by the Lie bracket of invariant vector fields. -/ noncomputable instance instLieAlgebraGroupLieAlgebra : LieAlgebra 𝕜 (GroupLieAlgebra I G) where lie_smul c v w := by simp only [GroupLieAlgebra.bracket_def, mulInvariantVectorField_smul] rw [mlieBracket_const_smul_right] exact mdifferentiableAt_mulInvariantVectorField _ end LieGroup
Basic.lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.Group.Semiconj.Defs import Mathlib.Algebra.Group.Basic /-! # Lemmas about semiconjugate elements of a group -/ assert_not_exists MonoidWithZero DenselyOrdered namespace SemiconjBy variable {G : Type*} section DivisionMonoid variable [DivisionMonoid G] {a x y : G} @[to_additive (attr := simp)] theorem inv_inv_symm_iff : SemiconjBy a⁻¹ x⁻¹ y⁻¹ ↔ SemiconjBy a y x := by simp_rw [SemiconjBy, ← mul_inv_rev, inv_inj, eq_comm] @[to_additive] alias ⟨_, inv_inv_symm⟩ := inv_inv_symm_iff end DivisionMonoid section Group variable [Group G] {a x y : G} @[to_additive (attr := simp)] lemma inv_symm_left_iff : SemiconjBy a⁻¹ y x ↔ SemiconjBy a x y := by simp_rw [SemiconjBy, eq_mul_inv_iff_mul_eq, mul_assoc, inv_mul_eq_iff_eq_mul, eq_comm] @[to_additive] alias ⟨_, inv_symm_left⟩ := inv_symm_left_iff @[to_additive (attr := simp)] lemma inv_right_iff : SemiconjBy a x⁻¹ y⁻¹ ↔ SemiconjBy a x y := by rw [← inv_symm_left_iff, inv_inv_symm_iff] @[to_additive] alias ⟨_, inv_right⟩ := inv_right_iff @[to_additive (attr := simp)] lemma zpow_right (h : SemiconjBy a x y) : ∀ m : ℤ, SemiconjBy a (x ^ m) (y ^ m) | (n : ℕ) => by simp [zpow_natCast, h.pow_right n] | .negSucc n => by simp only [zpow_negSucc, inv_right_iff] apply pow_right h variable (a) in @[to_additive] lemma eq_one_iff (h : SemiconjBy a x y) : x = 1 ↔ y = 1 := by rw [← conj_eq_one_iff (a := a) (b := x), h.eq, mul_inv_cancel_right] end Group end SemiconjBy
seq.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat. (******************************************************************************) (* The seq type is the ssreflect type for sequences; it is an alias for the *) (* standard Coq list type. The ssreflect library equips it with many *) (* operations, as well as eqType and predType (and, later, choiceType) *) (* structures. The operations are geared towards reflection: they generally *) (* expect and provide boolean predicates, e.g., the membership predicate *) (* expects an eqType. To avoid any confusion we do not Import the Coq List *) (* module. *) (* As there is no true subtyping in Coq, we don't use a type for non-empty *) (* sequences; rather, we pass explicitly the head and tail of the sequence. *) (* The empty sequence is especially bothersome for subscripting, since it *) (* forces us to pass a default value. This default value can often be hidden *) (* by a notation. *) (* Here is the list of seq operations: *) (* ** Constructors: *) (* seq T == the type of sequences of items of type T. *) (* bitseq == seq bool. *) (* [::], nil, Nil T == the empty sequence (of type T). *) (* x :: s, cons x s, Cons T x s == the sequence x followed by s (of type T). *) (* [:: x] == the singleton sequence. *) (* [:: x_0; ...; x_n] == the explicit sequence of the x_i. *) (* [:: x_0, ..., x_n & s] == the sequence of the x_i, followed by s. *) (* rcons s x == the sequence s, followed by x. *) (* All of the above, except rcons, can be used in patterns. We define a view *) (* lastP and an induction principle last_ind that can be used to decompose *) (* or traverse a sequence in a right to left order. The view lemma lastP has *) (* a dependent family type, so the ssreflect tactic case/lastP: p => [|p' x] *) (* will generate two subgoals in which p has been replaced by [::] and by *) (* rcons p' x, respectively. *) (* ** Factories: *) (* nseq n x == a sequence of n x's. *) (* ncons n x s == a sequence of n x's, followed by s. *) (* seqn n x_0 ... x_n-1 == the sequence of the x_i; can be partially applied. *) (* iota m n == the sequence m, m + 1, ..., m + n - 1. *) (* mkseq f n == the sequence f 0, f 1, ..., f (n - 1). *) (* ** Sequential access: *) (* head x0 s == the head (zero'th item) of s if s is non-empty, else x0. *) (* ohead s == None if s is empty, else Some x when the head of s is x. *) (* behead s == s minus its head, i.e., s' if s = x :: s', else [::]. *) (* last x s == the last element of x :: s (which is non-empty). *) (* belast x s == x :: s minus its last item. *) (* ** Dimensions: *) (* size s == the number of items (length) in s. *) (* shape ss == the sequence of sizes of the items of the sequence of *) (* sequences ss. *) (* ** Random access: *) (* nth x0 s i == the item i of s (numbered from 0), or x0 if s does *) (* not have at least i+1 items (i.e., size x <= i) *) (* s`_i == standard notation for nth x0 s i for a default x0, *) (* e.g., 0 for rings. *) (* onth s i == Some x if x is the i^th idem of s (numbered from 0), *) (* or None if size s <= i) *) (* set_nth x0 s i y == s where item i has been changed to y; if s does not *) (* have an item i, it is first padded with copies of x0 *) (* to size i+1. *) (* incr_nth s i == the nat sequence s with item i incremented (s is *) (* first padded with 0's to size i+1, if needed). *) (* ** Predicates: *) (* nilp s <=> s is [::]. *) (* := (size s == 0). *) (* x \in s == x appears in s (this requires an eqType for T). *) (* index x s == the first index at which x appears in s, or size s if *) (* x \notin s. *) (* has a s <=> a holds for some item in s, where a is an applicative *) (* bool predicate. *) (* all a s <=> a holds for all items in s. *) (* 'has_aP <-> the view reflect (exists2 x, x \in s & A x) (has a s), *) (* where aP x : reflect (A x) (a x). *) (* 'all_aP <=> the view for reflect {in s, forall x, A x} (all a s). *) (* all2 r s t <=> the (bool) relation r holds for all _respective_ items *) (* in s and t, which must also have the same size, i.e., *) (* for s := [:: x1; ...; x_m] and t := [:: y1; ...; y_n], *) (* the condition [&& r x_1 y_1, ..., r x_n y_n & m == n]. *) (* find p s == the index of the first item in s for which p holds, *) (* or size s if no such item is found. *) (* count p s == the number of items of s for which p holds. *) (* count_mem x s == the multiplicity of x in s, i.e., count (pred1 x) s. *) (* tally s == a tally of s, i.e., a sequence of (item, multiplicity) *) (* pairs for all items in sequence s (without duplicates). *) (* incr_tally bs x == increment the multiplicity of x in the tally bs, or add *) (* x with multiplicity 1 at then end if x is not in bs. *) (* bs \is a wf_tally <=> bs is well-formed tally, with no duplicate items or *) (* null multiplicities. *) (* tally_seq bs == the expansion of a tally bs into a sequence where each *) (* (x, n) pair expands into a sequence of n x's. *) (* constant s <=> all items in s are identical (trivial if s = [::]). *) (* uniq s <=> all the items in s are pairwise different. *) (* subseq s1 s2 <=> s1 is a subsequence of s2, i.e., s1 = mask m s2 for *) (* some m : bitseq (see below). *) (* infix s1 s2 <=> s1 is a contiguous subsequence of s2, i.e., *) (* s ++ s1 ++ s' = s2 for some sequences s, s'. *) (* prefix s1 s2 <=> s1 is a subchain of s2 appearing at the beginning *) (* of s2. *) (* suffix s1 s2 <=> s1 is a subchain of s2 appearing at the end of s2. *) (* infix_index s1 s2 <=> the first index at which s1 appears in s2, *) (* or (size s2).+1 if infix s1 s2 is false. *) (* perm_eq s1 s2 <=> s2 is a permutation of s1, i.e., s1 and s2 have the *) (* items (with the same repetitions), but possibly in a *) (* different order. *) (* perm_eql s1 s2 <-> s1 and s2 behave identically on the left of perm_eq. *) (* perm_eqr s1 s2 <-> s1 and s2 behave identically on the right of perm_eq. *) (* --> These left/right transitive versions of perm_eq make it easier to *) (* chain a sequence of equivalences. *) (* permutations s == a duplicate-free list of all permutations of s. *) (* ** Filtering: *) (* filter p s == the subsequence of s consisting of all the items *) (* for which the (boolean) predicate p holds. *) (* rem x s == the subsequence of s, where the first occurrence *) (* of x has been removed (compare filter (predC1 x) s *) (* where ALL occurrences of x are removed). *) (* undup s == the subsequence of s containing only the first *) (* occurrence of each item in s, i.e., s with all *) (* duplicates removed. *) (* mask m s == the subsequence of s selected by m : bitseq, with *) (* item i of s selected by bit i in m (extra items or *) (* bits are ignored. *) (* ** Surgery: *) (* s1 ++ s2, cat s1 s2 == the concatenation of s1 and s2. *) (* take n s == the sequence containing only the first n items of s *) (* (or all of s if size s <= n). *) (* drop n s == s minus its first n items ([::] if size s <= n) *) (* rot n s == s rotated left n times (or s if size s <= n). *) (* := drop n s ++ take n s *) (* rotr n s == s rotated right n times (or s if size s <= n). *) (* rev s == the (linear time) reversal of s. *) (* catrev s1 s2 == the reversal of s1 followed by s2 (this is the *) (* recursive form of rev). *) (* ** Dependent iterator: for s : seq S and t : S -> seq T *) (* [seq E | x <- s, y <- t] := flatten [seq [seq E | x <- t] | y <- s] *) (* == the sequence of all the f x y, with x and y drawn from *) (* s and t, respectively, in row-major order, *) (* and where t is possibly dependent in elements of s *) (* allpairs_dep f s t := self expanding definition for *) (* [seq f x y | x <- s, y <- t y] *) (* ** Iterators: for s == [:: x_1, ..., x_n], t == [:: y_1, ..., y_m], *) (* allpairs f s t := same as allpairs_dep but where t is non dependent, *) (* i.e. self expanding definition for *) (* [seq f x y | x <- s, y <- t] *) (* := [:: f x_1 y_1; ...; f x_1 y_m; f x_2 y_1; ...; f x_n y_m] *) (* allrel r xs ys := all [pred x | all (r x) ys] xs *) (* <=> r x y holds whenever x is in xs and y is in ys *) (* all2rel r xs := allrel r xs xs *) (* <=> the proposition r x y holds for all possible x, y in xs.*) (* pairwise r xs <=> the relation r holds for any i-th and j-th element of *) (* xs such that i < j. *) (* map f s == the sequence [:: f x_1, ..., f x_n]. *) (* pmap pf s == the sequence [:: y_i1, ..., y_ik] where i1 < ... < ik, *) (* pf x_i = Some y_i, and pf x_j = None iff j is not in *) (* {i1, ..., ik}. *) (* foldr f a s == the right fold of s by f (i.e., the natural iterator). *) (* := f x_1 (f x_2 ... (f x_n a)) *) (* sumn s == x_1 + (x_2 + ... + (x_n + 0)) (when s : seq nat). *) (* foldl f a s == the left fold of s by f. *) (* := f (f ... (f a x_1) ... x_n-1) x_n *) (* scanl f a s == the sequence of partial accumulators of foldl f a s. *) (* := [:: f a x_1; ...; foldl f a s] *) (* pairmap f a s == the sequence of f applied to consecutive items in a :: s. *) (* := [:: f a x_1; f x_1 x_2; ...; f x_n-1 x_n] *) (* zip s t == itemwise pairing of s and t (dropping any extra items). *) (* := [:: (x_1, y_1); ...; (x_mn, y_mn)] with mn = minn n m. *) (* unzip1 s == [:: (x_1).1; ...; (x_n).1] when s : seq (S * T). *) (* unzip2 s == [:: (x_1).2; ...; (x_n).2] when s : seq (S * T). *) (* flatten s == x_1 ++ ... ++ x_n ++ [::] when s : seq (seq T). *) (* reshape r s == s reshaped into a sequence of sequences whose sizes are *) (* given by r (truncating if s is too long or too short). *) (* := [:: [:: x_1; ...; x_r1]; *) (* [:: x_(r1 + 1); ...; x_(r0 + r1)]; *) (* ...; *) (* [:: x_(r1 + ... + r(k-1) + 1); ...; x_(r0 + ... rk)]] *) (* flatten_index sh r c == the index, in flatten ss, of the item of indexes *) (* (r, c) in any sequence of sequences ss of shape sh *) (* := sh_1 + sh_2 + ... + sh_r + c *) (* reshape_index sh i == the index, in reshape sh s, of the sequence *) (* containing the i-th item of s. *) (* reshape_offset sh i == the offset, in the (reshape_index sh i)-th *) (* sequence of reshape sh s of the i-th item of s *) (* ** Notation for manifest comprehensions: *) (* [seq x <- s | C] := filter (fun x => C) s. *) (* [seq E | x <- s] := map (fun x => E) s. *) (* [seq x <- s | C1 & C2] := [seq x <- s | C1 && C2]. *) (* [seq E | x <- s & C] := [seq E | x <- [seq x | C]]. *) (* --> The above allow optional type casts on the eigenvariables, as in *) (* [seq x : T <- s | C] or [seq E | x : T <- s, y : U <- t]. The cast may be *) (* needed as type inference considers E or C before s. *) (* We are quite systematic in providing lemmas to rewrite any composition *) (* of two operations. "rev", whose simplifications are not natural, is *) (* protected with simpl never. *) (* ** The following are equivalent: *) (* [<-> P0; P1; ..; Pn] <-> P0, P1, ..., Pn are all equivalent. *) (* := P0 -> P1 -> ... -> Pn -> P0 *) (* if T : [<-> P0; P1; ..; Pn] is such an equivalence, and i, j are in nat *) (* then T i j is a proof of the equivalence Pi <-> Pj between Pi and Pj; *) (* when i (resp. j) is out of bounds, Pi (resp. Pj) defaults to P0. *) (* The tactic tfae splits the goal into n+1 implications to prove. *) (* An example of use can be found in fingraph theorem orbitPcycle. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope seq_scope. Reserved Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" (format "[ '<->' '[' P0 ; '/' P1 ; '/' .. ; '/' Pn ']' ]"). Delimit Scope seq_scope with SEQ. Open Scope seq_scope. (* Inductive seq (T : Type) : Type := Nil | Cons of T & seq T. *) Notation seq := list. Bind Scope seq_scope with list. Arguments cons {T%_type} x s%_SEQ : rename. Arguments nil {T%_type} : rename. Notation Cons T := (@cons T) (only parsing). Notation Nil T := (@nil T) (only parsing). (* As :: and ++ are (improperly) declared in Init.datatypes, we only rebind *) (* them here. *) Infix "::" := cons : seq_scope. Notation "[ :: ]" := nil (format "[ :: ]") : seq_scope. Notation "[ :: x1 ]" := (x1 :: [::]) (format "[ :: x1 ]") : seq_scope. Notation "[ :: x & s ]" := (x :: s) (only parsing) : seq_scope. Notation "[ :: x1 , x2 , .. , xn & s ]" := (x1 :: x2 :: .. (xn :: s) ..) (format "'[hv' [ :: '[' x1 , '/' x2 , '/' .. , '/' xn ']' '/ ' & s ] ']'" ) : seq_scope. Notation "[ :: x1 ; x2 ; .. ; xn ]" := (x1 :: x2 :: .. [:: xn] ..) (format "[ :: '[' x1 ; '/' x2 ; '/' .. ; '/' xn ']' ]" ) : seq_scope. Section Sequences. Variable n0 : nat. (* numerical parameter for take, drop et al *) Variable T : Type. (* must come before the implicit Type *) Variable x0 : T. (* default for head/nth *) Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint size s := if s is _ :: s' then (size s').+1 else 0. Lemma size0nil s : size s = 0 -> s = [::]. Proof. by case: s. Qed. Definition nilp s := size s == 0. Lemma nilP s : reflect (s = [::]) (nilp s). Proof. by case: s => [|x s]; constructor. Qed. Definition ohead s := if s is x :: _ then Some x else None. Definition head s := if s is x :: _ then x else x0. Definition behead s := if s is _ :: s' then s' else [::]. Lemma size_behead s : size (behead s) = (size s).-1. Proof. by case: s. Qed. (* Factories *) Definition ncons n x := iter n (cons x). Definition nseq n x := ncons n x [::]. Lemma size_ncons n x s : size (ncons n x s) = n + size s. Proof. by elim: n => //= n ->. Qed. Lemma size_nseq n x : size (nseq n x) = n. Proof. by rewrite size_ncons addn0. Qed. (* n-ary, dependently typed constructor. *) Fixpoint seqn_type n := if n is n'.+1 then T -> seqn_type n' else seq T. Fixpoint seqn_rec f n : seqn_type n := if n is n'.+1 return seqn_type n then fun x => seqn_rec (fun s => f (x :: s)) n' else f [::]. Definition seqn := seqn_rec id. (* Sequence catenation "cat". *) Fixpoint cat s1 s2 := if s1 is x :: s1' then x :: s1' ++ s2 else s2 where "s1 ++ s2" := (cat s1 s2) : seq_scope. Lemma cat0s s : [::] ++ s = s. Proof. by []. Qed. Lemma cat1s x s : [:: x] ++ s = x :: s. Proof. by []. Qed. Lemma cat_cons x s1 s2 : (x :: s1) ++ s2 = x :: s1 ++ s2. Proof. by []. Qed. Lemma cat_nseq n x s : nseq n x ++ s = ncons n x s. Proof. by elim: n => //= n ->. Qed. Lemma nseqD n1 n2 x : nseq (n1 + n2) x = nseq n1 x ++ nseq n2 x. Proof. by rewrite cat_nseq /nseq /ncons iterD. Qed. Lemma cats0 s : s ++ [::] = s. Proof. by elim: s => //= x s ->. Qed. Lemma catA s1 s2 s3 : s1 ++ s2 ++ s3 = (s1 ++ s2) ++ s3. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma size_cat s1 s2 : size (s1 ++ s2) = size s1 + size s2. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma cat_nilp s1 s2 : nilp (s1 ++ s2) = nilp s1 && nilp s2. Proof. by case: s1. Qed. (* last, belast, rcons, and last induction. *) Fixpoint rcons s z := if s is x :: s' then x :: rcons s' z else [:: z]. Lemma rcons_cons x s z : rcons (x :: s) z = x :: rcons s z. Proof. by []. Qed. Lemma cats1 s z : s ++ [:: z] = rcons s z. Proof. by elim: s => //= x s ->. Qed. Fixpoint last x s := if s is x' :: s' then last x' s' else x. Fixpoint belast x s := if s is x' :: s' then x :: (belast x' s') else [::]. Lemma lastI x s : x :: s = rcons (belast x s) (last x s). Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cons x y s : last x (y :: s) = last y s. Proof. by []. Qed. Lemma size_rcons s x : size (rcons s x) = (size s).+1. Proof. by rewrite -cats1 size_cat addnC. Qed. Lemma size_belast x s : size (belast x s) = size s. Proof. by elim: s x => [|y s IHs] x //=; rewrite IHs. Qed. Lemma last_cat x s1 s2 : last x (s1 ++ s2) = last (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma last_rcons x s z : last x (rcons s z) = z. Proof. by rewrite -cats1 last_cat. Qed. Lemma belast_cat x s1 s2 : belast x (s1 ++ s2) = belast x s1 ++ belast (last x s1) s2. Proof. by elim: s1 x => [|y s1 IHs] x //=; rewrite IHs. Qed. Lemma belast_rcons x s z : belast x (rcons s z) = x :: s. Proof. by rewrite lastI -!cats1 belast_cat. Qed. Lemma cat_rcons x s1 s2 : rcons s1 x ++ s2 = s1 ++ x :: s2. Proof. by rewrite -cats1 -catA. Qed. Lemma rcons_cat x s1 s2 : rcons (s1 ++ s2) x = s1 ++ rcons s2 x. Proof. by rewrite -!cats1 catA. Qed. Variant last_spec : seq T -> Type := | LastNil : last_spec [::] | LastRcons s x : last_spec (rcons s x). Lemma lastP s : last_spec s. Proof. case: s => [|x s]; [left | rewrite lastI; right]. Qed. Lemma last_ind P : P [::] -> (forall s x, P s -> P (rcons s x)) -> forall s, P s. Proof. move=> Hnil Hlast s; rewrite -(cat0s s). elim: s [::] Hnil => [|x s2 IHs] s1 Hs1; first by rewrite cats0. by rewrite -cat_rcons; apply/IHs/Hlast. Qed. (* Sequence indexing. *) Fixpoint nth s n {struct n} := if s is x :: s' then if n is n'.+1 then @nth s' n' else x else x0. Fixpoint set_nth s n y {struct n} := if s is x :: s' then if n is n'.+1 then x :: @set_nth s' n' y else y :: s' else ncons n x0 [:: y]. Lemma nth0 s : nth s 0 = head s. Proof. by []. Qed. Lemma nth_default s n : size s <= n -> nth s n = x0. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma if_nth s b n : b || (size s <= n) -> (if b then nth s n else x0) = nth s n. Proof. by case: leqP; case: ifP => //= *; rewrite nth_default. Qed. Lemma nth_nil n : nth [::] n = x0. Proof. by case: n. Qed. Lemma nth_seq1 n x : nth [:: x] n = if n == 0 then x else x0. Proof. by case: n => [|[]]. Qed. Lemma last_nth x s : last x s = nth (x :: s) (size s). Proof. by elim: s x => [|y s IHs] x /=. Qed. Lemma nth_last s : nth s (size s).-1 = last x0 s. Proof. by case: s => //= x s; rewrite last_nth. Qed. Lemma nth_behead s n : nth (behead s) n = nth s n.+1. Proof. by case: s n => [|x s] [|n]. Qed. Lemma nth_cat s1 s2 n : nth (s1 ++ s2) n = if n < size s1 then nth s1 n else nth s2 (n - size s1). Proof. by elim: s1 n => [|x s1 IHs] []. Qed. Lemma nth_rcons s x n : nth (rcons s x) n = if n < size s then nth s n else if n == size s then x else x0. Proof. by elim: s n => [|y s IHs] [] //=; apply: nth_nil. Qed. Lemma nth_rcons_default s i : nth (rcons s x0) i = nth s i. Proof. by rewrite nth_rcons; case: ltngtP => //[/ltnW ?|->]; rewrite nth_default. Qed. Lemma nth_ncons m x s n : nth (ncons m x s) n = if n < m then x else nth s (n - m). Proof. by elim: m n => [|m IHm] []. Qed. Lemma nth_nseq m x n : nth (nseq m x) n = (if n < m then x else x0). Proof. by elim: m n => [|m IHm] []. Qed. Lemma eq_from_nth s1 s2 : size s1 = size s2 -> (forall i, i < size s1 -> nth s1 i = nth s2 i) -> s1 = s2. Proof. elim: s1 s2 => [|x1 s1 IHs1] [|x2 s2] //= [eq_sz] eq_s12. by rewrite [x1](eq_s12 0) // (IHs1 s2) // => i; apply: (eq_s12 i.+1). Qed. Lemma size_set_nth s n y : size (set_nth s n y) = maxn n.+1 (size s). Proof. rewrite maxnC; elim: s n => [|x s IHs] [|n] //=. - by rewrite size_ncons addn1. - by rewrite IHs maxnSS. Qed. Lemma set_nth_nil n y : set_nth [::] n y = ncons n x0 [:: y]. Proof. by case: n. Qed. Lemma nth_set_nth s n y : nth (set_nth s n y) =1 [eta nth s with n |-> y]. Proof. elim: s n => [|x s IHs] [|n] [|m] //=; rewrite ?nth_nil ?IHs // nth_ncons eqSS. case: ltngtP => // [lt_nm | ->]; last by rewrite subnn. by rewrite nth_default // subn_gt0. Qed. Lemma set_set_nth s n1 y1 n2 y2 (s2 := set_nth s n2 y2) : set_nth (set_nth s n1 y1) n2 y2 = if n1 == n2 then s2 else set_nth s2 n1 y1. Proof. have [-> | ne_n12] := eqVneq. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnA maxnn. by do 2!rewrite !nth_set_nth /=; case: eqP. apply: eq_from_nth => [|i _]; first by rewrite !size_set_nth maxnCA. by do 2!rewrite !nth_set_nth /=; case: eqP => // ->; case: eqVneq ne_n12. Qed. (* find, count, has, all. *) Section SeqFind. Variable a : pred T. Fixpoint find s := if s is x :: s' then if a x then 0 else (find s').+1 else 0. Fixpoint filter s := if s is x :: s' then if a x then x :: filter s' else filter s' else [::]. Fixpoint count s := if s is x :: s' then a x + count s' else 0. Fixpoint has s := if s is x :: s' then a x || has s' else false. Fixpoint all s := if s is x :: s' then a x && all s' else true. Lemma size_filter s : size (filter s) = count s. Proof. by elim: s => //= x s <-; case (a x). Qed. Lemma has_count s : has s = (0 < count s). Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma size_filter_gt0 s : (size (filter s) > 0) = (has s). Proof. by rewrite size_filter -has_count. Qed. Lemma count_size s : count s <= size s. Proof. by elim: s => //= x s; case: (a x); last apply: leqW. Qed. Lemma all_count s : all s = (count s == size s). Proof. elim: s => //= x s; case: (a x) => _ //=. by rewrite add0n eqn_leq andbC ltnNge count_size. Qed. Lemma filter_all s : all (filter s). Proof. by elim: s => //= x s IHs; case: ifP => //= ->. Qed. Lemma all_filterP s : reflect (filter s = s) (all s). Proof. apply: (iffP idP) => [| <-]; last exact: filter_all. by elim: s => //= x s IHs /andP[-> Hs]; rewrite IHs. Qed. Lemma filter_id s : filter (filter s) = filter s. Proof. by apply/all_filterP; apply: filter_all. Qed. Lemma has_find s : has s = (find s < size s). Proof. by elim: s => //= x s IHs; case (a x); rewrite ?leqnn. Qed. Lemma find_size s : find s <= size s. Proof. by elim: s => //= x s IHs; case (a x). Qed. Lemma find_cat s1 s2 : find (s1 ++ s2) = if has s1 then find s1 else size s1 + find s2. Proof. by elim: s1 => //= x s1 IHs; case: (a x) => //; rewrite IHs (fun_if succn). Qed. Lemma has_nil : has [::] = false. Proof. by []. Qed. Lemma has_seq1 x : has [:: x] = a x. Proof. exact: orbF. Qed. Lemma has_nseq n x : has (nseq n x) = (0 < n) && a x. Proof. by elim: n => //= n ->; apply: andKb. Qed. Lemma has_seqb (b : bool) x : has (nseq b x) = b && a x. Proof. by rewrite has_nseq lt0b. Qed. Lemma all_nil : all [::] = true. Proof. by []. Qed. Lemma all_seq1 x : all [:: x] = a x. Proof. exact: andbT. Qed. Lemma all_nseq n x : all (nseq n x) = (n == 0) || a x. Proof. by elim: n => //= n ->; apply: orKb. Qed. Lemma all_nseqb (b : bool) x : all (nseq b x) = b ==> a x. Proof. by rewrite all_nseq eqb0 implybE. Qed. Lemma filter_nseq n x : filter (nseq n x) = nseq (a x * n) x. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma count_nseq n x : count (nseq n x) = a x * n. Proof. by rewrite -size_filter filter_nseq size_nseq. Qed. Lemma find_nseq n x : find (nseq n x) = ~~ a x * n. Proof. by elim: n => /= [|n ->]; case: (a x). Qed. Lemma nth_find s : has s -> a (nth s (find s)). Proof. by elim: s => //= x s IHs; case a_x: (a x). Qed. Lemma before_find s i : i < find s -> a (nth s i) = false. Proof. by elim: s i => //= x s IHs; case: ifP => // a'x [|i] // /(IHs i). Qed. Lemma hasNfind s : ~~ has s -> find s = size s. Proof. by rewrite has_find; case: ltngtP (find_size s). Qed. Lemma filter_cat s1 s2 : filter (s1 ++ s2) = filter s1 ++ filter s2. Proof. by elim: s1 => //= x s1 ->; case (a x). Qed. Lemma filter_rcons s x : filter (rcons s x) = if a x then rcons (filter s) x else filter s. Proof. by rewrite -!cats1 filter_cat /=; case (a x); rewrite /= ?cats0. Qed. Lemma count_cat s1 s2 : count (s1 ++ s2) = count s1 + count s2. Proof. by rewrite -!size_filter filter_cat size_cat. Qed. Lemma has_cat s1 s2 : has (s1 ++ s2) = has s1 || has s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs orbA. Qed. Lemma has_rcons s x : has (rcons s x) = a x || has s. Proof. by rewrite -cats1 has_cat has_seq1 orbC. Qed. Lemma all_cat s1 s2 : all (s1 ++ s2) = all s1 && all s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs andbA. Qed. Lemma all_rcons s x : all (rcons s x) = a x && all s. Proof. by rewrite -cats1 all_cat all_seq1 andbC. Qed. End SeqFind. Lemma find_pred0 s : find pred0 s = size s. Proof. by []. Qed. Lemma find_predT s : find predT s = 0. Proof. by case: s. Qed. Lemma eq_find a1 a2 : a1 =1 a2 -> find a1 =1 find a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_filter a1 a2 : a1 =1 a2 -> filter a1 =1 filter a2. Proof. by move=> Ea; elim=> //= x s IHs; rewrite Ea IHs. Qed. Lemma eq_count a1 a2 : a1 =1 a2 -> count a1 =1 count a2. Proof. by move=> Ea s; rewrite -!size_filter (eq_filter Ea). Qed. Lemma eq_has a1 a2 : a1 =1 a2 -> has a1 =1 has a2. Proof. by move=> Ea s; rewrite !has_count (eq_count Ea). Qed. Lemma eq_all a1 a2 : a1 =1 a2 -> all a1 =1 all a2. Proof. by move=> Ea s; rewrite !all_count (eq_count Ea). Qed. Lemma all_filter (p q : pred T) xs : all p (filter q xs) = all [pred i | q i ==> p i] xs. Proof. by elim: xs => //= x xs <-; case: (q x). Qed. Section SubPred. Variable (a1 a2 : pred T). Hypothesis s12 : subpred a1 a2. Lemma sub_find s : find a2 s <= find a1 s. Proof. by elim: s => //= x s IHs; case: ifP => // /(contraFF (@s12 x))->. Qed. Lemma sub_has s : has a1 s -> has a2 s. Proof. by rewrite !has_find; apply: leq_ltn_trans (sub_find s). Qed. Lemma sub_count s : count a1 s <= count a2 s. Proof. by elim: s => //= x s; apply: leq_add; case a1x: (a1 x); rewrite // s12. Qed. Lemma sub_all s : all a1 s -> all a2 s. Proof. by rewrite !all_count !eqn_leq !count_size => /leq_trans-> //; apply: sub_count. Qed. End SubPred. Lemma filter_pred0 s : filter pred0 s = [::]. Proof. by elim: s. Qed. Lemma filter_predT s : filter predT s = s. Proof. by elim: s => //= x s ->. Qed. Lemma filter_predI a1 a2 s : filter (predI a1 a2) s = filter a1 (filter a2 s). Proof. by elim: s => //= x s ->; rewrite andbC; case: (a2 x). Qed. Lemma count_pred0 s : count pred0 s = 0. Proof. by rewrite -size_filter filter_pred0. Qed. Lemma count_predT s : count predT s = size s. Proof. by rewrite -size_filter filter_predT. Qed. Lemma count_predUI a1 a2 s : count (predU a1 a2) s + count (predI a1 a2) s = count a1 s + count a2 s. Proof. elim: s => //= x s IHs; rewrite /= addnACA [RHS]addnACA IHs. by case: (a1 x) => //; rewrite addn0. Qed. Lemma count_predC a s : count a s + count (predC a) s = size s. Proof. by elim: s => //= x s IHs; rewrite addnACA IHs; case: (a _). Qed. Lemma count_filter a1 a2 s : count a1 (filter a2 s) = count (predI a1 a2) s. Proof. by rewrite -!size_filter filter_predI. Qed. Lemma has_pred0 s : has pred0 s = false. Proof. by rewrite has_count count_pred0. Qed. Lemma has_predT s : has predT s = (0 < size s). Proof. by rewrite has_count count_predT. Qed. Lemma has_predC a s : has (predC a) s = ~~ all a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma has_predU a1 a2 s : has (predU a1 a2) s = has a1 s || has a2 s. Proof. by elim: s => //= x s ->; rewrite -!orbA; do !bool_congr. Qed. Lemma all_pred0 s : all pred0 s = (size s == 0). Proof. by rewrite all_count count_pred0 eq_sym. Qed. Lemma all_predT s : all predT s. Proof. by rewrite all_count count_predT. Qed. Lemma allT (a : pred T) s : (forall x, a x) -> all a s. Proof. by move/eq_all->; apply/all_predT. Qed. Lemma all_predC a s : all (predC a) s = ~~ has a s. Proof. by elim: s => //= x s ->; case (a x). Qed. Lemma all_predI a1 a2 s : all (predI a1 a2) s = all a1 s && all a2 s. Proof. apply: (can_inj negbK); rewrite negb_and -!has_predC -has_predU. by apply: eq_has => x; rewrite /= negb_and. Qed. (* Surgery: drop, take, rot, rotr. *) Fixpoint drop n s {struct s} := match s, n with | _ :: s', n'.+1 => drop n' s' | _, _ => s end. Lemma drop_behead : drop n0 =1 iter n0 behead. Proof. by elim: n0 => [|n IHn] [|x s] //; rewrite iterSr -IHn. Qed. Lemma drop0 s : drop 0 s = s. Proof. by case: s. Qed. Lemma drop1 : drop 1 =1 behead. Proof. by case=> [|x [|y s]]. Qed. Lemma drop_oversize n s : size s <= n -> drop n s = [::]. Proof. by elim: s n => [|x s IHs] []. Qed. Lemma drop_size s : drop (size s) s = [::]. Proof. by rewrite drop_oversize // leqnn. Qed. Lemma drop_cons x s : drop n0 (x :: s) = if n0 is n.+1 then drop n s else x :: s. Proof. by []. Qed. Lemma size_drop s : size (drop n0 s) = size s - n0. Proof. by elim: s n0 => [|x s IHs] []. Qed. Lemma drop_cat s1 s2 : drop n0 (s1 ++ s2) = if n0 < size s1 then drop n0 s1 ++ s2 else drop (n0 - size s1) s2. Proof. by elim: s1 n0 => [|x s1 IHs] []. Qed. Lemma drop_size_cat n s1 s2 : size s1 = n -> drop n (s1 ++ s2) = s2. Proof. by move <-; elim: s1 => //=; rewrite drop0. Qed. Lemma nconsK n x : cancel (ncons n x) (drop n). Proof. by elim: n => // -[]. Qed. Lemma drop_drop s n1 n2 : drop n1 (drop n2 s) = drop (n1 + n2) s. Proof. by elim: s n2 => // x s ihs [|n2]; rewrite ?drop0 ?addn0 ?addnS /=. Qed. Fixpoint take n s {struct s} := match s, n with | x :: s', n'.+1 => x :: take n' s' | _, _ => [::] end. Lemma take0 s : take 0 s = [::]. Proof. by case: s. Qed. Lemma take_oversize n s : size s <= n -> take n s = s. Proof. by elim: s n => [|x s IHs] [|n] //= /IHs->. Qed. Lemma take_size s : take (size s) s = s. Proof. exact: take_oversize. Qed. Lemma take_cons x s : take n0 (x :: s) = if n0 is n.+1 then x :: (take n s) else [::]. Proof. by []. Qed. Lemma drop_rcons s : n0 <= size s -> forall x, drop n0 (rcons s x) = rcons (drop n0 s) x. Proof. by elim: s n0 => [|y s IHs] []. Qed. Lemma cat_take_drop s : take n0 s ++ drop n0 s = s. Proof. by elim: s n0 => [|x s IHs] [|n] //=; rewrite IHs. Qed. Lemma size_takel s : n0 <= size s -> size (take n0 s) = n0. Proof. by move/subKn; rewrite -size_drop -[in size s](cat_take_drop s) size_cat addnK. Qed. Lemma size_take s : size (take n0 s) = if n0 < size s then n0 else size s. Proof. have [le_sn | lt_ns] := leqP (size s) n0; first by rewrite take_oversize. by rewrite size_takel // ltnW. Qed. Lemma size_take_min s : size (take n0 s) = minn n0 (size s). Proof. exact: size_take. Qed. Lemma take_cat s1 s2 : take n0 (s1 ++ s2) = if n0 < size s1 then take n0 s1 else s1 ++ take (n0 - size s1) s2. Proof. elim: s1 n0 => [|x s1 IHs] [|n] //=. by rewrite ltnS subSS -(fun_if (cons x)) -IHs. Qed. Lemma take_size_cat n s1 s2 : size s1 = n -> take n (s1 ++ s2) = s1. Proof. by move <-; elim: s1 => [|x s1 IHs]; rewrite ?take0 //= IHs. Qed. Lemma takel_cat s1 s2 : n0 <= size s1 -> take n0 (s1 ++ s2) = take n0 s1. Proof. by rewrite take_cat; case: ltngtP => // ->; rewrite subnn take0 take_size cats0. Qed. Lemma nth_drop s i : nth (drop n0 s) i = nth s (n0 + i). Proof. rewrite -[s in RHS]cat_take_drop nth_cat size_take ltnNge. case: ltnP => [?|le_s_n0]; rewrite ?(leq_trans le_s_n0) ?leq_addr ?addKn //=. by rewrite drop_oversize // !nth_default. Qed. Lemma find_ltn p s i : has p (take i s) -> find p s < i. Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs. Qed. Lemma has_take p s i : has p s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma has_take_leq (p : pred T) (s : seq T) i : i <= size s -> has p (take i s) = (find p s < i). Proof. by elim: s i => [|y s ihs] [|i]//=; case: (p _) => //= /ihs ->. Qed. Lemma nth_take i : i < n0 -> forall s, nth (take n0 s) i = nth s i. Proof. move=> lt_i_n0 s; case lt_n0_s: (n0 < size s). by rewrite -[s in RHS]cat_take_drop nth_cat size_take lt_n0_s /= lt_i_n0. by rewrite -[s in LHS]cats0 take_cat lt_n0_s /= cats0. Qed. Lemma take_min i j s : take (minn i j) s = take i (take j s). Proof. by elim: s i j => //= a l IH [|i] [|j] //=; rewrite minnSS IH. Qed. Lemma take_takel i j s : i <= j -> take i (take j s) = take i s. Proof. by move=> ?; rewrite -take_min (minn_idPl _). Qed. Lemma take_taker i j s : j <= i -> take i (take j s) = take j s. Proof. by move=> ?; rewrite -take_min (minn_idPr _). Qed. Lemma take_drop i j s : take i (drop j s) = drop j (take (i + j) s). Proof. by rewrite addnC; elim: s i j => // x s IHs [|i] [|j] /=. Qed. Lemma takeD i j s : take (i + j) s = take i s ++ take j (drop i s). Proof. elim: i j s => [|i IHi] [|j] [|a s] //; first by rewrite take0 addn0 cats0. by rewrite addSn /= IHi. Qed. Lemma takeC i j s : take i (take j s) = take j (take i s). Proof. by rewrite -!take_min minnC. Qed. Lemma take_nseq i j x : i <= j -> take i (nseq j x) = nseq i x. Proof. by move=>/subnKC <-; rewrite nseqD take_size_cat // size_nseq. Qed. Lemma drop_nseq i j x : drop i (nseq j x) = nseq (j - i) x. Proof. case: (leqP i j) => [/subnKC {1}<-|/ltnW j_le_i]. by rewrite nseqD drop_size_cat // size_nseq. by rewrite drop_oversize ?size_nseq // (eqP j_le_i). Qed. (* drop_nth and take_nth below do NOT use the default n0, because the "n" *) (* can be inferred from the condition, whereas the nth default value x0 *) (* will have to be given explicitly (and this will provide "d" as well). *) Lemma drop_nth n s : n < size s -> drop n s = nth s n :: drop n.+1 s. Proof. by elim: s n => [|x s IHs] [|n] Hn //=; rewrite ?drop0 1?IHs. Qed. Lemma take_nth n s : n < size s -> take n.+1 s = rcons (take n s) (nth s n). Proof. by elim: s n => [|x s IHs] //= [|n] Hn /=; rewrite ?take0 -?IHs. Qed. (* Rotation *) Definition rot n s := drop n s ++ take n s. Lemma rot0 s : rot 0 s = s. Proof. by rewrite /rot drop0 take0 cats0. Qed. Lemma size_rot s : size (rot n0 s) = size s. Proof. by rewrite -[s in RHS]cat_take_drop /rot !size_cat addnC. Qed. Lemma rot_oversize n s : size s <= n -> rot n s = s. Proof. by move=> le_s_n; rewrite /rot take_oversize ?drop_oversize. Qed. Lemma rot_size s : rot (size s) s = s. Proof. exact: rot_oversize. Qed. Lemma has_rot s a : has a (rot n0 s) = has a s. Proof. by rewrite has_cat orbC -has_cat cat_take_drop. Qed. Lemma rot_size_cat s1 s2 : rot (size s1) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rot take_size_cat ?drop_size_cat. Qed. Definition rotr n s := rot (size s - n) s. Lemma rotK : cancel (rot n0) (rotr n0). Proof. move=> s; rewrite /rotr size_rot -size_drop {2}/rot. by rewrite rot_size_cat cat_take_drop. Qed. Lemma rot_inj : injective (rot n0). Proof. exact (can_inj rotK). Qed. (* (efficient) reversal *) Fixpoint catrev s1 s2 := if s1 is x :: s1' then catrev s1' (x :: s2) else s2. Definition rev s := catrev s [::]. Lemma catrev_catl s t u : catrev (s ++ t) u = catrev t (catrev s u). Proof. by elim: s u => /=. Qed. Lemma catrev_catr s t u : catrev s (t ++ u) = catrev s t ++ u. Proof. by elim: s t => //= x s IHs t; rewrite -IHs. Qed. Lemma catrevE s t : catrev s t = rev s ++ t. Proof. by rewrite -catrev_catr. Qed. Lemma rev_cons x s : rev (x :: s) = rcons (rev s) x. Proof. by rewrite -cats1 -catrevE. Qed. Lemma size_rev s : size (rev s) = size s. Proof. by elim: s => // x s IHs; rewrite rev_cons size_rcons IHs. Qed. Lemma rev_nilp s : nilp (rev s) = nilp s. Proof. by rewrite /nilp size_rev. Qed. Lemma rev_cat s t : rev (s ++ t) = rev t ++ rev s. Proof. by rewrite -catrev_catr -catrev_catl. Qed. Lemma rev_rcons s x : rev (rcons s x) = x :: rev s. Proof. by rewrite -cats1 rev_cat. Qed. Lemma revK : involutive rev. Proof. by elim=> //= x s IHs; rewrite rev_cons rev_rcons IHs. Qed. Lemma nth_rev n s : n < size s -> nth (rev s) n = nth s (size s - n.+1). Proof. elim/last_ind: s => // s x IHs in n *. rewrite rev_rcons size_rcons ltnS subSS -cats1 nth_cat /=. case: n => [|n] lt_n_s; first by rewrite subn0 ltnn subnn. by rewrite subnSK //= leq_subr IHs. Qed. Lemma filter_rev a s : filter a (rev s) = rev (filter a s). Proof. by elim: s => //= x s IH; rewrite fun_if !rev_cons filter_rcons IH. Qed. Lemma count_rev a s : count a (rev s) = count a s. Proof. by rewrite -!size_filter filter_rev size_rev. Qed. Lemma has_rev a s : has a (rev s) = has a s. Proof. by rewrite !has_count count_rev. Qed. Lemma all_rev a s : all a (rev s) = all a s. Proof. by rewrite !all_count count_rev size_rev. Qed. Lemma rev_nseq n x : rev (nseq n x) = nseq n x. Proof. by elim: n => // n IHn; rewrite -[in LHS]addn1 nseqD rev_cat IHn. Qed. End Sequences. Prenex Implicits size ncons nseq head ohead behead last rcons belast. Arguments seqn {T} n. Prenex Implicits cat take drop rot rotr catrev. Prenex Implicits find count nth all has filter. Arguments rev {T} s : simpl never. Arguments nth : simpl nomatch. Arguments set_nth : simpl nomatch. Arguments take : simpl nomatch. Arguments drop : simpl nomatch. Arguments nilP {T s}. Arguments all_filterP {T a s}. Arguments rotK n0 {T} s : rename. Arguments rot_inj {n0 T} [s1 s2] eq_rot_s12 : rename. Arguments revK {T} s : rename. Notation count_mem x := (count (pred_of_simpl (pred1 x))). Infix "++" := cat : seq_scope. Notation "[ 'seq' x <- s | C ]" := (filter (fun x => C%B) s) (x at level 99, format "[ '[hv' 'seq' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (format "[ '[hv' 'seq' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C ]" := (filter (fun x => C%B) s) (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C ] ']'") : seq_scope. Notation "[ 'seq' ' x <- s | C1 & C2 ]" := [seq x <- s | C1 && C2] (x strict pattern, format "[ '[hv' 'seq' ' x <- s '/ ' | C1 '/ ' & C2 ] ']'") : seq_scope. Notation "[ 'seq' x : T <- s | C ]" := (filter (fun x : T => C%B) s) (only parsing). Notation "[ 'seq' x : T <- s | C1 & C2 ]" := [seq x : T <- s | C1 && C2] (only parsing). (* Double induction/recursion. *) Lemma seq_ind2 {S T} (P : seq S -> seq T -> Type) : P [::] [::] -> (forall x y s t, size s = size t -> P s t -> P (x :: s) (y :: t)) -> forall s t, size s = size t -> P s t. Proof. by move=> Pnil Pcons; elim=> [|x s IHs] [|y t] //= [eq_sz]; apply/Pcons/IHs. Qed. Section AllIff. (* The Following Are Equivalent *) (* We introduce a specific conjunction, used to chain the consecutive *) (* items in a circular list of implications *) Inductive all_iff_and (P Q : Prop) : Prop := AllIffConj of P & Q. Definition all_iff (P0 : Prop) (Ps : seq Prop) : Prop := let fix loop (P : Prop) (Qs : seq Prop) : Prop := if Qs is Q :: Qs then all_iff_and (P -> Q) (loop Q Qs) else P -> P0 in loop P0 Ps. Lemma all_iffLR P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m -> nth P0 (P0 :: Ps) n. Proof. move=> iffPs; have PsS n: nth P0 Ps n -> nth P0 Ps n.+1. elim: n P0 Ps iffPs => [|n IHn] P0 [|P [|Q Ps]] //= [iP0P] //; first by case. by rewrite nth_nil. by case=> iPQ iffPs; apply: IHn; split=> // /iP0P. have{PsS} lePs: {homo nth P0 Ps : m n / m <= n >-> (m -> n)}. by move=> m n /subnK<-; elim: {n}(n - m) => // n IHn /IHn; apply: PsS. move=> m n P_m; have{m P_m} hP0: P0. case: m P_m => //= m /(lePs m _ (leq_maxl m (size Ps))). by rewrite nth_default ?leq_maxr. case: n =>// n; apply: lePs 0 n (leq0n n) _. by case: Ps iffPs hP0 => // P Ps []. Qed. Lemma all_iffP P0 Ps : all_iff P0 Ps -> forall m n, nth P0 (P0 :: Ps) m <-> nth P0 (P0 :: Ps) n. Proof. by move=> /all_iffLR-iffPs m n; split => /iffPs. Qed. End AllIff. Arguments all_iffLR {P0 Ps}. Arguments all_iffP {P0 Ps}. Coercion all_iffP : all_iff >-> Funclass. (* This means "the following are all equivalent: P0, ... Pn" *) Notation "[ '<->' P0 ; P1 ; .. ; Pn ]" := (all_iff P0 (@cons Prop P1 (.. (@cons Prop Pn nil) ..))) : form_scope. Ltac tfae := do !apply: AllIffConj. Section FindSpec. Variable (T : Type) (a : {pred T}) (s : seq T). Variant find_spec : bool -> nat -> Type := | NotFound of ~~ has a s : find_spec false (size s) | Found (i : nat) of i < size s & (forall x0, a (nth x0 s i)) & (forall x0 j, j < i -> a (nth x0 s j) = false) : find_spec true i. Lemma findP : find_spec (has a s) (find a s). Proof. have [a_s|aNs] := boolP (has a s); last by rewrite hasNfind//; constructor. by constructor=> [|x0|x0]; rewrite -?has_find ?nth_find//; apply: before_find. Qed. End FindSpec. Arguments findP {T}. Section RotRcons. Variable T : Type. Implicit Types (x : T) (s : seq T). Lemma rot1_cons x s : rot 1 (x :: s) = rcons s x. Proof. by rewrite /rot /= take0 drop0 -cats1. Qed. Lemma rcons_inj s1 s2 x1 x2 : rcons s1 x1 = rcons s2 x2 :> seq T -> (s1, x1) = (s2, x2). Proof. by rewrite -!rot1_cons => /rot_inj[-> ->]. Qed. Lemma rcons_injl x : injective (rcons^~ x). Proof. by move=> s1 s2 /rcons_inj[]. Qed. Lemma rcons_injr s : injective (rcons s). Proof. by move=> x1 x2 /rcons_inj[]. Qed. End RotRcons. Arguments rcons_inj {T s1 x1 s2 x2} eq_rcons : rename. Arguments rcons_injl {T} x [s1 s2] eq_rcons : rename. Arguments rcons_injr {T} s [x1 x2] eq_rcons : rename. (* Equality and eqType for seq. *) Section EqSeq. Variables (n0 : nat) (T : eqType) (x0 : T). Local Notation nth := (nth x0). Implicit Types (x y z : T) (s : seq T). Fixpoint eqseq s1 s2 {struct s2} := match s1, s2 with | [::], [::] => true | x1 :: s1', x2 :: s2' => (x1 == x2) && eqseq s1' s2' | _, _ => false end. Lemma eqseqP : Equality.axiom eqseq. Proof. move; elim=> [|x1 s1 IHs] [|x2 s2]; do [by constructor | simpl]. have [<-|neqx] := x1 =P x2; last by right; case. by apply: (iffP (IHs s2)) => [<-|[]]. Qed. HB.instance Definition _ := hasDecEq.Build (seq T) eqseqP. Lemma eqseqE : eqseq = eq_op. Proof. by []. Qed. Lemma eqseq_cons x1 x2 s1 s2 : (x1 :: s1 == x2 :: s2) = (x1 == x2) && (s1 == s2). Proof. by []. Qed. Lemma eqseq_cat s1 s2 s3 s4 : size s1 = size s2 -> (s1 ++ s3 == s2 ++ s4) = (s1 == s2) && (s3 == s4). Proof. elim: s1 s2 => [|x1 s1 IHs] [|x2 s2] //= [sz12]. by rewrite !eqseq_cons -andbA IHs. Qed. Lemma eqseq_rcons s1 s2 x1 x2 : (rcons s1 x1 == rcons s2 x2) = (s1 == s2) && (x1 == x2). Proof. by rewrite -(can_eq revK) !rev_rcons eqseq_cons andbC (can_eq revK). Qed. Lemma size_eq0 s : (size s == 0) = (s == [::]). Proof. exact: (sameP nilP eqP). Qed. Lemma nilpE s : nilp s = (s == [::]). Proof. by case: s. Qed. Lemma has_filter a s : has a s = (filter a s != [::]). Proof. by rewrite -size_eq0 size_filter has_count lt0n. Qed. (* mem_seq and index. *) (* mem_seq defines a predType for seq. *) Fixpoint mem_seq (s : seq T) := if s is y :: s' then xpredU1 y (mem_seq s') else xpred0. Definition seq_eqclass := seq T. Identity Coercion seq_of_eqclass : seq_eqclass >-> seq. Coercion pred_of_seq (s : seq_eqclass) : {pred T} := mem_seq s. Canonical seq_predType := PredType (pred_of_seq : seq T -> pred T). (* The line below makes mem_seq a canonical instance of topred. *) Canonical mem_seq_predType := PredType mem_seq. Lemma in_cons y s x : (x \in y :: s) = (x == y) || (x \in s). Proof. by []. Qed. Lemma in_nil x : (x \in [::]) = false. Proof. by []. Qed. Lemma mem_seq1 x y : (x \in [:: y]) = (x == y). Proof. by rewrite in_cons orbF. Qed. (* to be repeated after the Section discharge. *) Let inE := (mem_seq1, in_cons, inE). Lemma forall_cons {P : T -> Prop} {a s} : {in a::s, forall x, P x} <-> P a /\ {in s, forall x, P x}. Proof. split=> [A|[A B]]; last by move => x /predU1P [-> //|]; apply: B. by split=> [|b Hb]; apply: A; rewrite !inE ?eqxx ?Hb ?orbT. Qed. Lemma exists_cons {P : T -> Prop} {a s} : (exists2 x, x \in a::s & P x) <-> P a \/ exists2 x, x \in s & P x. Proof. split=> [[x /predU1P[->|x_s] Px]|]; [by left| by right; exists x|]. by move=> [?|[x x_s ?]]; [exists a|exists x]; rewrite ?inE ?eqxx ?x_s ?orbT. Qed. Lemma mem_seq2 x y z : (x \in [:: y; z]) = xpred2 y z x. Proof. by rewrite !inE. Qed. Lemma mem_seq3 x y z t : (x \in [:: y; z; t]) = xpred3 y z t x. Proof. by rewrite !inE. Qed. Lemma mem_seq4 x y z t u : (x \in [:: y; z; t; u]) = xpred4 y z t u x. Proof. by rewrite !inE. Qed. Lemma mem_cat x s1 s2 : (x \in s1 ++ s2) = (x \in s1) || (x \in s2). Proof. by elim: s1 => //= y s1 IHs; rewrite !inE /= -orbA -IHs. Qed. Lemma mem_rcons s y : rcons s y =i y :: s. Proof. by move=> x; rewrite -cats1 /= mem_cat mem_seq1 orbC in_cons. Qed. Lemma mem_head x s : x \in x :: s. Proof. exact: predU1l. Qed. Lemma mem_last x s : last x s \in x :: s. Proof. by rewrite lastI mem_rcons mem_head. Qed. Lemma mem_behead s : {subset behead s <= s}. Proof. by case: s => // y s x; apply: predU1r. Qed. Lemma mem_belast s y : {subset belast y s <= y :: s}. Proof. by move=> x ys'x; rewrite lastI mem_rcons mem_behead. Qed. Lemma mem_nth s n : n < size s -> nth s n \in s. Proof. by elim: s n => // x s IHs [_|n sz_s]; rewrite ?mem_head // mem_behead ?IHs. Qed. Lemma mem_take s x : x \in take n0 s -> x \in s. Proof. by move=> s0x; rewrite -(cat_take_drop n0 s) mem_cat /= s0x. Qed. Lemma mem_drop s x : x \in drop n0 s -> x \in s. Proof. by move=> s0'x; rewrite -(cat_take_drop n0 s) mem_cat /= s0'x orbT. Qed. Lemma last_eq s z x y : x != y -> z != y -> (last x s == y) = (last z s == y). Proof. by move=> /negPf xz /negPf yz; case: s => [|t s]//; rewrite xz yz. Qed. Section Filters. Implicit Type a : pred T. Lemma hasP {a s} : reflect (exists2 x, x \in s & a x) (has a s). Proof. elim: s => [|y s IHs] /=; first by right; case. exact: equivP (orPP idP IHs) (iff_sym exists_cons). Qed. Lemma allP {a s} : reflect {in s, forall x, a x} (all a s). Proof. elim: s => [|/= y s IHs]; first by left. exact: equivP (andPP idP IHs) (iff_sym forall_cons). Qed. Lemma hasPn a s : reflect {in s, forall x, ~~ a x} (~~ has a s). Proof. by rewrite -all_predC; apply: allP. Qed. Lemma allPn a s : reflect (exists2 x, x \in s & ~~ a x) (~~ all a s). Proof. by rewrite -has_predC; apply: hasP. Qed. Lemma allss s : all [in s] s. Proof. exact/allP. Qed. Lemma mem_filter a x s : (x \in filter a s) = a x && (x \in s). Proof. rewrite andbC; elim: s => //= y s IHs. rewrite (fun_if (fun s' : seq T => x \in s')) !in_cons {}IHs. by case: eqP => [->|_]; case (a y); rewrite /= ?andbF. Qed. Variables (a : pred T) (s : seq T) (A : T -> Prop). Hypothesis aP : forall x, reflect (A x) (a x). Lemma hasPP : reflect (exists2 x, x \in s & A x) (has a s). Proof. by apply: (iffP hasP) => -[x ? /aP]; exists x. Qed. Lemma allPP : reflect {in s, forall x, A x} (all a s). Proof. by apply: (iffP allP) => a_s x /a_s/aP. Qed. End Filters. Section EqIn. Variables a1 a2 : pred T. Lemma eq_in_filter s : {in s, a1 =1 a2} -> filter a1 s = filter a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_find s : {in s, a1 =1 a2} -> find a1 s = find a2 s. Proof. by elim: s => //= x s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_in_count s : {in s, a1 =1 a2} -> count a1 s = count a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite -!size_filter eq_a12. Qed. Lemma eq_in_all s : {in s, a1 =1 a2} -> all a1 s = all a2 s. Proof. by move=> eq_a12; rewrite !all_count eq_in_count. Qed. Lemma eq_in_has s : {in s, a1 =1 a2} -> has a1 s = has a2 s. Proof. by move/eq_in_filter=> eq_a12; rewrite !has_filter eq_a12. Qed. End EqIn. Lemma eq_has_r s1 s2 : s1 =i s2 -> has^~ s1 =1 has^~ s2. Proof. by move=> Es a; apply/hasP/hasP=> -[x sx ax]; exists x; rewrite ?Es in sx *. Qed. Lemma eq_all_r s1 s2 : s1 =i s2 -> all^~ s1 =1 all^~ s2. Proof. by move=> Es a; apply/negb_inj; rewrite -!has_predC (eq_has_r Es). Qed. Lemma has_sym s1 s2 : has [in s1] s2 = has [in s2] s1. Proof. by apply/hasP/hasP=> -[x]; exists x. Qed. Lemma has_pred1 x s : has (pred1 x) s = (x \in s). Proof. by rewrite -(eq_has (mem_seq1^~ x)) (has_sym [:: x]) /= orbF. Qed. Lemma mem_rev s : rev s =i s. Proof. by move=> a; rewrite -!has_pred1 has_rev. Qed. (* Constant sequences, i.e., the image of nseq. *) Definition constant s := if s is x :: s' then all (pred1 x) s' else true. Lemma all_pred1P x s : reflect (s = nseq (size s) x) (all (pred1 x) s). Proof. elim: s => [|y s IHs] /=; first by left. case: eqP => [->{y} | ne_xy]; last by right=> [] [? _]; case ne_xy. by apply: (iffP IHs) => [<- //| []]. Qed. Lemma all_pred1_constant x s : all (pred1 x) s -> constant s. Proof. by case: s => //= y s /andP[/eqP->]. Qed. Lemma all_pred1_nseq x n : all (pred1 x) (nseq n x). Proof. by rewrite all_nseq /= eqxx orbT. Qed. Lemma mem_nseq n x y : (y \in nseq n x) = (0 < n) && (y == x). Proof. by rewrite -has_pred1 has_nseq eq_sym. Qed. Lemma nseqP n x y : reflect (y = x /\ n > 0) (y \in nseq n x). Proof. by rewrite mem_nseq andbC; apply: (iffP andP) => -[/eqP]. Qed. Lemma constant_nseq n x : constant (nseq n x). Proof. exact: all_pred1_constant (all_pred1_nseq x n). Qed. (* Uses x0 *) Lemma constantP s : reflect (exists x, s = nseq (size s) x) (constant s). Proof. apply: (iffP idP) => [| [x ->]]; last exact: constant_nseq. case: s => [|x s] /=; first by exists x0. by move/all_pred1P=> def_s; exists x; rewrite -def_s. Qed. (* Duplicate-freenes. *) Fixpoint uniq s := if s is x :: s' then (x \notin s') && uniq s' else true. Lemma cons_uniq x s : uniq (x :: s) = (x \notin s) && uniq s. Proof. by []. Qed. Lemma cat_uniq s1 s2 : uniq (s1 ++ s2) = [&& uniq s1, ~~ has [in s1] s2 & uniq s2]. Proof. elim: s1 => [|x s1 IHs]; first by rewrite /= has_pred0. by rewrite has_sym /= mem_cat !negb_or has_sym IHs -!andbA; do !bool_congr. Qed. Lemma uniq_catC s1 s2 : uniq (s1 ++ s2) = uniq (s2 ++ s1). Proof. by rewrite !cat_uniq has_sym andbCA andbA andbC. Qed. Lemma uniq_catCA s1 s2 s3 : uniq (s1 ++ s2 ++ s3) = uniq (s2 ++ s1 ++ s3). Proof. by rewrite !catA -!(uniq_catC s3) !(cat_uniq s3) uniq_catC !has_cat orbC. Qed. Lemma rcons_uniq s x : uniq (rcons s x) = (x \notin s) && uniq s. Proof. by rewrite -cats1 uniq_catC. Qed. Lemma filter_uniq s a : uniq s -> uniq (filter a s). Proof. elim: s => //= x s IHs /andP[s'x]; case: ifP => //= a_x /IHs->. by rewrite mem_filter a_x s'x. Qed. Lemma rot_uniq s : uniq (rot n0 s) = uniq s. Proof. by rewrite /rot uniq_catC cat_take_drop. Qed. Lemma rev_uniq s : uniq (rev s) = uniq s. Proof. elim: s => // x s IHs. by rewrite rev_cons -cats1 cat_uniq /= andbT andbC mem_rev orbF IHs. Qed. Lemma count_memPn x s : reflect (count_mem x s = 0) (x \notin s). Proof. by rewrite -has_pred1 has_count -eqn0Ngt; apply: eqP. Qed. Lemma count_uniq_mem s x : uniq s -> count_mem x s = (x \in s). Proof. elim: s => //= y s IHs /andP[/negbTE s'y /IHs-> {IHs}]. by rewrite in_cons; case: (eqVneq y x) => // <-; rewrite s'y. Qed. Lemma leq_uniq_countP x s1 s2 : uniq s1 -> reflect (x \in s1 -> x \in s2) (count_mem x s1 <= count_mem x s2). Proof. move/count_uniq_mem->; case: (boolP (_ \in _)) => //= _; last by constructor. by rewrite -has_pred1 has_count; apply: (iffP idP) => //; apply. Qed. Lemma leq_uniq_count s1 s2 : uniq s1 -> {subset s1 <= s2} -> (forall x, count_mem x s1 <= count_mem x s2). Proof. by move=> s1_uniq s1_s2 x; apply/leq_uniq_countP/s1_s2. Qed. Lemma filter_pred1_uniq s x : uniq s -> x \in s -> filter (pred1 x) s = [:: x]. Proof. move=> uniq_s s_x; rewrite (all_pred1P _ _ (filter_all _ _)). by rewrite size_filter count_uniq_mem ?s_x. Qed. (* Removing duplicates *) Fixpoint undup s := if s is x :: s' then if x \in s' then undup s' else x :: undup s' else [::]. Lemma size_undup s : size (undup s) <= size s. Proof. by elim: s => //= x s IHs; case: (x \in s) => //=; apply: ltnW. Qed. Lemma mem_undup s : undup s =i s. Proof. move=> x; elim: s => //= y s IHs. by case s_y: (y \in s); rewrite !inE IHs //; case: eqP => [->|]. Qed. Lemma undup_uniq s : uniq (undup s). Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= mem_undup s_x. Qed. Lemma undup_id s : uniq s -> undup s = s. Proof. by elim: s => //= x s IHs /andP[/negbTE-> /IHs->]. Qed. Lemma ltn_size_undup s : (size (undup s) < size s) = ~~ uniq s. Proof. by elim: s => //= x s IHs; case s_x: (x \in s); rewrite //= ltnS size_undup. Qed. Lemma filter_undup p s : filter p (undup s) = undup (filter p s). Proof. elim: s => //= x s IHs; rewrite (fun_if undup) [_ = _]fun_if /= mem_filter /=. by rewrite (fun_if (filter p)) /= IHs; case: ifP => -> //=; apply: if_same. Qed. Lemma undup_nil s : undup s = [::] -> s = [::]. Proof. by case: s => //= x s; rewrite -mem_undup; case: ifP; case: undup. Qed. Lemma undup_cat s t : undup (s ++ t) = [seq x <- undup s | x \notin t] ++ undup t. Proof. by elim: s => //= x s ->; rewrite mem_cat; do 2 case: in_mem => //=. Qed. Lemma undup_rcons s x : undup (rcons s x) = rcons [seq y <- undup s | y != x] x. Proof. by rewrite -!cats1 undup_cat; congr cat; apply: eq_filter => y; rewrite inE. Qed. Lemma count_undup s p : count p (undup s) <= count p s. Proof. by rewrite -!size_filter filter_undup size_undup. Qed. Lemma has_undup p s : has p (undup s) = has p s. Proof. by apply: eq_has_r => x; rewrite mem_undup. Qed. Lemma all_undup p s : all p (undup s) = all p s. Proof. by apply: eq_all_r => x; rewrite mem_undup. Qed. (* Lookup *) Definition index x := find (pred1 x). Lemma index_size x s : index x s <= size s. Proof. by rewrite /index find_size. Qed. Lemma index_mem x s : (index x s < size s) = (x \in s). Proof. by rewrite -has_pred1 has_find. Qed. Lemma memNindex x s : x \notin s -> index x s = size s. Proof. by rewrite -has_pred1 => /hasNfind. Qed. Lemma nth_index x s : x \in s -> nth s (index x s) = x. Proof. by rewrite -has_pred1 => /(nth_find x0)/eqP. Qed. Lemma index_inj s : {in s &, injective (index ^~ s)}. Proof. by move=> x y x_s y_s eidx; rewrite -(nth_index x_s) eidx nth_index. Qed. Lemma index_cat x s1 s2 : index x (s1 ++ s2) = if x \in s1 then index x s1 else size s1 + index x s2. Proof. by rewrite /index find_cat has_pred1. Qed. Lemma index_ltn x s i : x \in take i s -> index x s < i. Proof. by rewrite -has_pred1; apply: find_ltn. Qed. Lemma in_take x s i : x \in s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take. Qed. Lemma in_take_leq x s i : i <= size s -> (x \in take i s) = (index x s < i). Proof. by rewrite -?has_pred1; apply: has_take_leq. Qed. Lemma index_nth i s : i < size s -> index (nth s i) s <= i. Proof. move=> lti; rewrite -ltnS index_ltn// -(@nth_take i.+1)// mem_nth // size_take. by case: ifP. Qed. Lemma nthK s: uniq s -> {in gtn (size s), cancel (nth s) (index^~ s)}. Proof. elim: s => //= x s IHs /andP[s'x Us] i; rewrite inE ltnS eq_sym -if_neg. by case: i => /= [_|i lt_i_s]; rewrite ?eqxx ?IHs ?(memPn s'x) ?mem_nth. Qed. Lemma index_uniq i s : i < size s -> uniq s -> index (nth s i) s = i. Proof. by move/nthK. Qed. Lemma index_head x s : index x (x :: s) = 0. Proof. by rewrite /= eqxx. Qed. Lemma index_last x s : uniq (x :: s) -> index (last x s) (x :: s) = size s. Proof. rewrite lastI rcons_uniq -cats1 index_cat size_belast. by case: ifP => //=; rewrite eqxx addn0. Qed. Lemma nth_uniq s i j : i < size s -> j < size s -> uniq s -> (nth s i == nth s j) = (i == j). Proof. by move=> lti ltj /nthK/can_in_eq->. Qed. Lemma uniqPn s : reflect (exists i j, [/\ i < j, j < size s & nth s i = nth s j]) (~~ uniq s). Proof. apply: (iffP idP) => [|[i [j [ltij ltjs]]]]; last first. by apply: contra_eqN => Us; rewrite nth_uniq ?ltn_eqF // (ltn_trans ltij). elim: s => // x s IHs /nandP[/negbNE | /IHs[i [j]]]; last by exists i.+1, j.+1. by exists 0, (index x s).+1; rewrite !ltnS index_mem /= nth_index. Qed. Lemma uniqP s : reflect {in gtn (size s) &, injective (nth s)} (uniq s). Proof. apply: (iffP idP) => [/nthK/can_in_inj// | nth_inj]. apply/uniqPn => -[i [j [ltij ltjs /nth_inj/eqP/idPn]]]. by rewrite !inE (ltn_trans ltij ltjs) ltn_eqF //=; case. Qed. Lemma mem_rot s : rot n0 s =i s. Proof. by move=> x; rewrite -[s in RHS](cat_take_drop n0) !mem_cat /= orbC. Qed. Lemma eqseq_rot s1 s2 : (rot n0 s1 == rot n0 s2) = (s1 == s2). Proof. exact/inj_eq/rot_inj. Qed. Lemma drop_index s (n := index x0 s) : x0 \in s -> drop n s = x0 :: drop n.+1 s. Proof. by move=> xs; rewrite (drop_nth x0) ?index_mem ?nth_index. Qed. (* lemmas about the pivot pattern [_ ++ _ :: _] *) Lemma index_pivot x s1 s2 (s := s1 ++ x :: s2) : x \notin s1 -> index x s = size s1. Proof. by rewrite index_cat/= eqxx addn0; case: ifPn. Qed. Lemma take_pivot x s2 s1 (s := s1 ++ x :: s2) : x \notin s1 -> take (index x s) s = s1. Proof. by move=> /index_pivot->; rewrite take_size_cat. Qed. Lemma rev_pivot x s1 s2 : rev (s1 ++ x :: s2) = rev s2 ++ x :: rev s1. Proof. by rewrite rev_cat rev_cons cat_rcons. Qed. Lemma eqseq_pivot2l x s1 s2 s3 s4 : x \notin s1 -> x \notin s3 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs3; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. suff S : size s1 = size s3 by rewrite eqseq_cat// eqseq_cons eqxx in E. by rewrite -(index_pivot s2 xNs1) (eqP E) index_pivot. Qed. Lemma eqseq_pivot2r x s1 s2 s3 s4 : x \notin s2 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs2 xNs4; rewrite -(can_eq revK) !rev_pivot. by rewrite eqseq_pivot2l ?mem_rev // !(can_eq revK) andbC. Qed. Lemma eqseq_pivotl x s1 s2 s3 s4 : x \notin s1 -> x \notin s2 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. move=> xNs1 xNs2; apply/idP/idP => [E|/andP[/eqP-> /eqP->]//]. rewrite -(@eqseq_pivot2l x)//; have /eqP/(congr1 (count_mem x)) := E. rewrite !count_cat/= eqxx !addnS (count_memPn _ _ xNs1) (count_memPn _ _ xNs2). by move=> -[/esym/eqP]; rewrite addn_eq0 => /andP[/eqP/count_memPn]. Qed. Lemma eqseq_pivotr x s1 s2 s3 s4 : x \notin s3 -> x \notin s4 -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> *; rewrite eq_sym eqseq_pivotl//; case: eqVneq => /=. Qed. Lemma uniq_eqseq_pivotl x s1 s2 s3 s4 : uniq (s1 ++ x :: s2) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by rewrite uniq_catC/= mem_cat => /andP[/norP[? ?] _]; rewrite eqseq_pivotl. Qed. Lemma uniq_eqseq_pivotr x s1 s2 s3 s4 : uniq (s3 ++ x :: s4) -> (s1 ++ x :: s2 == s3 ++ x :: s4) = (s1 == s3) && (s2 == s4). Proof. by move=> ?; rewrite eq_sym uniq_eqseq_pivotl//; case: eqVneq => /=. Qed. End EqSeq. Arguments eqseq : simpl nomatch. Notation "'has_ view" := (hasPP _ (fun _ => view)) (at level 4, right associativity, format "''has_' view"). Notation "'all_ view" := (allPP _ (fun _ => view)) (at level 4, right associativity, format "''all_' view"). Section RotIndex. Variables (T : eqType). Implicit Types x y z : T. Lemma rot_index s x (i := index x s) : x \in s -> rot i s = x :: (drop i.+1 s ++ take i s). Proof. by move=> x_s; rewrite /rot drop_index. Qed. Variant rot_to_spec s x := RotToSpec i s' of rot i s = x :: s'. Lemma rot_to s x : x \in s -> rot_to_spec s x. Proof. by move=> /rot_index /RotToSpec. Qed. End RotIndex. Definition inE := (mem_seq1, in_cons, inE). Prenex Implicits mem_seq1 constant uniq undup index. Arguments eqseq {T} !_ !_. Arguments pred_of_seq {T} s x /. Arguments eqseqP {T x y}. Arguments hasP {T a s}. Arguments hasPn {T a s}. Arguments allP {T a s}. Arguments allPn {T a s}. Arguments nseqP {T n x y}. Arguments count_memPn {T x s}. Arguments uniqPn {T} x0 {s}. Arguments uniqP {T} x0 {s}. Arguments forall_cons {T P a s}. Arguments exists_cons {T P a s}. (* Since both `all [in s] s`, `all (mem s) s`, and `all (pred_of_seq s) s` *) (* may appear in goals, the following hint has to be declared using the *) (* `Hint Extern` command. Additionally, `mem` and `pred_of_seq` in the above *) (* terms do not reduce to each other; thus, stating `allss` in the form of *) (* one of them makes `apply: allss` fail for the other case. Since both `mem` *) (* and `pred_of_seq` reduce to `mem_seq`, the following explicit type *) (* annotation for `allss` makes it work for both cases. *) #[export] Hint Extern 0 (is_true (all _ _)) => apply: (allss : forall T s, all (mem_seq s) s) : core. Section NthTheory. Lemma nthP (T : eqType) (s : seq T) x x0 : reflect (exists2 i, i < size s & nth x0 s i = x) (x \in s). Proof. apply: (iffP idP) => [|[n Hn <-]]; last exact: mem_nth. by exists (index x s); [rewrite index_mem | apply nth_index]. Qed. Variable T : Type. Implicit Types (a : pred T) (x : T). Lemma has_nthP a s x0 : reflect (exists2 i, i < size s & a (nth x0 s i)) (has a s). Proof. elim: s => [|x s IHs] /=; first by right; case. case nax: (a x); first by left; exists 0. by apply: (iffP IHs) => [[i]|[[|i]]]; [exists i.+1 | rewrite nax | exists i]. Qed. Lemma all_nthP a s x0 : reflect (forall i, i < size s -> a (nth x0 s i)) (all a s). Proof. rewrite -(eq_all (fun x => negbK (a x))) all_predC. case: (has_nthP _ _ x0) => [na_s | a_s]; [right=> a_s | left=> i lti]. by case: na_s => i lti; rewrite a_s. by apply/idPn=> na_si; case: a_s; exists i. Qed. Lemma set_nthE s x0 n x : set_nth x0 s n x = if n < size s then take n s ++ x :: drop n.+1 s else s ++ ncons (n - size s) x0 [:: x]. Proof. elim: s n => [|a s IH] n /=; first by rewrite subn0 set_nth_nil. case: n => [|n]; first by rewrite drop0. by rewrite ltnS /=; case: ltnP (IH n) => _ ->. Qed. Lemma count_set_nth a s x0 n x : count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n) * (n < size s) + (a x0) * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. rewrite -cat_nseq !count_cat count_nseq /=. by rewrite muln0 addn0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in count a s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !count_cat/= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma count_set_nth_ltn a s x0 n x : n < size s -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> nlts; rewrite count_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma count_set_nthF a s x0 n x : ~~ a x0 -> count a (set_nth x0 s n x) = count a s + a x - a (nth x0 s n). Proof. move=> /negbTE ax0; rewrite count_set_nth ax0 mul0n addn0. case: ltnP => [_|nges]; first by rewrite muln1. by rewrite nth_default// ax0 subn0. Qed. End NthTheory. Lemma set_nth_default T s (y0 x0 : T) n : n < size s -> nth x0 s n = nth y0 s n. Proof. by elim: s n => [|y s' IHs] [|n] //= /IHs. Qed. Lemma headI T s (x : T) : rcons s x = head x s :: behead (rcons s x). Proof. by case: s. Qed. Arguments nthP {T s x}. Arguments has_nthP {T a s}. Arguments all_nthP {T a s}. Definition bitseq := seq bool. #[hnf] HB.instance Definition _ := Equality.on bitseq. Canonical bitseq_predType := Eval hnf in [predType of bitseq]. (* Generalizations of splitP (from path.v): split_find_nth and split_find *) Section FindNth. Variables (T : Type). Implicit Types (x : T) (p : pred T) (s : seq T). Variant split_find_nth_spec p : seq T -> seq T -> seq T -> T -> Type := FindNth x s1 s2 of p x & ~~ has p s1 : split_find_nth_spec p (rcons s1 x ++ s2) s1 s2 x. Lemma split_find_nth x0 p s (i := find p s) : has p s -> split_find_nth_spec p s (take i s) (drop i.+1 s) (nth x0 s i). Proof. move=> p_s; rewrite -[X in split_find_nth_spec _ X](cat_take_drop i s). rewrite (drop_nth x0 _) -?has_find// -cat_rcons. by constructor; [apply: nth_find | rewrite has_take -?leqNgt]. Qed. Variant split_find_spec p : seq T -> seq T -> seq T -> Type := FindSplit x s1 s2 of p x & ~~ has p s1 : split_find_spec p (rcons s1 x ++ s2) s1 s2. Lemma split_find p s (i := find p s) : has p s -> split_find_spec p s (take i s) (drop i.+1 s). Proof. by case: s => // x ? in i * => ?; case: split_find_nth => //; constructor. Qed. Lemma nth_rcons_cat_find x0 p s1 s2 x (s := rcons s1 x ++ s2) : p x -> ~~ has p s1 -> nth x0 s (find p s) = x. Proof. move=> pz pNs1; rewrite /s cat_rcons find_cat (negPf pNs1). by rewrite nth_cat/= pz addn0 subnn ltnn. Qed. End FindNth. (* Incrementing the ith nat in a seq nat, padding with 0's if needed. This *) (* allows us to use nat seqs as bags of nats. *) Fixpoint incr_nth v i {struct i} := if v is n :: v' then if i is i'.+1 then n :: incr_nth v' i' else n.+1 :: v' else ncons i 0 [:: 1]. Arguments incr_nth : simpl nomatch. Lemma nth_incr_nth v i j : nth 0 (incr_nth v i) j = (i == j) + nth 0 v j. Proof. elim: v i j => [|n v IHv] [|i] [|j] //=; rewrite ?eqSS ?addn0 //; try by case j. elim: i j => [|i IHv] [|j] //=; rewrite ?eqSS //; by case j. Qed. Lemma size_incr_nth v i : size (incr_nth v i) = if i < size v then size v else i.+1. Proof. elim: v i => [|n v IHv] [|i] //=; first by rewrite size_ncons /= addn1. by rewrite IHv; apply: fun_if. Qed. Lemma incr_nth_inj v : injective (incr_nth v). Proof. move=> i j /(congr1 (nth 0 ^~ i)); apply: contra_eq => neq_ij. by rewrite !nth_incr_nth eqn_add2r eqxx /nat_of_bool ifN_eqC. Qed. Lemma incr_nthC v i j : incr_nth (incr_nth v i) j = incr_nth (incr_nth v j) i. Proof. apply: (@eq_from_nth _ 0) => [|k _]; last by rewrite !nth_incr_nth addnCA. by do !rewrite size_incr_nth leqNgt if_neg -/(maxn _ _); apply: maxnAC. Qed. (* Equality up to permutation *) Section PermSeq. Variable T : eqType. Implicit Type s : seq T. Definition perm_eq s1 s2 := all [pred x | count_mem x s1 == count_mem x s2] (s1 ++ s2). Lemma permP s1 s2 : reflect (count^~ s1 =1 count^~ s2) (perm_eq s1 s2). Proof. apply: (iffP allP) => /= [eq_cnt1 a | eq_cnt x _]; last exact/eqP. have [n le_an] := ubnP (count a (s1 ++ s2)); elim: n => // n IHn in a le_an *. have [/eqP|] := posnP (count a (s1 ++ s2)). by rewrite count_cat addn_eq0; do 2!case: eqP => // ->. rewrite -has_count => /hasP[x s12x a_x]; pose a' := predD1 a x. have cnt_a' s: count a s = count_mem x s + count a' s. rewrite -count_predUI -[LHS]addn0 -(count_pred0 s). by congr (_ + _); apply: eq_count => y /=; case: eqP => // ->. rewrite !cnt_a' (eqnP (eq_cnt1 _ s12x)) (IHn a') // -ltnS. apply: leq_trans le_an. by rewrite ltnS cnt_a' -add1n leq_add2r -has_count has_pred1. Qed. Lemma perm_refl s : perm_eq s s. Proof. exact/permP. Qed. Hint Resolve perm_refl : core. Lemma perm_sym : symmetric perm_eq. Proof. by move=> s1 s2; apply/permP/permP=> eq_s12 a. Qed. Lemma perm_trans : transitive perm_eq. Proof. by move=> s2 s1 s3 /permP-eq12 /permP/(ftrans eq12)/permP. Qed. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Lemma permEl s1 s2 : perm_eql s1 s2 -> perm_eq s1 s2. Proof. by move->. Qed. Lemma permPl s1 s2 : reflect (perm_eql s1 s2) (perm_eq s1 s2). Proof. apply: (iffP idP) => [eq12 s3 | -> //]; apply/idP/idP; last exact: perm_trans. by rewrite -!(perm_sym s3) => /perm_trans; apply. Qed. Lemma permPr s1 s2 : reflect (perm_eqr s1 s2) (perm_eq s1 s2). Proof. by apply/(iffP idP) => [/permPl eq12 s3| <- //]; rewrite !(perm_sym s3) eq12. Qed. Lemma perm_catC s1 s2 : perm_eql (s1 ++ s2) (s2 ++ s1). Proof. by apply/permPl/permP=> a; rewrite !count_cat addnC. Qed. Lemma perm_cat2l s1 s2 s3 : perm_eq (s1 ++ s2) (s1 ++ s3) = perm_eq s2 s3. Proof. apply/permP/permP=> eq23 a; apply/eqP; by move/(_ a)/eqP: eq23; rewrite !count_cat eqn_add2l. Qed. Lemma perm_catl s t1 t2 : perm_eq t1 t2 -> perm_eql (s ++ t1) (s ++ t2). Proof. by move=> eq_t12; apply/permPl; rewrite perm_cat2l. Qed. Lemma perm_cons x s1 s2 : perm_eq (x :: s1) (x :: s2) = perm_eq s1 s2. Proof. exact: (perm_cat2l [::x]). Qed. Lemma perm_cat2r s1 s2 s3 : perm_eq (s2 ++ s1) (s3 ++ s1) = perm_eq s2 s3. Proof. by do 2!rewrite perm_sym perm_catC; apply: perm_cat2l. Qed. Lemma perm_catr s1 s2 t : perm_eq s1 s2 -> perm_eql (s1 ++ t) (s2 ++ t). Proof. by move=> eq_s12; apply/permPl; rewrite perm_cat2r. Qed. Lemma perm_cat s1 s2 t1 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq (s1 ++ t1) (s2 ++ t2). Proof. by move=> /perm_catr-> /perm_catl->. Qed. Lemma perm_catAC s1 s2 s3 : perm_eql ((s1 ++ s2) ++ s3) ((s1 ++ s3) ++ s2). Proof. by apply/permPl; rewrite -!catA perm_cat2l perm_catC. Qed. Lemma perm_catCA s1 s2 s3 : perm_eql (s1 ++ s2 ++ s3) (s2 ++ s1 ++ s3). Proof. by apply/permPl; rewrite !catA perm_cat2r perm_catC. Qed. Lemma perm_catACA s1 s2 s3 s4 : perm_eql ((s1 ++ s2) ++ (s3 ++ s4)) ((s1 ++ s3) ++ (s2 ++ s4)). Proof. by apply/permPl; rewrite perm_catAC !catA perm_catAC. Qed. Lemma perm_rcons x s : perm_eql (rcons s x) (x :: s). Proof. by move=> /= s2; rewrite -cats1 perm_catC. Qed. Lemma perm_rot n s : perm_eql (rot n s) s. Proof. by move=> /= s2; rewrite perm_catC cat_take_drop. Qed. Lemma perm_rotr n s : perm_eql (rotr n s) s. Proof. exact: perm_rot. Qed. Lemma perm_rev s : perm_eql (rev s) s. Proof. by apply/permPl/permP=> i; rewrite count_rev. Qed. Lemma perm_filter s1 s2 a : perm_eq s1 s2 -> perm_eq (filter a s1) (filter a s2). Proof. by move/permP=> s12_count; apply/permP=> Q; rewrite !count_filter. Qed. Lemma perm_filterC a s : perm_eql (filter a s ++ filter (predC a) s) s. Proof. apply/permPl; elim: s => //= x s IHs. by case: (a x); last rewrite /= -cat1s perm_catCA; rewrite perm_cons. Qed. Lemma perm_size s1 s2 : perm_eq s1 s2 -> size s1 = size s2. Proof. by move/permP=> eq12; rewrite -!count_predT eq12. Qed. Lemma perm_mem s1 s2 : perm_eq s1 s2 -> s1 =i s2. Proof. by move/permP=> eq12 x; rewrite -!has_pred1 !has_count eq12. Qed. Lemma perm_nilP s : reflect (s = [::]) (perm_eq s [::]). Proof. by apply: (iffP idP) => [/perm_size/eqP/nilP | ->]. Qed. Lemma perm_consP x s t : reflect (exists i u, rot i t = x :: u /\ perm_eq u s) (perm_eq t (x :: s)). Proof. apply: (iffP idP) => [eq_txs | [i [u [Dt eq_us]]]]. have /rot_to[i u Dt]: x \in t by rewrite (perm_mem eq_txs) mem_head. by exists i, u; rewrite -(perm_cons x) -Dt perm_rot. by rewrite -(perm_rot i) Dt perm_cons. Qed. Lemma perm_has s1 s2 a : perm_eq s1 s2 -> has a s1 = has a s2. Proof. by move/perm_mem/eq_has_r. Qed. Lemma perm_all s1 s2 a : perm_eq s1 s2 -> all a s1 = all a s2. Proof. by move/perm_mem/eq_all_r. Qed. Lemma perm_small_eq s1 s2 : size s2 <= 1 -> perm_eq s1 s2 -> s1 = s2. Proof. move=> s2_le1 eqs12; move/perm_size: eqs12 s2_le1 (perm_mem eqs12). by case: s2 s1 => [|x []] // [|y []] // _ _ /(_ x) /[!(inE, eqxx)] /eqP->. Qed. Lemma uniq_leq_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s1 <= size s2. Proof. elim: s1 s2 => //= x s1 IHs s2 /andP[not_s1x Us1] /forall_cons[s2x ss12]. have [i s3 def_s2] := rot_to s2x; rewrite -(size_rot i s2) def_s2. apply: IHs => // y s1y; have:= ss12 y s1y. by rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). Qed. Lemma leq_size_uniq s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> uniq s2. Proof. elim: s1 s2 => [[] | x s1 IHs s2] // Us1x; have /andP[not_s1x Us1] := Us1x. case/forall_cons => /rot_to[i s3 def_s2] ss12 le_s21. rewrite -(rot_uniq i) -(size_rot i) def_s2 /= in le_s21 *. have ss13 y (s1y : y \in s1): y \in s3. by have:= ss12 y s1y; rewrite -(mem_rot i) def_s2 inE (negPf (memPn _ y s1y)). rewrite IHs // andbT; apply: contraL _ le_s21 => s3x; rewrite -leqNgt. by apply/(uniq_leq_size Us1x)/allP; rewrite /= s3x; apply/allP. Qed. Lemma uniq_size_uniq s1 s2 : uniq s1 -> s1 =i s2 -> uniq s2 = (size s2 == size s1). Proof. move=> Us1 eqs12; apply/idP/idP=> [Us2 | /eqP eq_sz12]. by rewrite eqn_leq !uniq_leq_size // => y; rewrite eqs12. by apply: (leq_size_uniq Us1) => [y|]; rewrite (eqs12, eq_sz12). Qed. Lemma uniq_min_size s1 s2 : uniq s1 -> {subset s1 <= s2} -> size s2 <= size s1 -> (size s1 = size s2) * (s1 =i s2). Proof. move=> Us1 ss12 le_s21; have Us2: uniq s2 := leq_size_uniq Us1 ss12 le_s21. suffices: s1 =i s2 by split; first by apply/eqP; rewrite -uniq_size_uniq. move=> x; apply/idP/idP=> [/ss12// | s2x]; apply: contraLR le_s21 => not_s1x. rewrite -ltnNge (@uniq_leq_size (x :: s1)) /= ?not_s1x //. by apply/allP; rewrite /= s2x; apply/allP. Qed. Lemma eq_uniq s1 s2 : size s1 = size s2 -> s1 =i s2 -> uniq s1 = uniq s2. Proof. move=> eq_sz12 eq_s12. by apply/idP/idP=> Us; rewrite (uniq_size_uniq Us) ?eq_sz12 ?eqxx. Qed. Lemma perm_uniq s1 s2 : perm_eq s1 s2 -> uniq s1 = uniq s2. Proof. by move=> eq_s12; apply/eq_uniq; [apply/perm_size | apply/perm_mem]. Qed. Lemma uniq_perm s1 s2 : uniq s1 -> uniq s2 -> s1 =i s2 -> perm_eq s1 s2. Proof. move=> Us1 Us2 eq12; apply/allP=> x _; apply/eqP. by rewrite !count_uniq_mem ?eq12. Qed. Lemma perm_undup s1 s2 : s1 =i s2 -> perm_eq (undup s1) (undup s2). Proof. by move=> Es12; rewrite uniq_perm ?undup_uniq // => s; rewrite !mem_undup. Qed. Lemma count_mem_uniq s : (forall x, count_mem x s = (x \in s)) -> uniq s. Proof. move=> count1_s; have Uus := undup_uniq s. suffices: perm_eq s (undup s) by move/perm_uniq->. by apply/allP=> x _; apply/eqP; rewrite (count_uniq_mem x Uus) mem_undup. Qed. Lemma eq_count_undup a s1 s2 : {in a, s1 =i s2} -> count a (undup s1) = count a (undup s2). Proof. move=> s1_eq_s2; rewrite -!size_filter !filter_undup. apply/perm_size/perm_undup => x. by rewrite !mem_filter; case: (boolP (a x)) => //= /s1_eq_s2. Qed. Lemma catCA_perm_ind P : (forall s1 s2 s3, P (s1 ++ s2 ++ s3) -> P (s2 ++ s1 ++ s3)) -> (forall s1 s2, perm_eq s1 s2 -> P s1 -> P s2). Proof. move=> PcatCA s1 s2 eq_s12; rewrite -[s1]cats0 -[s2]cats0. elim: s2 nil => [|x s2 IHs] s3 in s1 eq_s12 *. by case: s1 {eq_s12}(perm_size eq_s12). have /rot_to[i s' def_s1]: x \in s1 by rewrite (perm_mem eq_s12) mem_head. rewrite -(cat_take_drop i s1) -catA => /PcatCA. rewrite catA -/(rot i s1) def_s1 /= -cat1s => /PcatCA/IHs/PcatCA; apply. by rewrite -(perm_cons x) -def_s1 perm_rot. Qed. Lemma catCA_perm_subst R F : (forall s1 s2 s3, F (s1 ++ s2 ++ s3) = F (s2 ++ s1 ++ s3) :> R) -> (forall s1 s2, perm_eq s1 s2 -> F s1 = F s2). Proof. move=> FcatCA s1 s2 /catCA_perm_ind => ind_s12. by apply: (ind_s12 (eq _ \o F)) => //= *; rewrite FcatCA. Qed. End PermSeq. Notation perm_eql s1 s2 := (perm_eq s1 =1 perm_eq s2). Notation perm_eqr s1 s2 := (perm_eq^~ s1 =1 perm_eq^~ s2). Arguments permP {T s1 s2}. Arguments permPl {T s1 s2}. Arguments permPr {T s1 s2}. Prenex Implicits perm_eq. #[global] Hint Resolve perm_refl : core. Section RotrLemmas. Variables (n0 : nat) (T : Type) (T' : eqType). Implicit Types (x : T) (s : seq T). Lemma size_rotr s : size (rotr n0 s) = size s. Proof. by rewrite size_rot. Qed. Lemma mem_rotr (s : seq T') : rotr n0 s =i s. Proof. by move=> x; rewrite mem_rot. Qed. Lemma rotr_size_cat s1 s2 : rotr (size s2) (s1 ++ s2) = s2 ++ s1. Proof. by rewrite /rotr size_cat addnK rot_size_cat. Qed. Lemma rotr1_rcons x s : rotr 1 (rcons s x) = x :: s. Proof. by rewrite -rot1_cons rotK. Qed. Lemma has_rotr a s : has a (rotr n0 s) = has a s. Proof. by rewrite has_rot. Qed. Lemma rotr_uniq (s : seq T') : uniq (rotr n0 s) = uniq s. Proof. by rewrite rot_uniq. Qed. Lemma rotrK : cancel (@rotr T n0) (rot n0). Proof. move=> s; have [lt_n0s | ge_n0s] := ltnP n0 (size s). by rewrite -{1}(subKn (ltnW lt_n0s)) -{1}[size s]size_rotr; apply: rotK. by rewrite -[in RHS](rot_oversize ge_n0s) /rotr (eqnP ge_n0s) rot0. Qed. Lemma rotr_inj : injective (@rotr T n0). Proof. exact (can_inj rotrK). Qed. Lemma take_rev s : take n0 (rev s) = rev (drop (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat take_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?subnn take0 cats0. Qed. Lemma rev_take s : rev (take n0 s) = drop (size s - n0) (rev s). Proof. by rewrite -[s in take _ s]revK take_rev revK size_rev. Qed. Lemma drop_rev s : drop n0 (rev s) = rev (take (size s - n0) s). Proof. set m := _ - n0; rewrite -[s in LHS](cat_take_drop m) rev_cat drop_cat. rewrite size_rev size_drop -minnE minnC leq_min ltnn /m. by have [_|/eqnP->] := ltnP; rewrite ?take0 // subnn drop0. Qed. Lemma rev_drop s : rev (drop n0 s) = take (size s - n0) (rev s). Proof. by rewrite -[s in drop _ s]revK drop_rev revK size_rev. Qed. Lemma rev_rotr s : rev (rotr n0 s) = rot n0 (rev s). Proof. by rewrite rev_cat -take_rev -drop_rev. Qed. Lemma rev_rot s : rev (rot n0 s) = rotr n0 (rev s). Proof. by apply: canLR revK _; rewrite rev_rotr revK. Qed. End RotrLemmas. Arguments rotrK n0 {T} s : rename. Arguments rotr_inj {n0 T} [s1 s2] eq_rotr_s12 : rename. Section RotCompLemmas. Variable T : Type. Implicit Type s : seq T. Lemma rotD m n s : m + n <= size s -> rot (m + n) s = rot m (rot n s). Proof. move=> sz_s; rewrite [LHS]/rot -[take _ s](cat_take_drop n). rewrite 5!(catA, =^~ rot_size_cat) !cat_take_drop. by rewrite size_drop !size_takel ?leq_addl ?addnK. Qed. Lemma rotS n s : n < size s -> rot n.+1 s = rot 1 (rot n s). Proof. exact: (@rotD 1). Qed. Lemma rot_add_mod m n s : n <= size s -> m <= size s -> rot m (rot n s) = rot (if m + n <= size s then m + n else m + n - size s) s. Proof. move=> Hn Hm; case: leqP => [/rotD // | /ltnW Hmn]; symmetry. by rewrite -{2}(rotK n s) /rotr -rotD size_rot addnBA ?subnK ?addnK. Qed. Lemma rot_minn n s : rot n s = rot (minn n (size s)) s. Proof. by case: (leqP n (size s)) => // /leqW ?; rewrite rot_size rot_oversize. Qed. Definition rot_add s n m (k := size s) (p := minn m k + minn n k) := locked (if p <= k then p else p - k). Lemma leq_rot_add n m s : rot_add s n m <= size s. Proof. by unlock rot_add; case: ifP; rewrite // leq_subLR leq_add // geq_minr. Qed. Lemma rot_addC n m s : rot_add s n m = rot_add s m n. Proof. by unlock rot_add; rewrite ![minn n _ + _]addnC. Qed. Lemma rot_rot_add n m s : rot m (rot n s) = rot (rot_add s n m) s. Proof. unlock rot_add. by rewrite (rot_minn n) (rot_minn m) rot_add_mod ?size_rot ?geq_minr. Qed. Lemma rot_rot m n s : rot m (rot n s) = rot n (rot m s). Proof. by rewrite rot_rot_add rot_addC -rot_rot_add. Qed. Lemma rot_rotr m n s : rot m (rotr n s) = rotr n (rot m s). Proof. by rewrite [RHS]/rotr size_rot rot_rot. Qed. Lemma rotr_rotr m n s : rotr m (rotr n s) = rotr n (rotr m s). Proof. by rewrite /rotr !size_rot rot_rot. Qed. End RotCompLemmas. Section Mask. Variables (n0 : nat) (T : Type). Implicit Types (m : bitseq) (s : seq T). Fixpoint mask m s {struct m} := match m, s with | b :: m', x :: s' => if b then x :: mask m' s' else mask m' s' | _, _ => [::] end. Lemma mask_false s n : mask (nseq n false) s = [::]. Proof. by elim: s n => [|x s IHs] [|n] /=. Qed. Lemma mask_true s n : size s <= n -> mask (nseq n true) s = s. Proof. by elim: s n => [|x s IHs] [|n] //= Hn; congr (_ :: _); apply: IHs. Qed. Lemma mask0 m : mask m [::] = [::]. Proof. by case: m. Qed. Lemma mask0s s : mask [::] s = [::]. Proof. by []. Qed. Lemma mask1 b x : mask [:: b] [:: x] = nseq b x. Proof. by case: b. Qed. Lemma mask_cons b m x s : mask (b :: m) (x :: s) = nseq b x ++ mask m s. Proof. by case: b. Qed. Lemma size_mask m s : size m = size s -> size (mask m s) = count id m. Proof. by move: m s; apply: seq_ind2 => // -[] x m s /= _ ->. Qed. Lemma mask_cat m1 m2 s1 s2 : size m1 = size s1 -> mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2. Proof. by move: m1 s1; apply: seq_ind2 => // -[] m1 x1 s1 /= _ ->. Qed. Lemma mask_rcons b m x s : size m = size s -> mask (rcons m b) (rcons s x) = mask m s ++ nseq b x. Proof. by move=> ms; rewrite -!cats1 mask_cat//; case: b. Qed. Lemma all_mask a m s : all a s -> all a (mask m s). Proof. by elim: s m => [|x s IHs] [|[] m]//= /andP[ax /IHs->]; rewrite ?ax. Qed. Lemma has_mask_cons a b m x s : has a (mask (b :: m) (x :: s)) = b && a x || has a (mask m s). Proof. by case: b. Qed. Lemma has_mask a m s : has a (mask m s) -> has a s. Proof. by apply/contraTT; rewrite -!all_predC; apply: all_mask. Qed. Lemma rev_mask m s : size m = size s -> rev (mask m s) = mask (rev m) (rev s). Proof. move: m s; apply: seq_ind2 => //= b x m s eq_size_sm IH. by case: b; rewrite !rev_cons mask_rcons ?IH ?size_rev// (cats1, cats0). Qed. Lemma mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) = rot (count id (take n0 m)) (mask m s). Proof. move=> Ems; rewrite mask_cat ?size_drop ?Ems // -rot_size_cat. by rewrite size_mask -?mask_cat ?size_take ?Ems // !cat_take_drop. Qed. Lemma resize_mask m s : {m1 | size m1 = size s & mask m s = mask m1 s}. Proof. exists (take (size s) m ++ nseq (size s - size m) false). by elim: s m => [|x s IHs] [|b m] //=; rewrite (size_nseq, IHs). by elim: s m => [|x s IHs] [|b m] //=; rewrite (mask_false, IHs). Qed. Lemma takeEmask i s : take i s = mask (nseq i true) s. Proof. by elim: i s => [s|i IHi []// ? ?]; rewrite ?take0 //= IHi. Qed. Lemma dropEmask i s : drop i s = mask (nseq i false ++ nseq (size s - i) true) s. Proof. by elim: i s => [s|? ? []//]; rewrite drop0/= mask_true// subn0. Qed. End Mask. Arguments mask _ !_ !_. Section EqMask. Variables (n0 : nat) (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mem_mask_cons x b m y s : (x \in mask (b :: m) (y :: s)) = b && (x == y) || (x \in mask m s). Proof. by case: b. Qed. Lemma mem_mask x m s : x \in mask m s -> x \in s. Proof. by rewrite -!has_pred1 => /has_mask. Qed. Lemma in_mask x m s : uniq s -> x \in mask m s = (x \in s) && nth false m (index x s). Proof. elim: s m => [|y s IHs] [|[] m]//= /andP[yNs ?]; rewrite ?in_cons ?IHs //=; by have [->|neq_xy] //= := eqVneq; rewrite ?andbF // (negPf yNs). Qed. Lemma mask_uniq s : uniq s -> forall m, uniq (mask m s). Proof. elim: s => [|x s IHs] Uxs [|b m] //=. case: b Uxs => //= /andP[s'x Us]; rewrite {}IHs // andbT. by apply: contra s'x; apply: mem_mask. Qed. Lemma mem_mask_rot m s : size m = size s -> mask (rot n0 m) (rot n0 s) =i mask m s. Proof. by move=> Ems x; rewrite mask_rot // mem_rot. Qed. End EqMask. Section Subseq. Variable T : eqType. Implicit Type s : seq T. Fixpoint subseq s1 s2 := if s2 is y :: s2' then if s1 is x :: s1' then subseq (if x == y then s1' else s1) s2' else true else s1 == [::]. Lemma sub0seq s : subseq [::] s. Proof. by case: s. Qed. Lemma subseq0 s : subseq s [::] = (s == [::]). Proof. by []. Qed. Lemma subseq_refl s : subseq s s. Proof. by elim: s => //= x s IHs; rewrite eqxx. Qed. Hint Resolve subseq_refl : core. Lemma subseqP s1 s2 : reflect (exists2 m, size m = size s2 & s1 = mask m s2) (subseq s1 s2). Proof. elim: s2 s1 => [|y s2 IHs2] [|x s1]. - by left; exists [::]. - by right=> -[m /eqP/nilP->]. - by left; exists (nseq (size s2).+1 false); rewrite ?size_nseq //= mask_false. apply: {IHs2}(iffP (IHs2 _)) => [] [m sz_m def_s1]. by exists ((x == y) :: m); rewrite /= ?sz_m // -def_s1; case: eqP => // ->. case: eqP => [_ | ne_xy]; last first. by case: m def_s1 sz_m => [|[] m] //; [case | move=> -> [<-]; exists m]. pose i := index true m; have def_m_i: take i m = nseq (size (take i m)) false. apply/all_pred1P; apply/(all_nthP true) => j. rewrite size_take ltnNge geq_min negb_or -ltnNge => /andP[lt_j_i _]. rewrite nth_take //= -negb_add addbF -addbT -negb_eqb. by rewrite [_ == _](before_find _ lt_j_i). have lt_i_m: i < size m. rewrite ltnNge; apply/negP=> le_m_i; rewrite take_oversize // in def_m_i. by rewrite def_m_i mask_false in def_s1. rewrite size_take lt_i_m in def_m_i. exists (take i m ++ drop i.+1 m). rewrite size_cat size_take size_drop lt_i_m. by rewrite sz_m in lt_i_m *; rewrite subnKC. rewrite {s1 def_s1}[s1](congr1 behead def_s1). rewrite -[s2](cat_take_drop i) -[m in LHS](cat_take_drop i) {}def_m_i -cat_cons. have sz_i_s2: size (take i s2) = i by apply: size_takel; rewrite sz_m in lt_i_m. rewrite lastI cat_rcons !mask_cat ?size_nseq ?size_belast ?mask_false //=. by rewrite (drop_nth true) // nth_index -?index_mem. Qed. Lemma mask_subseq m s : subseq (mask m s) s. Proof. by apply/subseqP; have [m1] := resize_mask m s; exists m1. Qed. Lemma subseq_trans : transitive subseq. Proof. move=> _ _ s /subseqP[m2 _ ->] /subseqP[m1 _ ->]. elim: s => [|x s IHs] in m2 m1 *; first by rewrite !mask0. case: m1 => [|[] m1]; first by rewrite mask0. case: m2 => [|[] m2] //; first by rewrite /= eqxx IHs. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. case/subseqP: (IHs m2 m1) => m sz_m def_s; apply/subseqP. by exists (false :: m); rewrite //= sz_m. Qed. Lemma cat_subseq s1 s2 s3 s4 : subseq s1 s3 -> subseq s2 s4 -> subseq (s1 ++ s2) (s3 ++ s4). Proof. case/subseqP=> m1 sz_m1 -> /subseqP [m2 sz_m2 ->]; apply/subseqP. by exists (m1 ++ m2); rewrite ?size_cat ?mask_cat ?sz_m1 ?sz_m2. Qed. Lemma prefix_subseq s1 s2 : subseq s1 (s1 ++ s2). Proof. by rewrite -[s1 in subseq s1]cats0 cat_subseq ?sub0seq. Qed. Lemma suffix_subseq s1 s2 : subseq s2 (s1 ++ s2). Proof. exact: cat_subseq (sub0seq s1) _. Qed. Lemma take_subseq s i : subseq (take i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) prefix_subseq. Qed. Lemma drop_subseq s i : subseq (drop i s) s. Proof. by rewrite -[s in X in subseq _ X](cat_take_drop i) suffix_subseq. Qed. Lemma mem_subseq s1 s2 : subseq s1 s2 -> {subset s1 <= s2}. Proof. by case/subseqP=> m _ -> x; apply: mem_mask. Qed. Lemma sub1seq x s : subseq [:: x] s = (x \in s). Proof. by elim: s => //= y s /[1!inE]; case: ifP; rewrite ?sub0seq. Qed. Lemma size_subseq s1 s2 : subseq s1 s2 -> size s1 <= size s2. Proof. by case/subseqP=> m sz_m ->; rewrite size_mask -sz_m ?count_size. Qed. Lemma size_subseq_leqif s1 s2 : subseq s1 s2 -> size s1 <= size s2 ?= iff (s1 == s2). Proof. move=> sub12; split; first exact: size_subseq. apply/idP/eqP=> [|-> //]; case/subseqP: sub12 => m sz_m ->{s1}. rewrite size_mask -sz_m // -all_count -(eq_all eqb_id). by move/(@all_pred1P _ true)->; rewrite sz_m mask_true. Qed. Lemma subseq_anti : antisymmetric subseq. Proof. move=> s1 s2 /andP[] /size_subseq_leqif /leqifP. by case: eqP => [//|_] + /size_subseq; rewrite ltnNge => /negP. Qed. Lemma subseq_cons s x : subseq s (x :: s). Proof. exact: suffix_subseq [:: x] s. Qed. Lemma cons_subseq s1 s2 x : subseq (x :: s1) s2 -> subseq s1 s2. Proof. exact/subseq_trans/subseq_cons. Qed. Lemma subseq_rcons s x : subseq s (rcons s x). Proof. by rewrite -cats1 prefix_subseq. Qed. Lemma subseq_uniq s1 s2 : subseq s1 s2 -> uniq s2 -> uniq s1. Proof. by case/subseqP=> m _ -> Us2; apply: mask_uniq. Qed. Lemma take_uniq s n : uniq s -> uniq (take n s). Proof. exact/subseq_uniq/take_subseq. Qed. Lemma drop_uniq s n : uniq s -> uniq (drop n s). Proof. exact/subseq_uniq/drop_subseq. Qed. Lemma undup_subseq s : subseq (undup s) s. Proof. elim: s => //= x s; case: (_ \in _); last by rewrite eqxx. by case: (undup s) => //= y u; case: (_ == _) => //=; apply: cons_subseq. Qed. Lemma subseq_rev s1 s2 : subseq (rev s1) (rev s2) = subseq s1 s2. Proof. wlog suff W : s1 s2 / subseq s1 s2 -> subseq (rev s1) (rev s2). by apply/idP/idP => /W //; rewrite !revK. by case/subseqP => m size_m ->; rewrite rev_mask // mask_subseq. Qed. Lemma subseq_cat2l s s1 s2 : subseq (s ++ s1) (s ++ s2) = subseq s1 s2. Proof. by elim: s => // x s IHs; rewrite !cat_cons /= eqxx. Qed. Lemma subseq_cat2r s s1 s2 : subseq (s1 ++ s) (s2 ++ s) = subseq s1 s2. Proof. by rewrite -subseq_rev !rev_cat subseq_cat2l subseq_rev. Qed. Lemma subseq_rot p s n : subseq p s -> exists2 k, k <= n & subseq (rot k p) (rot n s). Proof. move=> /subseqP[m size_m ->]. exists (count id (take n m)); last by rewrite -mask_rot // mask_subseq. by rewrite (leq_trans (count_size _ _))// size_take_min geq_minl. Qed. End Subseq. Prenex Implicits subseq. Arguments subseqP {T s1 s2}. #[global] Hint Resolve subseq_refl : core. Section Rem. Variables (T : eqType) (x : T). Fixpoint rem s := if s is y :: t then (if y == x then t else y :: rem t) else s. Lemma rem_cons y s : rem (y :: s) = if y == x then s else y :: rem s. Proof. by []. Qed. Lemma remE s : rem s = take (index x s) s ++ drop (index x s).+1 s. Proof. by elim: s => //= y s ->; case: eqVneq; rewrite ?drop0. Qed. Lemma rem_id s : x \notin s -> rem s = s. Proof. by elim: s => //= y s IHs /norP[neq_yx /IHs->]; case: eqVneq neq_yx. Qed. Lemma perm_to_rem s : x \in s -> perm_eq s (x :: rem s). Proof. move=> xs; rewrite remE -[X in perm_eq X](cat_take_drop (index x s)). by rewrite drop_index// -cat1s perm_catCA cat1s. Qed. Lemma size_rem s : x \in s -> size (rem s) = (size s).-1. Proof. by move/perm_to_rem/perm_size->. Qed. Lemma rem_subseq s : subseq (rem s) s. Proof. elim: s => //= y s IHs; rewrite eq_sym. by case: ifP => _; [apply: subseq_cons | rewrite eqxx]. Qed. Lemma rem_uniq s : uniq s -> uniq (rem s). Proof. by apply: subseq_uniq; apply: rem_subseq. Qed. Lemma mem_rem s : {subset rem s <= s}. Proof. exact: mem_subseq (rem_subseq s). Qed. Lemma rem_mem y s : y != x -> y \in s -> y \in rem s. Proof. move=> yx; elim: s => [//|z s IHs] /=. rewrite inE => /orP[/eqP<-|ys]; first by rewrite (negbTE yx) inE eqxx. by case: ifP => _ //; rewrite inE IHs ?orbT. Qed. Lemma rem_filter s : uniq s -> rem s = filter (predC1 x) s. Proof. elim: s => //= y s IHs /andP[not_s_y /IHs->]. by case: eqP => //= <-; apply/esym/all_filterP; rewrite all_predC has_pred1. Qed. Lemma mem_rem_uniq s : uniq s -> rem s =i [predD1 s & x]. Proof. by move/rem_filter=> -> y; rewrite mem_filter. Qed. Lemma mem_rem_uniqF s : uniq s -> x \in rem s = false. Proof. by move/mem_rem_uniq->; rewrite inE eqxx. Qed. Lemma count_rem P s : count P (rem s) = count P s - (x \in s) && P x. Proof. have [/perm_to_rem/permP->|xNs]/= := boolP (x \in s); first by rewrite addKn. by rewrite subn0 rem_id. Qed. Lemma count_mem_rem y s : count_mem y (rem s) = count_mem y s - (x == y). Proof. rewrite count_rem; have []//= := boolP (x \in s). by case: eqP => // <- /count_memPn->. Qed. End Rem. Section Map. Variables (n0 : nat) (T1 : Type) (x1 : T1). Variables (T2 : Type) (x2 : T2) (f : T1 -> T2). Fixpoint map s := if s is x :: s' then f x :: map s' else [::]. Lemma map_cons x s : map (x :: s) = f x :: map s. Proof. by []. Qed. Lemma map_nseq x : map (nseq n0 x) = nseq n0 (f x). Proof. by elim: n0 => // *; congr (_ :: _). Qed. Lemma map_cat s1 s2 : map (s1 ++ s2) = map s1 ++ map s2. Proof. by elim: s1 => [|x s1 IHs] //=; rewrite IHs. Qed. Lemma size_map s : size (map s) = size s. Proof. by elim: s => //= x s ->. Qed. Lemma behead_map s : behead (map s) = map (behead s). Proof. by case: s. Qed. Lemma nth_map n s : n < size s -> nth x2 (map s) n = f (nth x1 s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma map_rcons s x : map (rcons s x) = rcons (map s) (f x). Proof. by rewrite -!cats1 map_cat. Qed. Lemma last_map s x : last (f x) (map s) = f (last x s). Proof. by elim: s x => /=. Qed. Lemma belast_map s x : belast (f x) (map s) = map (belast x s). Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma filter_map a s : filter a (map s) = map (filter (preim f a) s). Proof. by elim: s => //= x s IHs; rewrite (fun_if map) /= IHs. Qed. Lemma find_map a s : find a (map s) = find (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma has_map a s : has a (map s) = has (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_map a s : all a (map s) = all (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma all_mapT (a : pred T2) s : (forall x, a (f x)) -> all a (map s). Proof. by rewrite all_map => /allT->. Qed. Lemma count_map a s : count a (map s) = count (preim f a) s. Proof. by elim: s => //= x s ->. Qed. Lemma map_take s : map (take n0 s) = take n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_drop s : map (drop n0 s) = drop n0 (map s). Proof. by elim: n0 s => [|n IHn] [|x s] //=; rewrite IHn. Qed. Lemma map_rot s : map (rot n0 s) = rot n0 (map s). Proof. by rewrite /rot map_cat map_take map_drop. Qed. Lemma map_rotr s : map (rotr n0 s) = rotr n0 (map s). Proof. by apply: canRL (rotK n0) _; rewrite -map_rot rotrK. Qed. Lemma map_rev s : map (rev s) = rev (map s). Proof. by elim: s => //= x s IHs; rewrite !rev_cons -!cats1 map_cat IHs. Qed. Lemma map_mask m s : map (mask m s) = mask m (map s). Proof. by elim: m s => [|[|] m IHm] [|x p] //=; rewrite IHm. Qed. Lemma inj_map : injective f -> injective map. Proof. by move=> injf; elim=> [|x s IHs] [|y t] //= [/injf-> /IHs->]. Qed. Lemma inj_in_map (A : {pred T1}) : {in A &, injective f} -> {in [pred s | all [in A] s] &, injective map}. Proof. move=> injf; elim=> [|x s IHs] [|y t] //= /andP[Ax As] /andP[Ay At]. by case=> /injf-> // /IHs->. Qed. End Map. (* Sequence indexing with error. *) Section onth. Variable T : Type. Implicit Types x y z : T. Implicit Types m n : nat. Implicit Type s : seq T. Fixpoint onth s n {struct n} : option T := if s isn't x :: s then None else if n isn't n.+1 then Some x else onth s n. Lemma odflt_onth x0 s n : odflt x0 (onth s n) = nth x0 s n. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthE s : onth s =1 nth None (map Some s). Proof. by move=> n; elim: n s => [|? ?] []. Qed. Lemma onth_nth x0 x t n : onth t n = Some x -> nth x0 t n = x. Proof. by move=> tn; rewrite -odflt_onth tn. Qed. Lemma onth0n n : onth [::] n = None. Proof. by case: n. Qed. Lemma onth1P x y n : onth [:: x] n = Some y <-> n = 0 /\ x = y. Proof. by case: n => [|[]]; split=> // -[] // _ ->. Qed. Lemma onthTE s n : onth s n = (n < size s) :> bool. Proof. by elim: n s => [|? ?] []. Qed. Lemma onthNE s n: ~~ onth s n = (size s <= n). Proof. by rewrite onthTE -leqNgt. Qed. Lemma onth_default n s : size s <= n -> onth s n = None. Proof. by rewrite -onthNE; case: onth. Qed. Lemma onth_cat s1 s2 n : onth (s1 ++ s2) n = if n < size s1 then onth s1 n else onth s2 (n - size s1). Proof. by elim: n s1 => [|? ?] []. Qed. Lemma onth_nseq x n m : onth (nseq n x) m = if m < n then Some x else None. Proof. by rewrite onthE/= -nth_nseq map_nseq. Qed. Lemma eq_onthP {s1 s2} : [<-> s1 = s2; forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i; forall i : nat, onth s1 i = onth s2 i]. Proof. tfae=> [->//|eqs12 i|eqs12]. have := eqs12 i; case: ltnP => [_ ->//|]. by rewrite geq_max => /andP[is1 is2] _; rewrite !onth_default. have /eqP eq_size_12 : size s1 == size s2. by rewrite eqn_leq -!onthNE eqs12 onthNE -eqs12 onthNE !leqnn. apply/(inj_map Some_inj)/(@eq_from_nth _ None); rewrite !size_map//. by move=> i _; rewrite -!onthE eqs12. Qed. Lemma eq_from_onth [s1 s2 : seq T] : (forall i : nat, onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 2). Qed. Lemma eq_from_onth_le [s1 s2 : seq T] : (forall i : nat, i < maxn (size s1) (size s2) -> onth s1 i = onth s2 i) -> s1 = s2. Proof. by move/(eq_onthP 0 1). Qed. End onth. Lemma onth_map {T S} n (s : seq T) (f : T -> S) : onth (map f s) n = omap f (onth s n). Proof. by elim: s n => [|x s IHs] []. Qed. Lemma inj_onth_map {T S} n (s : seq T) (f : T -> S) x : injective f -> onth (map f s) n = Some (f x) -> onth s n = Some x. Proof. by rewrite onth_map => /inj_omap + fs; apply. Qed. Section onthEqType. Variables T : eqType. Implicit Types x y z : T. Implicit Types i m n : nat. Implicit Type s : seq T. Lemma onthP s x : reflect (exists i, onth s i = Some x) (x \in s). Proof. elim: s => [|y s IHs]; first by constructor=> -[] []. rewrite in_cons; case: eqVneq => [->|/= Nxy]; first by constructor; exists 0. apply: (iffP idP) => [/IHs[i <-]|[[|i]//=]]; first by exists i.+1. by move=> [eq_xy]; rewrite eq_xy eqxx in Nxy. by move=> six; apply/IHs; exists i. Qed. Lemma onthPn s x : reflect (forall i, onth s i != Some x) (x \notin s). Proof. apply: (iffP idP); first by move=> /onthP + i; apply: contra_not_neq; exists i. by move=> nsix; apply/onthP => -[n /eqP/negPn]; rewrite nsix. Qed. Lemma onth_inj s n m : uniq s -> minn m n < size s -> onth s n = onth s m -> n = m. Proof. elim: s m n => [|x s IHs]//= [|m] [|n]//=; rewrite ?minnSS !ltnS. - by move=> /andP[+ _] _ /eqP => /onthPn/(_ _)/negPf->. - by move=> /andP[+ _] _ /esym /eqP => /onthPn/(_ _)/negPf->. by move=> /andP[xNs /IHs]/[apply]/[apply]->. Qed. End onthEqType. Arguments onthP {T s x}. Arguments onthPn {T s x}. Arguments onth_nth {T}. Arguments onth_inj {T}. Notation "[ 'seq' E | i <- s ]" := (map (fun i => E) s) (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s ] ']'") : seq_scope. Notation "[ 'seq' E | i <- s & C ]" := [seq E | i <- [seq i <- s | C]] (i binder, format "[ '[hv' 'seq' E '/ ' | i <- s '/ ' & C ] ']'") : seq_scope. Notation "[ 'seq' E : R | i <- s ]" := (@map _ R (fun i => E) s) (i binder, only parsing) : seq_scope. Notation "[ 'seq' E : R | i <- s & C ]" := [seq E : R | i <- [seq i <- s | C]] (i binder, only parsing) : seq_scope. Lemma filter_mask T a (s : seq T) : filter a s = mask (map a s) s. Proof. by elim: s => //= x s <-; case: (a x). Qed. Lemma all_sigP T a (s : seq T) : all a s -> {s' : seq (sig a) | s = map sval s'}. Proof. elim: s => /= [_|x s ihs /andP [ax /ihs [s' ->]]]; first by exists [::]. by exists (exist a x ax :: s'). Qed. Section MiscMask. Lemma leq_count_mask T (P : {pred T}) m s : count P (mask m s) <= count P s. Proof. by elim: s m => [|x s IHs] [|[] m]//=; rewrite ?leq_add2l (leq_trans (IHs _)) ?leq_addl. Qed. Variable (T : eqType). Implicit Types (s : seq T) (m : bitseq). Lemma mask_filter s m : uniq s -> mask m s = [seq i <- s | i \in mask m s]. Proof. elim: m s => [|[] m IH] [|x s /= /andP[/negP xS uS]]; rewrite ?filter_pred0 //. rewrite inE eqxx /=; congr cons; rewrite [LHS]IH//. by apply/eq_in_filter => ? /[1!inE]; case: eqP => [->|]. by case: ifP => [/mem_mask //|_]; apply: IH. Qed. Lemma leq_count_subseq P s1 s2 : subseq s1 s2 -> count P s1 <= count P s2. Proof. by move=> /subseqP[m _ ->]; rewrite leq_count_mask. Qed. Lemma count_maskP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 m : bitseq, size m = size s2 & perm_eq s1 (mask m s2). Proof. split=> [s1_le|[m _ /permP s1ms2 x]]; last by rewrite s1ms2 leq_count_mask. suff [m mP]: exists m, perm_eq s1 (mask m s2). by have [m' sm' eqm] := resize_mask m s2; exists m'; rewrite -?eqm. elim: s2 => [|x s2 IHs]//= in s1 s1_le *. by exists [::]; apply/allP => x _/=; rewrite eqn_leq s1_le. have [y|m s1s2] := IHs (rem x s1); first by rewrite count_mem_rem leq_subLR. exists ((x \in s1) :: m); have [|/rem_id<-//] := boolP (x \in s1). by move/perm_to_rem/permPl->; rewrite perm_cons. Qed. Lemma count_subseqP s1 s2 : (forall x, count_mem x s1 <= count_mem x s2) <-> exists2 s, subseq s s2 & perm_eq s1 s. Proof. split=> [/count_maskP[m _]|]; first by exists (mask m s2); rewrite ?mask_subseq. by move=> -[_/subseqP[m sm ->] ?]; apply/count_maskP; exists m. Qed. End MiscMask. Section FilterSubseq. Variable T : eqType. Implicit Types (s : seq T) (a : pred T). Lemma filter_subseq a s : subseq (filter a s) s. Proof. by apply/subseqP; exists (map a s); rewrite ?size_map ?filter_mask. Qed. Lemma subseq_filter s1 s2 a : subseq s1 (filter a s2) = all a s1 && subseq s1 s2. Proof. elim: s2 s1 => [|x s2 IHs] [|y s1] //=; rewrite ?andbF ?sub0seq //. by case a_x: (a x); rewrite /= !IHs /=; case: eqP => // ->; rewrite a_x. Qed. Lemma subseq_uniqP s1 s2 : uniq s2 -> reflect (s1 = filter [in s1] s2) (subseq s1 s2). Proof. move=> uniq_s2; apply: (iffP idP) => [ss12 | ->]; last exact: filter_subseq. apply/eqP; rewrite -size_subseq_leqif ?subseq_filter ?(introT allP) //. apply/eqP/esym/perm_size. rewrite uniq_perm ?filter_uniq ?(subseq_uniq ss12) // => x. by rewrite mem_filter; apply: andb_idr; apply: (mem_subseq ss12). Qed. Lemma uniq_subseq_pivot x (s1 s2 s3 s4 : seq T) (s := s3 ++ x :: s4) : uniq s -> subseq (s1 ++ x :: s2) s = (subseq s1 s3 && subseq s2 s4). Proof. move=> uniq_s; apply/idP/idP => [sub_s'_s|/andP[? ?]]; last first. by rewrite cat_subseq //= eqxx. have uniq_s' := subseq_uniq sub_s'_s uniq_s. have/eqP {sub_s'_s uniq_s} := subseq_uniqP _ uniq_s sub_s'_s. rewrite !filter_cat /= mem_cat inE eqxx orbT /=. rewrite uniq_eqseq_pivotl // => /andP [/eqP -> /eqP ->]. by rewrite !filter_subseq. Qed. Lemma perm_to_subseq s1 s2 : subseq s1 s2 -> {s3 | perm_eq s2 (s1 ++ s3)}. Proof. elim Ds2: s2 s1 => [|y s2' IHs] [|x s1] //=; try by exists s2; rewrite Ds2. case: eqP => [-> | _] /IHs[s3 perm_s2] {IHs}. by exists s3; rewrite perm_cons. by exists (rcons s3 y); rewrite -cat_cons -perm_rcons -!cats1 catA perm_cat2r. Qed. Lemma subseq_rem x : {homo rem x : s1 s2 / @subseq T s1 s2}. Proof. move=> s1 s2; elim: s2 s1 => [|x2 s2 IHs2] [|x1 s1]; rewrite ?sub0seq //=. have [->|_] := eqVneq x1 x2; first by case: eqP => //= _ /IHs2; rewrite eqxx. move=> /IHs2/subseq_trans->//. by have [->|_] := eqVneq x x2; [apply: rem_subseq|apply: subseq_cons]. Qed. End FilterSubseq. Arguments subseq_uniqP [T s1 s2]. Section EqMap. Variables (n0 : nat) (T1 : eqType) (x1 : T1). Variables (T2 : eqType) (x2 : T2) (f : T1 -> T2). Implicit Type s : seq T1. Lemma map_f s x : x \in s -> f x \in map f s. Proof. by elim: s => //= y s IHs /predU1P[->|/IHs]; [apply: predU1l | apply: predU1r]. Qed. Lemma mapP s y : reflect (exists2 x, x \in s & y = f x) (y \in map f s). Proof. elim: s => [|x s IHs]; [by right; case|rewrite /= inE]. exact: equivP (orPP eqP IHs) (iff_sym exists_cons). Qed. Lemma subset_mapP (s : seq T1) (s' : seq T2) : {subset s' <= map f s} <-> exists2 t, all (mem s) t & s' = map f t. Proof. split => [|[r /allP/= rE ->] _ /mapP[x xr ->]]; last by rewrite map_f ?rE. elim: s' => [|x s' IHs'] subss'; first by exists [::]. have /mapP[y ys ->] := subss' _ (mem_head _ _). have [x' x's'|t st ->] := IHs'; first by rewrite subss'// inE x's' orbT. by exists (y :: t); rewrite //= ys st. Qed. Lemma map_uniq s : uniq (map f s) -> uniq s. Proof. elim: s => //= x s IHs /andP[not_sfx /IHs->]; rewrite andbT. by apply: contra not_sfx => sx; apply/mapP; exists x. Qed. Lemma map_inj_in_uniq s : {in s &, injective f} -> uniq (map f s) = uniq s. Proof. elim: s => //= x s IHs //= injf; congr (~~ _ && _). apply/mapP/idP=> [[y sy /injf] | ]; last by exists x. by rewrite mem_head mem_behead // => ->. by apply: IHs => y z sy sz; apply: injf => //; apply: predU1r. Qed. Lemma map_subseq s1 s2 : subseq s1 s2 -> subseq (map f s1) (map f s2). Proof. case/subseqP=> m sz_m ->; apply/subseqP. by exists m; rewrite ?size_map ?map_mask. Qed. Lemma nth_index_map s x0 x : {in s &, injective f} -> x \in s -> nth x0 s (index (f x) (map f s)) = x. Proof. elim: s => //= y s IHs inj_f s_x; rewrite (inj_in_eq inj_f) ?mem_head //. move: s_x; rewrite inE; have [-> // | _] := eqVneq; apply: IHs. by apply: sub_in2 inj_f => z; apply: predU1r. Qed. Lemma perm_map s t : perm_eq s t -> perm_eq (map f s) (map f t). Proof. by move/permP=> Est; apply/permP=> a; rewrite !count_map Est. Qed. Lemma sub_map s1 s2 : {subset s1 <= s2} -> {subset map f s1 <= map f s2}. Proof. by move=> sub_s ? /mapP[x x_s ->]; rewrite map_f ?sub_s. Qed. Lemma eq_mem_map s1 s2 : s1 =i s2 -> map f s1 =i map f s2. Proof. by move=> Es x; apply/idP/idP; apply: sub_map => ?; rewrite Es. Qed. Hypothesis Hf : injective f. Lemma mem_map s x : (f x \in map f s) = (x \in s). Proof. by apply/mapP/idP=> [[y Hy /Hf->] //|]; exists x. Qed. Lemma index_map s x : index (f x) (map f s) = index x s. Proof. by rewrite /index; elim: s => //= y s IHs; rewrite (inj_eq Hf) IHs. Qed. Lemma map_inj_uniq s : uniq (map f s) = uniq s. Proof. by apply: map_inj_in_uniq; apply: in2W. Qed. Lemma undup_map_inj s : undup (map f s) = map f (undup s). Proof. by elim: s => //= s0 s ->; rewrite mem_map //; case: (_ \in _). Qed. Lemma perm_map_inj s t : perm_eq (map f s) (map f t) -> perm_eq s t. Proof. move/permP=> Est; apply/allP=> x _ /=. have Dx: pred1 x =1 preim f (pred1 (f x)) by move=> y /=; rewrite inj_eq. by rewrite !(eq_count Dx) -!count_map Est. Qed. End EqMap. Arguments mapP {T1 T2 f s y}. Arguments subset_mapP {T1 T2}. Lemma map_of_seq (T1 : eqType) T2 (s : seq T1) (fs : seq T2) (y0 : T2) : {f | uniq s -> size fs = size s -> map f s = fs}. Proof. exists (fun x => nth y0 fs (index x s)) => uAs eq_sz. apply/esym/(@eq_from_nth _ y0); rewrite ?size_map eq_sz // => i ltis. by have x0 : T1 by [case: (s) ltis]; rewrite (nth_map x0) // index_uniq. Qed. Section MapComp. Variable S T U : Type. Lemma map_id (s : seq T) : map id s = s. Proof. by elim: s => //= x s ->. Qed. Lemma eq_map (f g : S -> T) : f =1 g -> map f =1 map g. Proof. by move=> Ef; elim=> //= x s ->; rewrite Ef. Qed. Lemma map_comp (f : T -> U) (g : S -> T) s : map (f \o g) s = map f (map g s). Proof. by elim: s => //= x s ->. Qed. Lemma mapK (f : S -> T) (g : T -> S) : cancel f g -> cancel (map f) (map g). Proof. by move=> fK; elim=> //= x s ->; rewrite fK. Qed. Lemma mapK_in (A : {pred S}) (f : S -> T) (g : T -> S) : {in A, cancel f g} -> {in [pred s | all [in A] s], cancel (map f) (map g)}. Proof. by move=> fK; elim=> //= x s IHs /andP[/fK-> /IHs->]. Qed. End MapComp. Lemma eq_in_map (S : eqType) T (f g : S -> T) (s : seq S) : {in s, f =1 g} <-> map f s = map g s. Proof. elim: s => //= x s IHs; split=> [/forall_cons[-> ?]|]; first by rewrite IHs.1. by move=> -[? ?]; apply/forall_cons; split=> [//|]; apply: IHs.2. Qed. Lemma map_id_in (T : eqType) f (s : seq T) : {in s, f =1 id} -> map f s = s. Proof. by move/eq_in_map->; apply: map_id. Qed. (* Map a partial function *) Section Pmap. Variables (aT rT : Type) (f : aT -> option rT) (g : rT -> aT). Fixpoint pmap s := if s is x :: s' then let r := pmap s' in oapp (cons^~ r) r (f x) else [::]. Lemma map_pK : pcancel g f -> cancel (map g) pmap. Proof. by move=> gK; elim=> //= x s ->; rewrite gK. Qed. Lemma size_pmap s : size (pmap s) = count [eta f] s. Proof. by elim: s => //= x s <-; case: (f _). Qed. Lemma pmapS_filter s : map some (pmap s) = map f (filter [eta f] s). Proof. by elim: s => //= x s; case fx: (f x) => //= [u] <-; congr (_ :: _). Qed. Hypothesis fK : ocancel f g. Lemma pmap_filter s : map g (pmap s) = filter [eta f] s. Proof. by elim: s => //= x s <-; rewrite -{3}(fK x); case: (f _). Qed. Lemma pmap_cat s t : pmap (s ++ t) = pmap s ++ pmap t. Proof. by elim: s => //= x s ->; case/f: x. Qed. Lemma all_pmap (p : pred rT) s : all p (pmap s) = all [pred i | oapp p true (f i)] s. Proof. by elim: s => //= x s <-; case: f. Qed. End Pmap. Lemma eq_in_pmap (aT : eqType) rT (f1 f2 : aT -> option rT) s : {in s, f1 =1 f2} -> pmap f1 s = pmap f2 s. Proof. by elim: s => //= a s IHs /forall_cons [-> /IHs ->]. Qed. Lemma eq_pmap aT rT (f1 f2 : aT -> option rT) : f1 =1 f2 -> pmap f1 =1 pmap f2. Proof. by move=> Ef; elim => //= a s ->; rewrite Ef. Qed. Section EqPmap. Variables (aT rT : eqType) (f : aT -> option rT) (g : rT -> aT). Lemma mem_pmap s u : (u \in pmap f s) = (Some u \in map f s). Proof. by elim: s => //= x s IHs; rewrite in_cons -IHs; case: (f x). Qed. Hypothesis fK : ocancel f g. Lemma can2_mem_pmap : pcancel g f -> forall s u, (u \in pmap f s) = (g u \in s). Proof. by move=> gK s u; rewrite -(mem_map (pcan_inj gK)) pmap_filter // mem_filter gK. Qed. Lemma pmap_uniq s : uniq s -> uniq (pmap f s). Proof. move/(filter_uniq f); rewrite -(pmap_filter fK); exact: map_uniq. Qed. Lemma perm_pmap s t : perm_eq s t -> perm_eq (pmap f s) (pmap f t). Proof. move=> eq_st; apply/(perm_map_inj Some_inj); rewrite !pmapS_filter. exact/perm_map/perm_filter. Qed. End EqPmap. Section PmapSub. Variables (T : Type) (p : pred T) (sT : subType p). Lemma size_pmap_sub s : size (pmap (insub : T -> option sT) s) = count p s. Proof. by rewrite size_pmap (eq_count (isSome_insub _)). Qed. End PmapSub. Section EqPmapSub. Variables (T : eqType) (p : pred T) (sT : subEqType p). Let insT : T -> option sT := insub. Lemma mem_pmap_sub s u : (u \in pmap insT s) = (val u \in s). Proof. exact/(can2_mem_pmap (insubK _))/valK. Qed. Lemma pmap_sub_uniq s : uniq s -> uniq (pmap insT s). Proof. exact: (pmap_uniq (insubK _)). Qed. End EqPmapSub. (* Index sequence *) Fixpoint iota m n := if n is n'.+1 then m :: iota m.+1 n' else [::]. Lemma size_iota m n : size (iota m n) = n. Proof. by elim: n m => //= n IHn m; rewrite IHn. Qed. Lemma iotaD m n1 n2 : iota m (n1 + n2) = iota m n1 ++ iota (m + n1) n2. Proof. by elim: n1 m => [|n1 IHn1] m; rewrite ?addn0 // -addSnnS /= -IHn1. Qed. Lemma iotaDl m1 m2 n : iota (m1 + m2) n = map (addn m1) (iota m2 n). Proof. by elim: n m2 => //= n IHn m2; rewrite -addnS IHn. Qed. Lemma nth_iota p m n i : i < n -> nth p (iota m n) i = m + i. Proof. by move/subnKC <-; rewrite addSnnS iotaD nth_cat size_iota ltnn subnn. Qed. Lemma mem_iota m n i : (i \in iota m n) = (m <= i < m + n). Proof. elim: n m => [|n IHn] /= m; first by rewrite addn0 ltnNge andbN. by rewrite in_cons IHn addnS ltnS; case: ltngtP => // ->; rewrite leq_addr. Qed. Lemma iota_uniq m n : uniq (iota m n). Proof. by elim: n m => //= n IHn m; rewrite mem_iota ltnn /=. Qed. Lemma take_iota k m n : take k (iota m n) = iota m (minn k n). Proof. have [lt_k_n|le_n_k] := ltnP. by elim: k n lt_k_n m => [|k IHk] [|n] //= H m; rewrite IHk. by apply: take_oversize; rewrite size_iota. Qed. Lemma drop_iota k m n : drop k (iota m n) = iota (m + k) (n - k). Proof. by elim: k m n => [|k IHk] m [|n] //=; rewrite ?addn0 // IHk addnS subSS. Qed. Lemma filter_iota_ltn m n j : j <= n -> [seq i <- iota m n | i < m + j] = iota m j. Proof. elim: n m j => [m j|n IHn m [|j] jlen]; first by rewrite leqn0 => /eqP ->. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 ltnNge mem_iota => /andP[->]. by rewrite /= addnS leq_addr -addSn IHn. Qed. Lemma filter_iota_leq n m j : j < n -> [seq i <- iota m n | i <= m + j] = iota m j.+1. Proof. elim: n m j => [//|n IHn] m [|j] jlen /=; rewrite leq_addr. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => i. by rewrite addn0 leqNgt mem_iota => /andP[->]. by rewrite addnS -addSn IHn -1?ltnS. Qed. (* Making a sequence of a specific length, using indexes to compute items. *) Section MakeSeq. Variables (T : Type) (x0 : T). Definition mkseq f n : seq T := map f (iota 0 n). Lemma size_mkseq f n : size (mkseq f n) = n. Proof. by rewrite size_map size_iota. Qed. Lemma mkseqS f n : mkseq f n.+1 = rcons (mkseq f n) (f n). Proof. by rewrite /mkseq -addn1 iotaD add0n map_cat cats1. Qed. Lemma eq_mkseq f g : f =1 g -> mkseq f =1 mkseq g. Proof. by move=> Efg n; apply: eq_map Efg _. Qed. Lemma nth_mkseq f n i : i < n -> nth x0 (mkseq f n) i = f i. Proof. by move=> Hi; rewrite (nth_map 0) ?nth_iota ?size_iota. Qed. Lemma mkseq_nth s : mkseq (nth x0 s) (size s) = s. Proof. by apply: (@eq_from_nth _ x0); rewrite size_mkseq // => i Hi; rewrite nth_mkseq. Qed. Variant mkseq_spec s : seq T -> Type := | MapIota n f : s = mkseq f n -> mkseq_spec s (mkseq f n). Lemma mkseqP s : mkseq_spec s s. Proof. by rewrite -[s]mkseq_nth; constructor. Qed. Lemma map_nth_iota0 s i : i <= size s -> [seq nth x0 s j | j <- iota 0 i] = take i s. Proof. by move=> ile; rewrite -[s in RHS]mkseq_nth -map_take take_iota (minn_idPl _). Qed. Lemma map_nth_iota s i j : j <= size s - i -> [seq nth x0 s k | k <- iota i j] = take j (drop i s). Proof. elim: i => [|i IH] in s j *; first by rewrite subn0 drop0 => /map_nth_iota0->. case: s => [|x s /IH<-]; first by rewrite leqn0 => /eqP->. by rewrite -add1n iotaDl -map_comp. Qed. End MakeSeq. Section MakeEqSeq. Variable T : eqType. Lemma mkseq_uniqP (f : nat -> T) n : reflect {in gtn n &, injective f} (uniq (mkseq f n)). Proof. apply: (equivP (uniqP (f 0))); rewrite size_mkseq. by split=> injf i j lti ltj; have:= injf i j lti ltj; rewrite !nth_mkseq. Qed. Lemma mkseq_uniq (f : nat -> T) n : injective f -> uniq (mkseq f n). Proof. by move/map_inj_uniq->; apply: iota_uniq. Qed. Lemma perm_iotaP {s t : seq T} x0 (It := iota 0 (size t)) : reflect (exists2 Is, perm_eq Is It & s = map (nth x0 t) Is) (perm_eq s t). Proof. apply: (iffP idP) => [Est | [Is eqIst ->]]; last first. by rewrite -{2}[t](mkseq_nth x0) perm_map. elim: t => [|x t IHt] in s It Est *. by rewrite (perm_small_eq _ Est) //; exists [::]. have /rot_to[k s1 Ds]: x \in s by rewrite (perm_mem Est) mem_head. have [|Is1 eqIst1 Ds1] := IHt s1; first by rewrite -(perm_cons x) -Ds perm_rot. exists (rotr k (0 :: map succn Is1)). by rewrite perm_rot /It /= perm_cons (iotaDl 1) perm_map. by rewrite map_rotr /= -map_comp -(@eq_map _ _ (nth x0 t)) // -Ds1 -Ds rotK. Qed. End MakeEqSeq. Arguments perm_iotaP {T s t}. Section FoldRight. Variables (T : Type) (R : Type) (f : T -> R -> R) (z0 : R). Fixpoint foldr s := if s is x :: s' then f x (foldr s') else z0. End FoldRight. Section FoldRightComp. Variables (T1 T2 : Type) (h : T1 -> T2). Variables (R : Type) (f : T2 -> R -> R) (z0 : R). Lemma foldr_cat s1 s2 : foldr f z0 (s1 ++ s2) = foldr f (foldr f z0 s2) s1. Proof. by elim: s1 => //= x s1 ->. Qed. Lemma foldr_rcons s x : foldr f z0 (rcons s x) = foldr f (f x z0) s. Proof. by rewrite -cats1 foldr_cat. Qed. Lemma foldr_map s : foldr f z0 (map h s) = foldr (fun x z => f (h x) z) z0 s. Proof. by elim: s => //= x s ->. Qed. End FoldRightComp. (* Quick characterization of the null sequence. *) Definition sumn := foldr addn 0. Lemma sumn_ncons x n s : sumn (ncons n x s) = x * n + sumn s. Proof. by rewrite mulnC; elim: n => //= n ->; rewrite addnA. Qed. Lemma sumn_nseq x n : sumn (nseq n x) = x * n. Proof. by rewrite sumn_ncons addn0. Qed. Lemma sumn_cat s1 s2 : sumn (s1 ++ s2) = sumn s1 + sumn s2. Proof. by elim: s1 => //= x s1 ->; rewrite addnA. Qed. Lemma sumn_count T (a : pred T) s : sumn [seq a i : nat | i <- s] = count a s. Proof. by elim: s => //= s0 s /= ->. Qed. Lemma sumn_rcons s n : sumn (rcons s n) = sumn s + n. Proof. by rewrite -cats1 sumn_cat /= addn0. Qed. Lemma perm_sumn s1 s2 : perm_eq s1 s2 -> sumn s1 = sumn s2. Proof. by apply/catCA_perm_subst: s1 s2 => s1 s2 s3; rewrite !sumn_cat addnCA. Qed. Lemma sumn_rot s n : sumn (rot n s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rot. Qed. Lemma sumn_rev s : sumn (rev s) = sumn s. Proof. by apply/perm_sumn; rewrite perm_rev. Qed. Lemma natnseq0P s : reflect (s = nseq (size s) 0) (sumn s == 0). Proof. apply: (iffP idP) => [|->]; last by rewrite sumn_nseq. by elim: s => //= x s IHs; rewrite addn_eq0 => /andP[/eqP-> /IHs <-]. Qed. Lemma sumn_set_nth s x0 n x : sumn (set_nth x0 s n x) = sumn s + x - (nth x0 s n) * (n < size s) + x0 * (n - size s). Proof. rewrite set_nthE; case: ltnP => [nlts|nges]; last first. by rewrite sumn_cat sumn_ncons /= addn0 muln0 subn0 addnAC addnA. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. rewrite -[in sumn s](cat_take_drop n s) [drop n s](drop_nth x0)//. by rewrite !sumn_cat /= muln1 muln0 addn0 addnAC !addnA [in RHS]addnAC addnK. Qed. Lemma sumn_set_nth_ltn s x0 n x : n < size s -> sumn (set_nth x0 s n x) = sumn s + x - nth x0 s n. Proof. move=> nlts; rewrite sumn_set_nth nlts muln1. have -> : n - size s = 0 by apply/eqP; rewrite subn_eq0 ltnW. by rewrite muln0 addn0. Qed. Lemma sumn_set_nth0 s n x : sumn (set_nth 0 s n x) = sumn s + x - nth 0 s n. Proof. rewrite sumn_set_nth mul0n addn0. by case: ltnP => [_|nges]; rewrite ?muln1// nth_default. Qed. Section FoldLeft. Variables (T R : Type) (f : R -> T -> R). Fixpoint foldl z s := if s is x :: s' then foldl (f z x) s' else z. Lemma foldl_rev z s : foldl z (rev s) = foldr (fun x z => f z x) z s. Proof. by elim/last_ind: s z => // s x IHs z; rewrite rev_rcons -cats1 foldr_cat -IHs. Qed. Lemma foldl_cat z s1 s2 : foldl z (s1 ++ s2) = foldl (foldl z s1) s2. Proof. by rewrite -(revK (s1 ++ s2)) foldl_rev rev_cat foldr_cat -!foldl_rev !revK. Qed. Lemma foldl_rcons z s x : foldl z (rcons s x) = f (foldl z s) x. Proof. by rewrite -cats1 foldl_cat. Qed. End FoldLeft. Section Folds. Variables (T : Type) (f : T -> T -> T). Hypotheses (fA : associative f) (fC : commutative f). Lemma foldl_foldr x0 l : foldl f x0 l = foldr f x0 l. Proof. elim: l x0 => [//|x1 l IHl] x0 /=; rewrite {}IHl. by elim: l x0 x1 => [//|x2 l IHl] x0 x1 /=; rewrite IHl !fA [f x2 x1]fC. Qed. End Folds. Section Scan. Variables (T1 : Type) (x1 : T1) (T2 : Type) (x2 : T2). Variables (f : T1 -> T1 -> T2) (g : T1 -> T2 -> T1). Fixpoint pairmap x s := if s is y :: s' then f x y :: pairmap y s' else [::]. Lemma size_pairmap x s : size (pairmap x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma pairmap_cat x s1 s2 : pairmap x (s1 ++ s2) = pairmap x s1 ++ pairmap (last x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma nth_pairmap s n : n < size s -> forall x, nth x2 (pairmap x s) n = f (nth x1 (x :: s) n) (nth x1 s n). Proof. by elim: s n => [|y s IHs] [|n] //= Hn x; apply: IHs. Qed. Fixpoint scanl x s := if s is y :: s' then let x' := g x y in x' :: scanl x' s' else [::]. Lemma size_scanl x s : size (scanl x s) = size s. Proof. by elim: s x => //= y s IHs x; rewrite IHs. Qed. Lemma scanl_cat x s1 s2 : scanl x (s1 ++ s2) = scanl x s1 ++ scanl (foldl g x s1) s2. Proof. by elim: s1 x => //= y s1 IHs1 x; rewrite IHs1. Qed. Lemma scanl_rcons x s1 y : scanl x (rcons s1 y) = rcons (scanl x s1) (foldl g x (rcons s1 y)). Proof. by rewrite -!cats1 scanl_cat foldl_cat. Qed. Lemma nth_cons_scanl s n : n <= size s -> forall x, nth x1 (x :: scanl x s) n = foldl g x (take n s). Proof. by elim: s n => [|y s IHs] [|n] Hn x //=; rewrite IHs. Qed. Lemma nth_scanl s n : n < size s -> forall x, nth x1 (scanl x s) n = foldl g x (take n.+1 s). Proof. by move=> n_lt x; rewrite -nth_cons_scanl. Qed. Lemma scanlK : (forall x, cancel (g x) (f x)) -> forall x, cancel (scanl x) (pairmap x). Proof. by move=> Hfg x s; elim: s x => //= y s IHs x; rewrite Hfg IHs. Qed. Lemma pairmapK : (forall x, cancel (f x) (g x)) -> forall x, cancel (pairmap x) (scanl x). Proof. by move=> Hgf x s; elim: s x => //= y s IHs x; rewrite Hgf IHs. Qed. End Scan. Prenex Implicits mask map pmap foldr foldl scanl pairmap. Section Zip. Variables (S T : Type) (r : S -> T -> bool). Fixpoint zip (s : seq S) (t : seq T) {struct t} := match s, t with | x :: s', y :: t' => (x, y) :: zip s' t' | _, _ => [::] end. Definition unzip1 := map (@fst S T). Definition unzip2 := map (@snd S T). Fixpoint all2 s t := match s, t with | [::], [::] => true | x :: s, y :: t => r x y && all2 s t | _, _ => false end. Lemma zip_unzip s : zip (unzip1 s) (unzip2 s) = s. Proof. by elim: s => [|[x y] s /= ->]. Qed. Lemma unzip1_zip s t : size s <= size t -> unzip1 (zip s t) = s. Proof. by elim: s t => [|x s IHs] [|y t] //= le_s_t; rewrite IHs. Qed. Lemma unzip2_zip s t : size t <= size s -> unzip2 (zip s t) = t. Proof. by elim: s t => [|x s IHs] [|y t] //= le_t_s; rewrite IHs. Qed. Lemma size1_zip s t : size s <= size t -> size (zip s t) = size s. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size2_zip s t : size t <= size s -> size (zip s t) = size t. Proof. by elim: s t => [|x s IHs] [|y t] //= Hs; rewrite IHs. Qed. Lemma size_zip s t : size (zip s t) = minn (size s) (size t). Proof. by elim: s t => [|x s IHs] [|t2 t] //=; rewrite IHs minnSS. Qed. Lemma zip_cat s1 s2 t1 t2 : size s1 = size t1 -> zip (s1 ++ s2) (t1 ++ t2) = zip s1 t1 ++ zip s2 t2. Proof. by move: s1 t1; apply: seq_ind2 => //= x y s1 t1 _ ->. Qed. Lemma nth_zip x y s t i : size s = size t -> nth (x, y) (zip s t) i = (nth x s i, nth y t i). Proof. by elim: i s t => [|i IHi] [|y1 s1] [|y2 t] //= [/IHi->]. Qed. Lemma nth_zip_cond p s t i : nth p (zip s t) i = (if i < size (zip s t) then (nth p.1 s i, nth p.2 t i) else p). Proof. rewrite size_zip ltnNge geq_min. by elim: s t i => [|x s IHs] [|y t] [|i] //=; rewrite ?orbT -?IHs. Qed. Lemma zip_rcons s t x y : size s = size t -> zip (rcons s x) (rcons t y) = rcons (zip s t) (x, y). Proof. by move=> eq_sz; rewrite -!cats1 zip_cat //= eq_sz. Qed. Lemma rev_zip s t : size s = size t -> rev (zip s t) = zip (rev s) (rev t). Proof. move: s t; apply: seq_ind2 => //= x y s t eq_sz IHs. by rewrite !rev_cons IHs zip_rcons ?size_rev. Qed. Lemma all2E s t : all2 s t = (size s == size t) && all [pred xy | r xy.1 xy.2] (zip s t). Proof. by elim: s t => [|x s IHs] [|y t] //=; rewrite IHs andbCA. Qed. Lemma zip_map I f g (s : seq I) : zip (map f s) (map g s) = [seq (f i, g i) | i <- s]. Proof. by elim: s => //= i s ->. Qed. Lemma unzip1_map_nth_zip x y s t l : size s = size t -> unzip1 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth x s i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. Lemma unzip2_map_nth_zip x y s t l : size s = size t -> unzip2 [seq nth (x, y) (zip s t) i | i <- l] = [seq nth y t i | i <- l]. Proof. by move=> st; elim: l => [//=|n l IH /=]; rewrite nth_zip ?IH ?st. Qed. End Zip. Lemma zip_uniql (S T : eqType) (s : seq S) (t : seq T) : uniq s -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[n _]. by apply/(uniqPn s0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minl. Qed. Lemma zip_uniqr (S T : eqType) (s : seq S) (t : seq T) : uniq t -> uniq (zip s t). Proof. case: s t => [|s0 s] [|t0 t] //; apply: contraTT => /(uniqPn (s0, t0)) [i [j]]. case=> o z; rewrite !nth_zip_cond !ifT ?js ?(ltn_trans o)// => -[_ n]. by apply/(uniqPn t0); exists i, j; rewrite o n (leq_trans z) ?size_zip?geq_minr. Qed. Lemma perm_zip_sym (S T : eqType) (s1 s2 : seq S) (t1 t2 : seq T) : perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq (zip t1 s1) (zip t2 s2). Proof. have swap t s : zip t s = map (fun u => (u.2, u.1)) (zip s t). by elim: s t => [|x s +] [|y t]//= => ->. by rewrite [zip t1 s1]swap [zip t2 s2]swap; apply: perm_map. Qed. Lemma perm_zip1 {S T : eqType} (t1 t2 : seq T) (s1 s2 : seq S): size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq s1 s2. Proof. wlog [x y] : s1 s2 t1 t2 / (S * T)%type => [hwlog|]. case: s2 t2 => [|x s2] [|y t2] //; last exact: hwlog. by case: s1 t1 => [|u s1] [|v t1]//= _ _ /perm_nilP. move=> eq1 eq2 /(perm_iotaP (x, y))[ns nsP /(congr1 (@unzip1 _ _))]. rewrite unzip1_zip ?unzip1_map_nth_zip -?eq1// => ->. by apply/(perm_iotaP x); exists ns; rewrite // size_zip -eq2 minnn in nsP. Qed. Lemma perm_zip2 {S T : eqType} (s1 s2 : seq S) (t1 t2 : seq T) : size s1 = size t1 -> size s2 = size t2 -> perm_eq (zip s1 t1) (zip s2 t2) -> perm_eq t1 t2. Proof. by move=> ? ? ?; rewrite (@perm_zip1 _ _ s1 s2) 1?perm_zip_sym. Qed. Prenex Implicits zip unzip1 unzip2 all2. Lemma eqseq_all (T : eqType) (s t : seq T) : (s == t) = all2 eq_op s t. Proof. by elim: s t => [|x s +] [|y t]//= => <-. Qed. Lemma eq_map_all I (T : eqType) (f g : I -> T) (s : seq I) : (map f s == map g s) = all [pred xy | xy.1 == xy.2] [seq (f i, g i) | i <- s]. Proof. by rewrite eqseq_all all2E !size_map eqxx zip_map. Qed. Section Flatten. Variable T : Type. Implicit Types (s : seq T) (ss : seq (seq T)). Definition flatten := foldr cat (Nil T). Definition shape := map (@size T). Fixpoint reshape sh s := if sh is n :: sh' then take n s :: reshape sh' (drop n s) else [::]. Definition flatten_index sh r c := sumn (take r sh) + c. Definition reshape_index sh i := find (pred1 0) (scanl subn i.+1 sh). Definition reshape_offset sh i := i - sumn (take (reshape_index sh i) sh). Lemma size_flatten ss : size (flatten ss) = sumn (shape ss). Proof. by elim: ss => //= s ss <-; rewrite size_cat. Qed. Lemma flatten_cat ss1 ss2 : flatten (ss1 ++ ss2) = flatten ss1 ++ flatten ss2. Proof. by elim: ss1 => //= s ss1 ->; rewrite catA. Qed. Lemma size_reshape sh s : size (reshape sh s) = size sh. Proof. by elim: sh s => //= s0 sh IHsh s; rewrite IHsh. Qed. Lemma nth_reshape (sh : seq nat) l n : nth [::] (reshape sh l) n = take (nth 0 sh n) (drop (sumn (take n sh)) l). Proof. elim: n sh l => [| n IHn] [| sh0 sh] l; rewrite ?take0 ?drop0 //=. by rewrite addnC -drop_drop; apply: IHn. Qed. Lemma flattenK ss : reshape (shape ss) (flatten ss) = ss. Proof. by elim: ss => //= s ss IHss; rewrite take_size_cat ?drop_size_cat ?IHss. Qed. Lemma reshapeKr sh s : size s <= sumn sh -> flatten (reshape sh s) = s. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s; rewrite IHsh ?cat_take_drop //. by rewrite size_drop leq_subLR. Qed. Lemma reshapeKl sh s : size s >= sumn sh -> shape (reshape sh s) = sh. Proof. elim: sh s => [[]|n sh IHsh] //= s sz_s. rewrite size_takel; last exact: leq_trans (leq_addr _ _) sz_s. by rewrite IHsh // -(leq_add2l n) size_drop -maxnE leq_max sz_s orbT. Qed. Lemma flatten_rcons ss s : flatten (rcons ss s) = flatten ss ++ s. Proof. by rewrite -cats1 flatten_cat /= cats0. Qed. Lemma flatten_seq1 s : flatten [seq [:: x] | x <- s] = s. Proof. by elim: s => //= s0 s ->. Qed. Lemma count_flatten ss P : count P (flatten ss) = sumn [seq count P x | x <- ss]. Proof. by elim: ss => //= s ss IHss; rewrite count_cat IHss. Qed. Lemma filter_flatten ss (P : pred T) : filter P (flatten ss) = flatten [seq filter P i | i <- ss]. Proof. by elim: ss => // s ss /= <-; apply: filter_cat. Qed. Lemma rev_flatten ss : rev (flatten ss) = flatten (rev (map rev ss)). Proof. by elim: ss => //= s ss IHss; rewrite rev_cons flatten_rcons -IHss rev_cat. Qed. Lemma nth_shape ss i : nth 0 (shape ss) i = size (nth [::] ss i). Proof. rewrite /shape; case: (ltnP i (size ss)) => Hi; first exact: nth_map. by rewrite !nth_default // size_map. Qed. Lemma shape_rev ss : shape (rev ss) = rev (shape ss). Proof. exact: map_rev. Qed. Lemma eq_from_flatten_shape ss1 ss2 : flatten ss1 = flatten ss2 -> shape ss1 = shape ss2 -> ss1 = ss2. Proof. by move=> Eflat Esh; rewrite -[LHS]flattenK Eflat Esh flattenK. Qed. Lemma rev_reshape sh s : size s = sumn sh -> rev (reshape sh s) = map rev (reshape (rev sh) (rev s)). Proof. move=> sz_s; apply/(canLR revK)/eq_from_flatten_shape. rewrite reshapeKr ?sz_s // -rev_flatten reshapeKr ?revK //. by rewrite size_rev sumn_rev sz_s. transitivity (rev (shape (reshape (rev sh) (rev s)))). by rewrite !reshapeKl ?revK ?size_rev ?sz_s ?sumn_rev. rewrite shape_rev; congr (rev _); rewrite -[RHS]map_comp. by under eq_map do rewrite /= size_rev. Qed. Lemma reshape_rcons s sh n (m := sumn sh) : m + n = size s -> reshape (rcons sh n) s = rcons (reshape sh (take m s)) (drop m s). Proof. move=> Dmn; apply/(can_inj revK); rewrite rev_reshape ?rev_rcons ?sumn_rcons //. rewrite /= take_rev drop_rev -Dmn addnK revK -rev_reshape //. by rewrite size_takel // -Dmn leq_addr. Qed. Lemma flatten_indexP sh r c : c < nth 0 sh r -> flatten_index sh r c < sumn sh. Proof. move=> lt_c_sh; rewrite -[sh in sumn sh](cat_take_drop r) sumn_cat ltn_add2l. suffices lt_r_sh: r < size sh by rewrite (drop_nth 0 lt_r_sh) ltn_addr. by case: ltnP => // le_sh_r; rewrite nth_default in lt_c_sh. Qed. Lemma reshape_indexP sh i : i < sumn sh -> reshape_index sh i < size sh. Proof. rewrite /reshape_index; elim: sh => //= n sh IHsh in i *; rewrite subn_eq0. by have [// | le_n_i] := ltnP i n; rewrite -leq_subLR subSn // => /IHsh. Qed. Lemma reshape_offsetP sh i : i < sumn sh -> reshape_offset sh i < nth 0 sh (reshape_index sh i). Proof. rewrite /reshape_offset /reshape_index; elim: sh => //= n sh IHsh in i *. rewrite subn_eq0; have [| le_n_i] := ltnP i n; first by rewrite subn0. by rewrite -leq_subLR /= subnDA subSn // => /IHsh. Qed. Lemma reshape_indexK sh i : flatten_index sh (reshape_index sh i) (reshape_offset sh i) = i. Proof. rewrite /reshape_offset /reshape_index /flatten_index -subSKn. elim: sh => //= n sh IHsh in i *; rewrite subn_eq0; have [//|le_n_i] := ltnP. by rewrite /= subnDA subSn // -addnA IHsh subnKC. Qed. Lemma flatten_indexKl sh r c : c < nth 0 sh r -> reshape_index sh (flatten_index sh r c) = r. Proof. rewrite /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT. by rewrite -addnA -addnS addKn IHsh. Qed. Lemma flatten_indexKr sh r c : c < nth 0 sh r -> reshape_offset sh (flatten_index sh r c) = c. Proof. rewrite /reshape_offset /reshape_index /flatten_index. elim: sh r => [|n sh IHsh] [|r] //= lt_c_sh; first by rewrite ifT ?subn0. by rewrite -addnA -addnS addKn /= subnDl IHsh. Qed. Lemma nth_flatten x0 ss i (r := reshape_index (shape ss) i) : nth x0 (flatten ss) i = nth x0 (nth [::] ss r) (reshape_offset (shape ss) i). Proof. rewrite /reshape_offset -subSKn {}/r /reshape_index. elim: ss => //= s ss IHss in i *; rewrite subn_eq0 nth_cat. by have [//|le_s_i] := ltnP; rewrite subnDA subSn /=. Qed. Lemma reshape_leq sh i1 i2 (r1 := reshape_index sh i1) (c1 := reshape_offset sh i1) (r2 := reshape_index sh i2) (c2 := reshape_offset sh i2) : (i1 <= i2) = ((r1 < r2) || ((r1 == r2) && (c1 <= c2))). Proof. rewrite {}/r1 {}/c1 {}/r2 {}/c2 /reshape_offset /reshape_index. elim: sh => [|s0 s IHs] /= in i1 i2 *; rewrite ?subn0 ?subn_eq0 //. have [[] i1s0 [] i2s0] := (ltnP i1 s0, ltnP i2 s0); first by rewrite !subn0. - by apply: leq_trans i2s0; apply/ltnW. - by apply/negP => /(leq_trans i1s0); rewrite leqNgt i2s0. by rewrite !subSn // !eqSS !ltnS !subnDA -IHs leq_subLR subnKC. Qed. End Flatten. Prenex Implicits flatten shape reshape. Lemma map_flatten S T (f : T -> S) ss : map f (flatten ss) = flatten (map (map f) ss). Proof. by elim: ss => // s ss /= <-; apply: map_cat. Qed. Lemma flatten_map1 (S T : Type) (f : S -> T) s : flatten [seq [:: f x] | x <- s] = map f s. Proof. by elim: s => //= s0 s ->. Qed. Lemma undup_flatten_nseq n (T : eqType) (s : seq T) : 0 < n -> undup (flatten (nseq n s)) = undup s. Proof. elim: n => [|[|n]/= IHn]//= _; rewrite ?cats0// undup_cat {}IHn//. rewrite (@eq_in_filter _ _ pred0) ?filter_pred0// => x. by rewrite mem_undup mem_cat => ->. Qed. Lemma sumn_flatten (ss : seq (seq nat)) : sumn (flatten ss) = sumn (map sumn ss). Proof. by elim: ss => // s ss /= <-; apply: sumn_cat. Qed. Lemma map_reshape T S (f : T -> S) sh s : map (map f) (reshape sh s) = reshape sh (map f s). Proof. by elim: sh s => //= sh0 sh IHsh s; rewrite map_take IHsh map_drop. Qed. Section EqFlatten. Variables S T : eqType. Lemma flattenP (A : seq (seq T)) x : reflect (exists2 s, s \in A & x \in s) (x \in flatten A). Proof. elim: A => /= [|s A IH_A]; [by right; case | rewrite mem_cat]. by apply: equivP (iff_sym exists_cons); apply: (orPP idP IH_A). Qed. Arguments flattenP {A x}. Lemma flatten_mapP (A : S -> seq T) s y : reflect (exists2 x, x \in s & y \in A x) (y \in flatten (map A s)). Proof. apply: (iffP flattenP) => [[_ /mapP[x sx ->]] | [x sx]] Axy; first by exists x. by exists (A x); rewrite ?map_f. Qed. Lemma perm_flatten (ss1 ss2 : seq (seq T)) : perm_eq ss1 ss2 -> perm_eq (flatten ss1) (flatten ss2). Proof. move=> eq_ss; apply/permP=> a; apply/catCA_perm_subst: ss1 ss2 eq_ss. by move=> ss1 ss2 ss3; rewrite !flatten_cat !count_cat addnCA. Qed. End EqFlatten. Arguments flattenP {T A x}. Arguments flatten_mapP {S T A s y}. Notation "[ 'seq' E | x <- s , y <- t ]" := (flatten [seq [seq E | y <- t] | x <- s]) (x binder, y binder, format "[ '[hv' 'seq' E '/ ' | x <- s , '/ ' y <- t ] ']'") : seq_scope. Notation "[ 'seq' E : R | x <- s , y <- t ]" := (flatten [seq [seq E : R | y <- t] | x <- s]) (x binder, y binder, only parsing) : seq_scope. Section PrefixSuffixInfix. Variables T : eqType. Implicit Type s : seq T. Fixpoint prefix s1 s2 {struct s2} := if s1 isn't x :: s1' then true else if s2 isn't y :: s2' then false else (x == y) && prefix s1' s2'. Lemma prefixE s1 s2 : prefix s1 s2 = (take (size s1) s2 == s1). Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => ->; rewrite eq_sym. Qed. Lemma prefix_refl s : prefix s s. Proof. by rewrite prefixE take_size. Qed. Lemma prefixs0 s : prefix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma prefix0s s : prefix [::] s. Proof. by case: s. Qed. Lemma prefix_cons s1 s2 x y : prefix (x :: s1) (y :: s2) = (x == y) && prefix s1 s2. Proof. by []. Qed. Lemma prefix_catr s1 s2 s1' s3 : size s1 = size s1' -> prefix (s1 ++ s2) (s1' ++ s3) = (s1 == s1') && prefix s2 s3. Proof. elim: s1 s1' => [|x s1 IHs1] [|y s1']//= [eqs1]. by rewrite IHs1// eqseq_cons andbA. Qed. Lemma prefix_prefix s1 s2 : prefix s1 (s1 ++ s2). Proof. by rewrite prefixE take_cat ltnn subnn take0 cats0. Qed. Hint Resolve prefix_prefix : core. Lemma prefixP {s1 s2} : reflect (exists s2' : seq T, s2 = s1 ++ s2') (prefix s1 s2). Proof. apply: (iffP idP) => [|[{}s2 ->]]; last exact: prefix_prefix. by rewrite prefixE => /eqP<-; exists (drop (size s1) s2); rewrite cat_take_drop. Qed. Lemma prefix_trans : transitive prefix. Proof. by move=> _ s2 _ /prefixP[s1 ->] /prefixP[s3 ->]; rewrite -catA. Qed. Lemma prefixs1 s x : prefix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by case: s => //= y s; rewrite prefixs0 eqseq_cons. Qed. Lemma catl_prefix s1 s2 s3 : prefix (s1 ++ s3) s2 -> prefix s1 s2. Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_catl s1 s2 s3 : prefix s1 s2 -> prefix s1 (s2 ++ s3). Proof. by move=> /prefixP [s2'] ->; rewrite -catA. Qed. Lemma prefix_rcons s x : prefix s (rcons s x). Proof. by rewrite -cats1 prefix_prefix. Qed. Definition suffix s1 s2 := prefix (rev s1) (rev s2). Lemma suffixE s1 s2 : suffix s1 s2 = (drop (size s2 - size s1) s2 == s1). Proof. by rewrite /suffix prefixE take_rev (can_eq revK) size_rev. Qed. Lemma suffix_refl s : suffix s s. Proof. exact: prefix_refl. Qed. Lemma suffixs0 s : suffix s [::] = (s == [::]). Proof. by rewrite /suffix prefixs0 -!nilpE rev_nilp. Qed. Lemma suffix0s s : suffix [::] s. Proof. exact: prefix0s. Qed. Lemma prefix_rev s1 s2 : prefix (rev s1) (rev s2) = suffix s1 s2. Proof. by []. Qed. Lemma prefix_revLR s1 s2 : prefix (rev s1) s2 = suffix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_rev s1 s2 : suffix (rev s1) (rev s2) = prefix s1 s2. Proof. by rewrite -prefix_rev !revK. Qed. Lemma suffix_revLR s1 s2 : suffix (rev s1) s2 = prefix s1 (rev s2). Proof. by rewrite -prefix_rev revK. Qed. Lemma suffix_suffix s1 s2 : suffix s2 (s1 ++ s2). Proof. by rewrite /suffix rev_cat prefix_prefix. Qed. Hint Resolve suffix_suffix : core. Lemma suffixP {s1 s2} : reflect (exists s2' : seq T, s2 = s2' ++ s1) (suffix s1 s2). Proof. apply: (iffP prefixP) => [[s2' rev_s2]|[s2' ->]]; exists (rev s2'); last first. by rewrite rev_cat. by rewrite -[s2]revK rev_s2 rev_cat revK. Qed. Lemma suffix_trans : transitive suffix. Proof. by move=> _ s2 _ /suffixP[s1 ->] /suffixP[s3 ->]; rewrite catA. Qed. Lemma suffix_rcons s1 s2 x y : suffix (rcons s1 x) (rcons s2 y) = (x == y) && suffix s1 s2. Proof. by rewrite /suffix 2!rev_rcons prefix_cons. Qed. Lemma suffix_catl s1 s2 s3 s3' : size s3 = size s3' -> suffix (s1 ++ s3) (s2 ++ s3') = (s3 == s3') && suffix s1 s2. Proof. by move=> eqs3; rewrite /suffix !rev_cat prefix_catr ?size_rev// (can_eq revK). Qed. Lemma suffix_catr s1 s2 s3 : suffix s1 s2 -> suffix s1 (s3 ++ s2). Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma catl_suffix s s1 s2 : suffix (s ++ s1) s2 -> suffix s1 s2. Proof. by move=> /suffixP [s2'] ->; rewrite catA suffix_suffix. Qed. Lemma suffix_cons s x : suffix s (x :: s). Proof. by rewrite /suffix rev_cons prefix_rcons. Qed. Fixpoint infix s1 s2 := if s2 is y :: s2' then prefix s1 s2 || infix s1 s2' else s1 == [::]. Fixpoint infix_index s1 s2 := if prefix s1 s2 then 0 else if s2 is y :: s2' then (infix_index s1 s2').+1 else 1. Lemma infix0s s : infix [::] s. Proof. by case: s. Qed. Lemma infixs0 s : infix s [::] = (s == [::]). Proof. by case: s. Qed. Lemma infix_consl s1 y s2 : infix s1 (y :: s2) = prefix s1 (y :: s2) || infix s1 s2. Proof. by []. Qed. Lemma infix_indexss s : infix_index s s = 0. Proof. by case: s => //= x s; rewrite eqxx prefix_refl. Qed. Lemma infix_index_le s1 s2 : infix_index s1 s2 <= (size s2).+1. Proof. by elim: s2 => [|x s2'] /=; case: ifP. Qed. Lemma infixTindex s1 s2 : (infix_index s1 s2 <= size s2) = infix s1 s2. Proof. by elim: s2 s1 => [|y s2 +] [|x s1]//= => <-; case: ifP. Qed. Lemma infixPn s1 s2 : reflect (infix_index s1 s2 = (size s2).+1) (~~ infix s1 s2). Proof. rewrite -infixTindex -ltnNge; apply: (iffP idP) => [s2lt|->//]. by apply/eqP; rewrite eqn_leq s2lt infix_index_le. Qed. Lemma infix_index0s s : infix_index [::] s = 0. Proof. by case: s. Qed. Lemma infix_indexs0 s : infix_index s [::] = (s != [::]). Proof. by case: s. Qed. Lemma infixE s1 s2 : infix s1 s2 = (take (size s1) (drop (infix_index s1 s2) s2) == s1). Proof. elim: s2 s1 => [|y s2 +] [|x s1]//= => -> /=. by case: ifP => // /andP[/eqP-> ps1s2/=]; rewrite eqseq_cons -prefixE eqxx. Qed. Lemma infix_refl s : infix s s. Proof. by rewrite infixE infix_indexss// drop0 take_size. Qed. Lemma prefixW s1 s2 : prefix s1 s2 -> infix s1 s2. Proof. by elim: s2 s1 => [|y s2 IHs2] [|x s1]//=->. Qed. Lemma prefix_infix s1 s2 : infix s1 (s1 ++ s2). Proof. exact: prefixW. Qed. Hint Resolve prefix_infix : core. Lemma infix_infix s1 s2 s3 : infix s2 (s1 ++ s2 ++ s3). Proof. by elim: s1 => //= x s1 ->; rewrite orbT. Qed. Hint Resolve infix_infix : core. Lemma suffix_infix s1 s2 : infix s2 (s1 ++ s2). Proof. by rewrite -[X in s1 ++ X]cats0. Qed. Hint Resolve suffix_infix : core. Lemma infixP {s1 s2} : reflect (exists s s' : seq T, s2 = s ++ s1 ++ s') (infix s1 s2). Proof. apply: (iffP idP) => [|[p [s {s2}->]]]//=; rewrite infixE => /eqP<-. set k := infix_index _ _; exists (take k s2), (drop (size s1 + k) s2). by rewrite -drop_drop !cat_take_drop. Qed. Lemma infix_rev s1 s2 : infix (rev s1) (rev s2) = infix s1 s2. Proof. gen have sr : s1 s2 / infix s1 s2 -> infix (rev s1) (rev s2); last first. by apply/idP/idP => /sr; rewrite ?revK. by move=> /infixP[s [p ->]]; rewrite !rev_cat -catA. Qed. Lemma suffixW s1 s2 : suffix s1 s2 -> infix s1 s2. Proof. by rewrite -infix_rev; apply: prefixW. Qed. Lemma infix_trans : transitive infix. Proof. move=> s s1 s2 /infixP[s1p [s1s def_s]] /infixP[sp [ss def_s2]]. by apply/infixP; exists (sp ++ s1p),(s1s ++ ss); rewrite def_s2 def_s -!catA. Qed. Lemma infix_revLR s1 s2 : infix (rev s1) s2 = infix s1 (rev s2). Proof. by rewrite -infix_rev revK. Qed. Lemma infix_rconsl s1 s2 y : infix s1 (rcons s2 y) = suffix s1 (rcons s2 y) || infix s1 s2. Proof. rewrite -infix_rev rev_rcons infix_consl. by rewrite -rev_rcons prefix_rev infix_rev. Qed. Lemma infix_cons s x : infix s (x :: s). Proof. by rewrite -cat1s suffix_infix. Qed. Lemma infixs1 s x : infix s [:: x] = (s == [::]) || (s == [:: x]). Proof. by rewrite infix_consl prefixs1 orbC orbA orbb. Qed. Lemma catl_infix s s1 s2 : infix (s ++ s1) s2 -> infix s1 s2. Proof. apply: infix_trans; exact/suffixW/suffix_suffix. Qed. Lemma catr_infix s s1 s2 : infix (s1 ++ s) s2 -> infix s1 s2. Proof. by rewrite -infix_rev rev_cat => /catl_infix; rewrite infix_rev. Qed. Lemma cons2_infix s1 s2 x : infix (x :: s1) (x :: s2) -> infix s1 s2. Proof. by rewrite /= eqxx /= -cat1s => /orP[/prefixW//|]; exact: catl_infix. Qed. Lemma rcons2_infix s1 s2 x : infix (rcons s1 x) (rcons s2 x) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_rcons => /cons2_infix; rewrite infix_rev. Qed. Lemma catr2_infix s s1 s2 : infix (s ++ s1) (s ++ s2) -> infix s1 s2. Proof. by elim: s => //= x s IHs /cons2_infix. Qed. Lemma catl2_infix s s1 s2 : infix (s1 ++ s) (s2 ++ s) -> infix s1 s2. Proof. by rewrite -infix_rev !rev_cat => /catr2_infix; rewrite infix_rev. Qed. Lemma infix_catl s1 s2 s3 : infix s1 s2 -> infix s1 (s3 ++ s2). Proof. by move=> is12; apply: infix_trans is12 (suffix_infix _ _). Qed. Lemma infix_catr s1 s2 s3 : infix s1 s2 -> infix s1 (s2 ++ s3). Proof. case: s3 => [|x s /infixP [p [sf]] ->]; first by rewrite cats0. by rewrite -catA; apply: infix_catl; rewrite -catA prefix_infix. Qed. Lemma prefix_infix_trans s2 s1 s3 : prefix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW/infix_trans; apply. Qed. Lemma suffix_infix_trans s2 s1 s3 : suffix s1 s2 -> infix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW/infix_trans; apply. Qed. Lemma infix_prefix_trans s2 s1 s3 : infix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> + /prefixW; apply: infix_trans. Qed. Lemma infix_suffix_trans s2 s1 s3 : infix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> + /suffixW; apply: infix_trans. Qed. Lemma prefix_suffix_trans s2 s1 s3 : prefix s1 s2 -> suffix s2 s3 -> infix s1 s3. Proof. by move=> /prefixW + /suffixW +; apply: infix_trans. Qed. Lemma suffix_prefix_trans s2 s1 s3 : suffix s1 s2 -> prefix s2 s3 -> infix s1 s3. Proof. by move=> /suffixW + /prefixW +; apply: infix_trans. Qed. Lemma infixW s1 s2 : infix s1 s2 -> subseq s1 s2. Proof. move=> /infixP[sp [ss ->]]. exact: subseq_trans (prefix_subseq _ _) (suffix_subseq _ _). Qed. Lemma mem_infix s1 s2 : infix s1 s2 -> {subset s1 <= s2}. Proof. by move=> /infixW subH; apply: mem_subseq. Qed. Lemma infix1s s x : infix [:: x] s = (x \in s). Proof. by elim: s => // x' s /= ->; rewrite in_cons prefix0s andbT. Qed. Lemma prefix1s s x : prefix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /prefixW. Qed. Lemma suffix1s s x : suffix [:: x] s -> x \in s. Proof. by rewrite -infix1s => /suffixW. Qed. Lemma infix_rcons s x : infix s (rcons s x). Proof. by rewrite -cats1 prefix_infix. Qed. Lemma infix_uniq s1 s2 : infix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /infixW /subseq_uniq subH. Qed. Lemma prefix_uniq s1 s2 : prefix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /prefixW /infix_uniq preH. Qed. Lemma suffix_uniq s1 s2 : suffix s1 s2 -> uniq s2 -> uniq s1. Proof. by move=> /suffixW /infix_uniq preH. Qed. Lemma prefix_take s i : prefix (take i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma suffix_drop s i : suffix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma infix_take s i : infix (take i s) s. Proof. by rewrite prefixW // prefix_take. Qed. Lemma prefix_drop_gt0 s i : ~~ prefix (drop i s) s -> i > 0. Proof. by case: i => //=; rewrite drop0 ltnn prefix_refl. Qed. Lemma infix_drop s i : infix (drop i s) s. Proof. by rewrite -{2}[s](cat_take_drop i). Qed. Lemma consr_infix s1 s2 x : infix (x :: s1) s2 -> infix [:: x] s2. Proof. by rewrite -cat1s => /catr_infix. Qed. Lemma consl_infix s1 s2 x : infix (x :: s1) s2 -> infix s1 s2. Proof. by rewrite -cat1s => /catl_infix. Qed. Lemma prefix_index s1 s2 : prefix s1 s2 -> infix_index s1 s2 = 0. Proof. by case: s1 s2 => [|x s1] [|y s2] //= ->. Qed. Lemma size_infix s1 s2 : infix s1 s2 -> size s1 <= size s2. Proof. by move=> /infixW; apply: size_subseq. Qed. Lemma size_prefix s1 s2 : prefix s1 s2 -> size s1 <= size s2. Proof. by move=> /prefixW; apply: size_infix. Qed. Lemma size_suffix s1 s2 : suffix s1 s2 -> size s1 <= size s2. Proof. by move=> /suffixW; apply: size_infix. Qed. End PrefixSuffixInfix. Section AllPairsDep. Variables (S S' : Type) (T T' : S -> Type) (R : Type). Implicit Type f : forall x, T x -> R. Definition allpairs_dep f s t := [seq f x y | x <- s, y <- t x]. Lemma size_allpairs_dep f s t : size [seq f x y | x <- s, y <- t x] = sumn [seq size (t x) | x <- s]. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. Lemma allpairs0l f t : [seq f x y | x <- [::], y <- t x] = [::]. Proof. by []. Qed. Lemma allpairs0r f s : [seq f x y | x <- s, y <- [::]] = [::]. Proof. by elim: s. Qed. Lemma allpairs1l f x t : [seq f x y | x <- [:: x], y <- t x] = [seq f x y | y <- t x]. Proof. exact: cats0. Qed. Lemma allpairs1r f s y : [seq f x y | x <- s, y <- [:: y x]] = [seq f x (y x) | x <- s]. Proof. exact: flatten_map1. Qed. Lemma allpairs_cons f x s t : [seq f x y | x <- x :: s, y <- t x] = [seq f x y | y <- t x] ++ [seq f x y | x <- s, y <- t x]. Proof. by []. Qed. Lemma eq_allpairs (f1 f2 : forall x, T x -> R) s t : (forall x, f1 x =1 f2 x) -> [seq f1 x y | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. by move=> eq_f; under eq_map do under eq_map do rewrite eq_f. Qed. Lemma eq_allpairsr (f : forall x, T x -> R) s t1 t2 : (forall x, t1 x = t2 x) -> [seq f x y | x <- s, y <- t1 x] = [seq f x y | x <- s, y <- t2 x]. Proof. by move=> eq_t; under eq_map do rewrite eq_t. Qed. Lemma allpairs_cat f s1 s2 t : [seq f x y | x <- s1 ++ s2, y <- t x] = [seq f x y | x <- s1, y <- t x] ++ [seq f x y | x <- s2, y <- t x]. Proof. by rewrite map_cat flatten_cat. Qed. Lemma allpairs_rcons f x s t : [seq f x y | x <- rcons s x, y <- t x] = [seq f x y | x <- s, y <- t x] ++ [seq f x y | y <- t x]. Proof. by rewrite -cats1 allpairs_cat allpairs1l. Qed. Lemma allpairs_mapl f (g : S' -> S) s t : [seq f x y | x <- map g s, y <- t x] = [seq f (g x) y | x <- s, y <- t (g x)]. Proof. by rewrite -map_comp. Qed. Lemma allpairs_mapr f (g : forall x, T' x -> T x) s t : [seq f x y | x <- s, y <- map (g x) (t x)] = [seq f x (g x y) | x <- s, y <- t x]. Proof. by under eq_map do rewrite -map_comp. Qed. End AllPairsDep. Arguments allpairs_dep {S T R} f s t /. Lemma map_allpairs S T R R' (g : R' -> R) f s t : map g [seq f x y | x : S <- s, y : T x <- t x] = [seq g (f x y) | x <- s, y <- t x]. Proof. by rewrite map_flatten allpairs_mapl allpairs_mapr. Qed. Section AllPairsNonDep. Variables (S T R : Type) (f : S -> T -> R). Implicit Types (s : seq S) (t : seq T). Definition allpairs s t := [seq f x y | x <- s, y <- t]. Lemma size_allpairs s t : size [seq f x y | x <- s, y <- t] = size s * size t. Proof. by elim: s => //= x s IHs; rewrite size_cat size_map IHs. Qed. End AllPairsNonDep. Arguments allpairs {S T R} f s t /. Section EqAllPairsDep. Variables (S : eqType) (T : S -> eqType). Implicit Types (R : eqType) (s : seq S) (t : forall x, seq (T x)). Lemma allpairsPdep R (f : forall x, T x -> R) s t (z : R) : reflect (exists x y, [/\ x \in s, y \in t x & z = f x y]) (z \in [seq f x y | x <- s, y <- t x]). Proof. apply: (iffP flatten_mapP); first by case=> x sx /mapP[y ty ->]; exists x, y. by case=> x [y [sx ty ->]]; exists x; last apply: map_f. Qed. Variable R : eqType. Implicit Type f : forall x, T x -> R. Lemma allpairs_f_dep f s t x y : x \in s -> y \in t x -> f x y \in [seq f x y | x <- s, y <- t x]. Proof. by move=> sx ty; apply/allpairsPdep; exists x, y. Qed. Lemma eq_in_allpairs_dep f1 f2 s t : {in s, forall x, {in t x, f1 x =1 f2 x}} <-> [seq f1 x y : R | x <- s, y <- t x] = [seq f2 x y | x <- s, y <- t x]. Proof. split=> [eq_f | eq_fst x s_x]. by congr flatten; apply/eq_in_map=> x s_x; apply/eq_in_map/eq_f. apply/eq_in_map; apply/eq_in_map: x s_x; apply/eq_from_flatten_shape => //. by rewrite /shape -!map_comp; apply/eq_map=> x /=; rewrite !size_map. Qed. Lemma perm_allpairs_dep f s1 t1 s2 t2 : perm_eq s1 s2 -> {in s1, forall x, perm_eq (t1 x) (t2 x)} -> perm_eq [seq f x y | x <- s1, y <- t1 x] [seq f x y | x <- s2, y <- t2 x]. Proof. elim: s1 s2 t1 t2 => [s2 t1 t2 |a s1 IH s2 t1 t2 perm_s2 perm_t1]. by rewrite perm_sym => /perm_nilP->. have mem_a : a \in s2 by rewrite -(perm_mem perm_s2) inE eqxx. rewrite -[s2](cat_take_drop (index a s2)). rewrite allpairs_cat (drop_nth a) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC -catA perm_cat //; last first. rewrite perm_catC -allpairs_cat. rewrite -remE perm_sym IH // => [|x xI]; last first. by apply: perm_t1; rewrite inE xI orbT. by rewrite -(perm_cons a) (perm_trans perm_s2 (perm_to_rem _)). have /perm_t1 : a \in a :: s1 by rewrite inE eqxx. rewrite perm_sym; elim: (t2 a) (t1 a) => /= [s4|b s3 IH1 s4 perm_s4]. by rewrite perm_sym => /perm_nilP->. have mem_b : b \in s4 by rewrite -(perm_mem perm_s4) inE eqxx. rewrite -[s4](cat_take_drop (index b s4)). rewrite map_cat /= (drop_nth b) ?index_mem //= nth_index //=. rewrite perm_sym perm_catC /= perm_cons // perm_catC -map_cat. rewrite -remE perm_sym IH1 // -(perm_cons b). by apply: perm_trans perm_s4 (perm_to_rem _). Qed. Lemma mem_allpairs_dep f s1 t1 s2 t2 : s1 =i s2 -> {in s1, forall x, t1 x =i t2 x} -> [seq f x y | x <- s1, y <- t1 x] =i [seq f x y | x <- s2, y <- t2 x]. Proof. move=> eq_s eq_t z; apply/allpairsPdep/allpairsPdep=> -[x [y [sx ty ->]]]; by exists x, y; rewrite -eq_s in sx *; rewrite eq_t in ty *. Qed. Lemma allpairs_uniq_dep f s t (st := [seq Tagged T y | x <- s, y <- t x]) : let g (p : {x : S & T x}) : R := f (tag p) (tagged p) in uniq s -> {in s, forall x, uniq (t x)} -> {in st &, injective g} -> uniq [seq f x y | x <- s, y <- t x]. Proof. move=> g Us Ut; rewrite -(map_allpairs g (existT T)) => /map_inj_in_uniq->{f g}. elim: s Us => //= x s IHs /andP[s'x Us] in st Ut *; rewrite {st}cat_uniq. rewrite {}IHs {Us}// ?andbT => [|x1 s_s1]; last exact/Ut/mem_behead. have injT: injective (existT T x) by move=> y z /eqP; rewrite eq_Tagged => /eqP. rewrite (map_inj_in_uniq (in2W injT)) {injT}Ut ?mem_head // has_sym has_map. by apply: contra s'x => /hasP[y _ /allpairsPdep[z [_ [? _ /(congr1 tag)/=->]]]]. Qed. End EqAllPairsDep. Arguments allpairsPdep {S T R f s t z}. Section MemAllPairs. Variables (S : Type) (T : S -> Type) (R : eqType). Implicit Types (f : forall x, T x -> R) (s : seq S). Lemma perm_allpairs_catr f s t1 t2 : perm_eql [seq f x y | x <- s, y <- t1 x ++ t2 x] ([seq f x y | x <- s, y <- t1 x] ++ [seq f x y | x <- s, y <- t2 x]). Proof. apply/permPl; rewrite perm_sym; elim: s => //= x s ihs. by rewrite perm_catACA perm_cat ?map_cat. Qed. Lemma mem_allpairs_catr f s y0 t : [seq f x y | x <- s, y <- y0 x ++ t x] =i [seq f x y | x <- s, y <- y0 x] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_catr. Qed. Lemma perm_allpairs_consr f s y0 t : perm_eql [seq f x y | x <- s, y <- y0 x :: t x] ([seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]). Proof. by apply/permPl; rewrite (perm_allpairs_catr _ _ (fun=> [:: _])) allpairs1r. Qed. Lemma mem_allpairs_consr f s t y0 : [seq f x y | x <- s, y <- y0 x :: t x] =i [seq f x (y0 x) | x <- s] ++ [seq f x y | x <- s, y <- t x]. Proof. exact/perm_mem/permPl/perm_allpairs_consr. Qed. Lemma allpairs_rconsr f s y0 t : perm_eql [seq f x y | x <- s, y <- rcons (t x) (y0 x)] ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. apply/permPl; rewrite -(eq_allpairsr _ _ (fun=> cats1 _ _)). by rewrite perm_allpairs_catr allpairs1r. Qed. Lemma mem_allpairs_rconsr f s t y0 : [seq f x y | x <- s, y <- rcons (t x) (y0 x)] =i ([seq f x y | x <- s, y <- t x] ++ [seq f x (y0 x) | x <- s]). Proof. exact/perm_mem/permPl/allpairs_rconsr. Qed. End MemAllPairs. Lemma all_allpairsP (S : eqType) (T : S -> eqType) (R : Type) (p : pred R) (f : forall x : S, T x -> R) (s : seq S) (t : forall x : S, seq (T x)) : reflect (forall (x : S) (y : T x), x \in s -> y \in t x -> p (f x y)) (all p [seq f x y | x <- s, y <- t x]). Proof. elim: s => [|x s IHs]; first by constructor. rewrite /= all_cat all_map /preim. apply/(iffP andP)=> [[/allP /= ? ? x' y x'_in_xs]|p_xs_t]. by move: x'_in_xs y => /[1!inE] /predU1P [-> //|? ?]; exact: IHs. split; first by apply/allP => ?; exact/p_xs_t/mem_head. by apply/IHs => x' y x'_in_s; apply: p_xs_t; rewrite inE x'_in_s orbT. Qed. Arguments all_allpairsP {S T R p f s t}. Section EqAllPairs. Variables S T R : eqType. Implicit Types (f : S -> T -> R) (s : seq S) (t : seq T). Lemma allpairsP f s t (z : R) : reflect (exists p, [/\ p.1 \in s, p.2 \in t & z = f p.1 p.2]) (z \in [seq f x y | x <- s, y <- t]). Proof. by apply: (iffP allpairsPdep) => [[x[y]]|[[x y]]]; [exists (x, y)|exists x, y]. Qed. Lemma allpairs_f f s t x y : x \in s -> y \in t -> f x y \in [seq f x y | x <- s, y <- t]. Proof. exact: allpairs_f_dep. Qed. Lemma eq_in_allpairs f1 f2 s t : {in s & t, f1 =2 f2} <-> [seq f1 x y : R | x <- s, y <- t] = [seq f2 x y | x <- s, y <- t]. Proof. split=> [eq_f | /eq_in_allpairs_dep-eq_f x y /eq_f/(_ y)//]. by apply/eq_in_allpairs_dep=> x /eq_f. Qed. Lemma perm_allpairs f s1 t1 s2 t2 : perm_eq s1 s2 -> perm_eq t1 t2 -> perm_eq [seq f x y | x <- s1, y <- t1] [seq f x y | x <- s2, y <- t2]. Proof. by move=> perm_s perm_t; apply: perm_allpairs_dep. Qed. Lemma mem_allpairs f s1 t1 s2 t2 : s1 =i s2 -> t1 =i t2 -> [seq f x y | x <- s1, y <- t1] =i [seq f x y | x <- s2, y <- t2]. Proof. by move=> eq_s eq_t; apply: mem_allpairs_dep. Qed. Lemma allpairs_uniq f s t (st := [seq (x, y) | x <- s, y <- t]) : uniq s -> uniq t -> {in st &, injective (uncurry f)} -> uniq [seq f x y | x <- s, y <- t]. Proof. move=> Us Ut inj_f; rewrite -(map_allpairs (uncurry f) (@pair S T)) -/st. rewrite map_inj_in_uniq // allpairs_uniq_dep {Us Ut st inj_f}//. by apply: in2W => -[x1 y1] [x2 y2] /= [-> ->]. Qed. End EqAllPairs. Arguments allpairsP {S T R f s t z}. Arguments perm_nilP {T s}. Arguments perm_consP {T x s t}. Section AllRel. Variables (T S : Type) (r : T -> S -> bool). Implicit Types (x : T) (y : S) (xs : seq T) (ys : seq S). Definition allrel xs ys := all [pred x | all (r x) ys] xs. Lemma allrel0l ys : allrel [::] ys. Proof. by []. Qed. Lemma allrel0r xs : allrel xs [::]. Proof. by elim: xs. Qed. Lemma allrel_consl x xs ys : allrel (x :: xs) ys = all (r x) ys && allrel xs ys. Proof. by []. Qed. Lemma allrel_consr xs y ys : allrel xs (y :: ys) = all (r^~ y) xs && allrel xs ys. Proof. exact: all_predI. Qed. Lemma allrel_cons2 x y xs ys : allrel (x :: xs) (y :: ys) = [&& r x y, all (r x) ys, all (r^~ y) xs & allrel xs ys]. Proof. by rewrite /= allrel_consr -andbA. Qed. Lemma allrel1l x ys : allrel [:: x] ys = all (r x) ys. Proof. exact: andbT. Qed. Lemma allrel1r xs y : allrel xs [:: y] = all (r^~ y) xs. Proof. by rewrite allrel_consr allrel0r andbT. Qed. Lemma allrel_catl xs xs' ys : allrel (xs ++ xs') ys = allrel xs ys && allrel xs' ys. Proof. exact: all_cat. Qed. Lemma allrel_catr xs ys ys' : allrel xs (ys ++ ys') = allrel xs ys && allrel xs ys'. Proof. elim: ys => /= [|y ys ihys]; first by rewrite allrel0r. by rewrite !allrel_consr ihys andbA. Qed. Lemma allrel_maskl m xs ys : allrel xs ys -> allrel (mask m xs) ys. Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [xys /IHm->]; rewrite ?xys. Qed. Lemma allrel_maskr m xs ys : allrel xs ys -> allrel xs (mask m ys). Proof. by elim: xs => //= x xs IHxs /andP [/all_mask->]. Qed. Lemma allrel_filterl a xs ys : allrel xs ys -> allrel (filter a xs) ys. Proof. by rewrite filter_mask; apply: allrel_maskl. Qed. Lemma allrel_filterr a xs ys : allrel xs ys -> allrel xs (filter a ys). Proof. by rewrite filter_mask; apply: allrel_maskr. Qed. Lemma allrel_allpairsE xs ys : allrel xs ys = all id [seq r x y | x <- xs, y <- ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat all_map. Qed. End AllRel. Arguments allrel {T S} r xs ys : simpl never. Arguments allrel0l {T S} r ys. Arguments allrel0r {T S} r xs. Arguments allrel_consl {T S} r x xs ys. Arguments allrel_consr {T S} r xs y ys. Arguments allrel1l {T S} r x ys. Arguments allrel1r {T S} r xs y. Arguments allrel_catl {T S} r xs xs' ys. Arguments allrel_catr {T S} r xs ys ys'. Arguments allrel_maskl {T S} r m xs ys. Arguments allrel_maskr {T S} r m xs ys. Arguments allrel_filterl {T S} r a xs ys. Arguments allrel_filterr {T S} r a xs ys. Arguments allrel_allpairsE {T S} r xs ys. Notation all2rel r xs := (allrel r xs xs). Lemma sub_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) (r r' : T -> S -> bool) : {in P & Q, forall x y, r x y -> r' x y} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys -> allrel r' xs ys. Proof. move=> rr' + ys; elim=> //= x xs IHxs /andP [Px Pxs] Qys. rewrite !allrel_consl => /andP [+ {}/IHxs-> //]; rewrite andbT. by elim: ys Qys => //= y ys IHys /andP [Qy Qys] /andP [/rr'-> // /IHys->]. Qed. Lemma sub_allrel {T S : Type} (r r' : T -> S -> bool) : (forall x y, r x y -> r' x y) -> forall xs ys, allrel r xs ys -> allrel r' xs ys. Proof. by move=> rr' xs ys; apply/sub_in_allrel/all_predT/all_predT; apply: in2W. Qed. Lemma eq_in_allrel {T S : Type} (P : {pred T}) (Q : {pred S}) r r' : {in P & Q, r =2 r'} -> forall xs ys, all P xs -> all Q ys -> allrel r xs ys = allrel r' xs ys. Proof. move=> rr' xs ys Pxs Qys. by apply/idP/idP; apply/sub_in_allrel/Qys/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_allrel {T S : Type} (r r' : T -> S -> bool) : r =2 r' -> allrel r =2 allrel r'. Proof. by move=> rr' xs ys; apply/eq_in_allrel/all_predT/all_predT. Qed. Lemma allrelC {T S : Type} (r : T -> S -> bool) xs ys : allrel r xs ys = allrel (fun y => r^~ y) ys xs. Proof. by elim: xs => [|x xs ih]; [elim: ys | rewrite allrel_consr -ih]. Qed. Lemma allrel_mapl {T T' S : Type} (f : T' -> T) (r : T -> S -> bool) xs ys : allrel r (map f xs) ys = allrel (fun x => r (f x)) xs ys. Proof. exact: all_map. Qed. Lemma allrel_mapr {T S S' : Type} (f : S' -> S) (r : T -> S -> bool) xs ys : allrel r xs (map f ys) = allrel (fun x y => r x (f y)) xs ys. Proof. by rewrite allrelC allrel_mapl allrelC. Qed. Lemma allrelP {T S : eqType} {r : T -> S -> bool} {xs ys} : reflect {in xs & ys, forall x y, r x y} (allrel r xs ys). Proof. by rewrite allrel_allpairsE; exact: all_allpairsP. Qed. Lemma allrelT {T S : Type} (xs : seq T) (ys : seq S) : allrel (fun _ _ => true) xs ys = true. Proof. by elim: xs => //= ? ?; rewrite allrel_consl all_predT. Qed. Lemma allrel_relI {T S : Type} (r r' : T -> S -> bool) xs ys : allrel (fun x y => r x y && r' x y) xs ys = allrel r xs ys && allrel r' xs ys. Proof. by rewrite -all_predI; apply: eq_all => ?; rewrite /= -all_predI. Qed. Lemma allrel_revl {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) s2 = allrel r s1 s2. Proof. exact: all_rev. Qed. Lemma allrel_revr {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r s1 (rev s2) = allrel r s1 s2. Proof. by rewrite allrelC allrel_revl allrelC. Qed. Lemma allrel_rev2 {T S : Type} (r : T -> S -> bool) (s1 : seq T) (s2 : seq S) : allrel r (rev s1) (rev s2) = allrel r s1 s2. Proof. by rewrite allrel_revr allrel_revl. Qed. Lemma eq_allrel_meml {T : eqType} {S} (r : T -> S -> bool) (s1 s1' : seq T) s2 : s1 =i s1' -> allrel r s1 s2 = allrel r s1' s2. Proof. by move=> eqs1; apply: eq_all_r. Qed. Lemma eq_allrel_memr {T} {S : eqType} (r : T -> S -> bool) s1 (s2 s2' : seq S) : s2 =i s2' -> allrel r s1 s2 = allrel r s1 s2'. Proof. by rewrite ![allrel _ s1 _]allrelC; apply: eq_allrel_meml. Qed. Lemma eq_allrel_mem2 {T S : eqType} (r : T -> S -> bool) (s1 s1' : seq T) (s2 s2' : seq S) : s1 =i s1' -> s2 =i s2' -> allrel r s1 s2 = allrel r s1' s2'. Proof. by move=> /eq_allrel_meml -> /eq_allrel_memr ->. Qed. Section All2Rel. Variable (T : nonPropType) (r : rel T). Implicit Types (x y z : T) (xs : seq T). Hypothesis (rsym : symmetric r). Lemma all2rel1 x : all2rel r [:: x] = r x x. Proof. by rewrite /allrel /= !andbT. Qed. Lemma all2rel2 x y : all2rel r [:: x; y] = r x x && r y y && r x y. Proof. by rewrite /allrel /= rsym; do 3 case: r. Qed. Lemma all2rel_cons x xs : all2rel r (x :: xs) = [&& r x x, all (r x) xs & all2rel r xs]. Proof. rewrite allrel_cons2; congr andb; rewrite andbA -all_predI; congr andb. by elim: xs => //= y xs ->; rewrite rsym andbb. Qed. End All2Rel. Section Pairwise. Variables (T : Type) (r : T -> T -> bool). Implicit Types (x y : T) (xs ys : seq T). Fixpoint pairwise xs : bool := if xs is x :: xs then all (r x) xs && pairwise xs else true. Lemma pairwise_cons x xs : pairwise (x :: xs) = all (r x) xs && pairwise xs. Proof. by []. Qed. Lemma pairwise_cat xs ys : pairwise (xs ++ ys) = [&& allrel r xs ys, pairwise xs & pairwise ys]. Proof. by elim: xs => //= x xs ->; rewrite all_cat -!andbA; bool_congr. Qed. Lemma pairwise_rcons xs x : pairwise (rcons xs x) = all (r^~ x) xs && pairwise xs. Proof. by rewrite -cats1 pairwise_cat allrel1r andbT. Qed. Lemma pairwise2 x y : pairwise [:: x; y] = r x y. Proof. by rewrite /= !andbT. Qed. Lemma pairwise_mask m xs : pairwise xs -> pairwise (mask m xs). Proof. by elim: m xs => [|[] m IHm] [|x xs] //= /andP [? ?]; rewrite ?IHm // all_mask. Qed. Lemma pairwise_filter a xs : pairwise xs -> pairwise (filter a xs). Proof. by rewrite filter_mask; apply: pairwise_mask. Qed. Lemma pairwiseP x0 xs : reflect {in gtn (size xs) &, {homo nth x0 xs : i j / i < j >-> r i j}} (pairwise xs). Proof. elim: xs => /= [|x xs IHxs]; first exact: (iffP idP). apply: (iffP andP) => [[r_x_xs pxs] i j|Hnth]; rewrite -?topredE /= ?ltnS. by case: i j => [|i] [|j] //= gti gtj ij; [exact/all_nthP | exact/IHxs]. split; last by apply/IHxs => // i j; apply/(Hnth i.+1 j.+1). by apply/(all_nthP x0) => i gti; apply/(Hnth 0 i.+1). Qed. Lemma pairwise_all2rel : reflexive r -> symmetric r -> forall xs, pairwise xs = all2rel r xs. Proof. by move=> r_refl r_sym; elim => //= x xs ->; rewrite all2rel_cons // r_refl. Qed. End Pairwise. Arguments pairwise {T} r xs. Arguments pairwise_cons {T} r x xs. Arguments pairwise_cat {T} r xs ys. Arguments pairwise_rcons {T} r xs x. Arguments pairwise2 {T} r x y. Arguments pairwise_mask {T r} m {xs}. Arguments pairwise_filter {T r} a {xs}. Arguments pairwiseP {T r} x0 {xs}. Arguments pairwise_all2rel {T r} r_refl r_sym xs. Lemma sub_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, subrel r r'} -> forall xs, all P xs -> pairwise r xs -> pairwise r' xs. Proof. move=> rr'; elim=> //= x xs IHxs /andP [Px Pxs] /andP [+ {}/IHxs->] //. rewrite andbT; elim: xs Pxs => //= x' xs IHxs /andP [? ?] /andP [+ /IHxs->] //. by rewrite andbT; apply: rr'. Qed. Lemma sub_pairwise {T : Type} (r r' : rel T) xs : subrel r r' -> pairwise r xs -> pairwise r' xs. Proof. by move=> rr'; apply/sub_in_pairwise/all_predT; apply: in2W. Qed. Lemma eq_in_pairwise {T : Type} (P : {pred T}) (r r' : rel T) : {in P &, r =2 r'} -> forall xs, all P xs -> pairwise r xs = pairwise r' xs. Proof. move=> rr' xs Pxs. by apply/idP/idP; apply/sub_in_pairwise/Pxs => ? ? ? ?; rewrite rr'. Qed. Lemma eq_pairwise {T : Type} (r r' : rel T) : r =2 r' -> pairwise r =i pairwise r'. Proof. by move=> rr' xs; apply/eq_in_pairwise/all_predT. Qed. Lemma pairwise_map {T T' : Type} (f : T' -> T) (r : rel T) xs : pairwise r (map f xs) = pairwise (relpre f r) xs. Proof. by elim: xs => //= x xs ->; rewrite all_map. Qed. Lemma pairwise_relI {T : Type} (r r' : rel T) (s : seq T) : pairwise [rel x y | r x y && r' x y] s = pairwise r s && pairwise r' s. Proof. by elim: s => //= x s ->; rewrite andbACA all_predI. Qed. Section EqPairwise. Variables (T : eqType) (r : T -> T -> bool). Implicit Types (xs ys : seq T). Lemma subseq_pairwise xs ys : subseq xs ys -> pairwise r ys -> pairwise r xs. Proof. by case/subseqP => m _ ->; apply: pairwise_mask. Qed. Lemma uniq_pairwise xs : uniq xs = pairwise [rel x y | x != y] xs. Proof. elim: xs => //= x xs ->; congr andb; rewrite -has_pred1 -all_predC. by elim: xs => //= x' xs ->; case: eqVneq. Qed. Lemma pairwise_uniq xs : irreflexive r -> pairwise r xs -> uniq xs. Proof. move=> r_irr; rewrite uniq_pairwise; apply/sub_pairwise => x y. by apply: contraTneq => ->; rewrite r_irr. Qed. Lemma pairwise_eq : antisymmetric r -> forall xs ys, pairwise r xs -> pairwise r ys -> perm_eq xs ys -> xs = ys. Proof. move=> r_asym; elim=> [|x xs IHxs] [|y ys] //=; try by move=> ? ? /perm_size. move=> /andP [r_x_xs pxs] /andP [r_y_ys pys] eq_xs_ys. move: (mem_head y ys) (mem_head x xs). rewrite -(perm_mem eq_xs_ys) [x \in _](perm_mem eq_xs_ys) !inE. case: eqVneq eq_xs_ys => /= [->|ne_xy] eq_xs_ys ys_x xs_y. by rewrite (IHxs ys) // -(perm_cons x). by case/eqP: ne_xy; apply: r_asym; rewrite (allP r_x_xs) ?(allP r_y_ys). Qed. Lemma pairwise_trans s : antisymmetric r -> pairwise r s -> {in s & &, transitive r}. Proof. move=> /(_ _ _ _)/eqP r_anti + y x z => /pairwiseP-/(_ y) ltP ys xs zs. have [-> //|neqxy] := eqVneq x y; have [-> //|neqzy] := eqVneq z y. move=> lxy lyz; move: ys xs zs lxy neqxy lyz neqzy. move=> /(nthP y)[j jlt <-] /(nthP y)[i ilt <-] /(nthP y)[k klt <-]. have [ltij|ltji|->] := ltngtP i j; last 2 first. - by move=> leij; rewrite r_anti// leij ltP. - by move=> lejj; rewrite r_anti// lejj. move=> _ _; have [ltjk|ltkj|->] := ltngtP j k; last 2 first. - by move=> lejk; rewrite r_anti// lejk ltP. - by move=> lekk; rewrite r_anti// lekk. by move=> _ _; apply: (ltP) => //; apply: ltn_trans ltjk. Qed. End EqPairwise. Arguments subseq_pairwise {T r xs ys}. Arguments uniq_pairwise {T} xs. Arguments pairwise_uniq {T r xs}. Arguments pairwise_eq {T r} r_asym {xs ys}. Section Permutations. Variable T : eqType. Implicit Types (x : T) (s t : seq T) (bs : seq (T * nat)) (acc : seq (seq T)). Fixpoint incr_tally bs x := if bs isn't b :: bs then [:: (x, 1)] else if x == b.1 then (x, b.2.+1) :: bs else b :: incr_tally bs x. Definition tally s := foldl incr_tally [::] s. Definition wf_tally := [qualify a bs : seq (T * nat) | uniq (unzip1 bs) && (0 \notin unzip2 bs)]. Definition tally_seq bs := flatten [seq nseq b.2 b.1 | b <- bs]. Local Notation tseq := tally_seq. Lemma size_tally_seq bs : size (tally_seq bs) = sumn (unzip2 bs). Proof. by rewrite size_flatten /shape -map_comp; under eq_map do rewrite /= size_nseq. Qed. Lemma tally_seqK : {in wf_tally, cancel tally_seq tally}. Proof. move=> bs /andP[]; elim: bs => [|[x [|n]] bs IHbs] //= /andP[bs'x Ubs] bs'0. rewrite inE /tseq /tally /= -[n.+1]addn1 in bs'0 *. elim: n 1 => /= [|n IHn] m; last by rewrite eqxx IHn addnS. rewrite -{}[in RHS]IHbs {Ubs bs'0}// /tally /tally_seq add0n. elim: bs bs'x [::] => [|[y n] bs IHbs] //= /[1!inE] /norP[y'x bs'x]. by elim: n => [|n IHn] bs1 /=; [rewrite IHbs | rewrite eq_sym ifN // IHn]. Qed. Lemma incr_tallyP x : {homo incr_tally^~ x : bs / bs \in wf_tally}. Proof. move=> bs /andP[]; rewrite unfold_in. elim: bs => [|[y [|n]] bs IHbs] //= /andP[bs'y Ubs] /[1!inE] /= bs'0. have [<- | y'x] /= := eqVneq y; first by rewrite bs'y Ubs. rewrite -andbA {}IHbs {Ubs bs'0}// andbT. elim: bs bs'y => [|b bs IHbs] /=; rewrite inE ?y'x // => /norP[b'y bs'y]. by case: ifP => _; rewrite /= inE negb_or ?y'x // b'y IHbs. Qed. Lemma tallyP s : tally s \is a wf_tally. Proof. rewrite /tally; set bs := [::]; have: bs \in wf_tally by []. by elim: s bs => //= x s IHs bs /(incr_tallyP x)/IHs. Qed. Lemma tallyK s : perm_eq (tally_seq (tally s)) s. Proof. rewrite -[s in perm_eq _ s]cats0 -[nil]/(tseq [::]) /tally. elim: s [::] => //= x s IHs bs; rewrite {IHs}(permPl (IHs _)). rewrite perm_sym -cat1s perm_catCA {s}perm_cat2l. elim: bs => //= b bs IHbs; case: eqP => [-> | _] //=. by rewrite -cat1s perm_catCA perm_cat2l. Qed. Lemma tallyEl s : perm_eq (unzip1 (tally s)) (undup s). Proof. have /andP[Ubs bs'0] := tallyP s; set bs := tally s in Ubs bs'0 *. rewrite uniq_perm ?undup_uniq {Ubs}// => x. rewrite mem_undup -(perm_mem (tallyK s)) -/bs. elim: bs => [|[y [|m]] bs IHbs] //= in bs'0 *. by rewrite inE IHbs // mem_cat mem_nseq. Qed. Lemma tallyE s : perm_eq (tally s) [seq (x, count_mem x s) | x <- undup s]. Proof. have /andP[Ubs _] := tallyP s; pose b := [fun s x => (x, count_mem x (tseq s))]. suffices /permPl->: perm_eq (tally s) (map (b (tally s)) (unzip1 (tally s))). congr perm_eq: (perm_map (b (tally s)) (tallyEl s)). by under eq_map do rewrite /= (permP (tallyK s)). elim: (tally s) Ubs => [|[x m] bs IH] //= /andP[bs'x /IH-IHbs {IH}]. rewrite /tseq /= -/(tseq _) count_cat count_nseq /= eqxx mul1n. rewrite (count_memPn _) ?addn0 ?perm_cons; last first. apply: contra bs'x; elim: {b IHbs}bs => //= b bs IHbs. by rewrite mem_cat mem_nseq inE andbC; case: (_ == _). congr perm_eq: IHbs; apply/eq_in_map=> y bs_y; congr (y, _). by rewrite count_cat count_nseq /= (negPf (memPnC bs'x y bs_y)). Qed. Lemma perm_tally s1 s2 : perm_eq s1 s2 -> perm_eq (tally s1) (tally s2). Proof. move=> eq_s12; apply: (@perm_trans _ [seq (x, count_mem x s2) | x <- undup s1]). by congr perm_eq: (tallyE s1); under eq_map do rewrite (permP eq_s12). by rewrite (permPr (tallyE s2)); apply/perm_map/perm_undup/(perm_mem eq_s12). Qed. Lemma perm_tally_seq bs1 bs2 : perm_eq bs1 bs2 -> perm_eq (tally_seq bs1) (tally_seq bs2). Proof. by move=> Ebs12; rewrite perm_flatten ?perm_map. Qed. Local Notation perm_tseq := perm_tally_seq. Lemma perm_count_undup s : perm_eq (flatten [seq nseq (count_mem x s) x | x <- undup s]) s. Proof. by rewrite -(permPr (tallyK s)) (permPr (perm_tseq (tallyE s))) /tseq -map_comp. Qed. Local Fixpoint cons_perms_ perms_rec (s : seq T) bs bs2 acc := if bs isn't b :: bs1 then acc else if b isn't (x, m.+1) then cons_perms_ perms_rec s bs1 bs2 acc else let acc_xs := perms_rec (x :: s) ((x, m) :: bs1 ++ bs2) acc in cons_perms_ perms_rec s bs1 (b :: bs2) acc_xs. Local Fixpoint perms_rec n s bs acc := if n isn't n.+1 then s :: acc else cons_perms_ (perms_rec n) s bs [::] acc. Local Notation cons_perms n := (cons_perms_ (perms_rec n) [::]). Definition permutations s := perms_rec (size s) [::] (tally s) [::]. Let permsP s : exists n bs, [/\ permutations s = perms_rec n [::] bs [::], size (tseq bs) == n, perm_eq (tseq bs) s & uniq (unzip1 bs)]. Proof. have /andP[Ubs _] := tallyP s; exists (size s), (tally s). by rewrite (perm_size (tallyK s)) tallyK. Qed. Local Notation bsCA := (permEl (perm_catCA _ [:: _] _)). Let cons_permsE : forall n x bs bs1 bs2, let cp := cons_perms n bs bs2 in let perms s := perms_rec n s bs1 [::] in cp (perms [:: x]) = cp [::] ++ [seq rcons t x | t <- perms [::]]. Proof. pose is_acc f := forall acc, f acc = f [::] ++ acc. (* f is accumulating. *) have cpE: forall f & forall s bs, is_acc (f s bs), is_acc (cons_perms_ f _ _ _). move=> s bs bs2 f fE acc; elim: bs => [|[x [|m]] bs IHbs] //= in s bs2 acc *. by rewrite fE IHbs catA -IHbs. have prE: is_acc (perms_rec _ _ _) by elim=> //= n IHn s bs; apply: cpE. pose has_suffix f := forall s : seq T, f s = [seq t ++ s | t <- f [::]]. suffices prEs n bs: has_suffix (fun s => perms_rec n s bs [::]). move=> n x bs bs1 bs2 /=; rewrite cpE // prEs. by under eq_map do rewrite cats1. elim: n bs => //= n IHn bs s; elim: bs [::] => [|[x [|m]] bs IHbs] //= bs1. rewrite cpE // IHbs IHn [in RHS]cpE // [in RHS]IHn map_cat -map_comp. by congr (_ ++ _); apply: eq_map => t /=; rewrite -catA. Qed. Lemma mem_permutations s t : (t \in permutations s) = perm_eq t s. Proof. have{s} [n [bs [-> Dn /permPr<- _]]] := permsP s. elim: n => [|n IHn] /= in t bs Dn *. by rewrite inE (nilP Dn); apply/eqP/perm_nilP. rewrite -[bs in tseq bs]cats0 in Dn *; have x0 : T by case: (tseq _) Dn. rewrite -[RHS](@andb_idl (last x0 t \in tseq bs)); last first. case/lastP: t {IHn} => [|t x] Dt; first by rewrite -(perm_size Dt) in Dn. by rewrite -[bs]cats0 -(perm_mem Dt) last_rcons mem_rcons mem_head. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn *. rewrite cons_permsE -!cat_cons !mem_cat (mem_nseq m.+1) orbC andb_orl. rewrite {}IHbs ?(perm_size (perm_tseq bsCA)) //= (permPr (perm_tseq bsCA)). congr (_ || _); apply/mapP/andP=> [[t1 Dt1 ->] | [/eqP]]. by rewrite last_rcons perm_rcons perm_cons IHn in Dt1 *. case/lastP: t => [_ /perm_size//|t y]; rewrite last_rcons perm_rcons => ->. by rewrite perm_cons; exists t; rewrite ?IHn. Qed. Lemma permutations_uniq s : uniq (permutations s). Proof. have{s} [n [bs [-> Dn _ Ubs]]] := permsP s. elim: n => //= n IHn in bs Dn Ubs *; rewrite -[bs]cats0 /unzip1 in Dn Ubs. elim: bs [::] => [|[x [|m]] bs IHbs] //= bs2 in Dn Ubs *. by case/andP: Ubs => _ /IHbs->. rewrite /= cons_permsE cat_uniq has_sym andbCA andbC. rewrite {}IHbs; first 1 last; first by rewrite (perm_size (perm_tseq bsCA)). by rewrite (perm_uniq (perm_map _ bsCA)). rewrite (map_inj_uniq (rcons_injl x)) {}IHn {Dn}//=. have: x \notin unzip1 bs by apply: contraL Ubs; rewrite map_cat mem_cat => ->. move: {bs2 m Ubs}(perms_rec n _ _ _) (_ :: bs2) => ts. elim: bs => [|[y [|m]] bs IHbs] //= /[1!inE] bs2 /norP[x'y /IHbs//]. rewrite cons_permsE has_cat negb_or has_map => ->. by apply/hasPn=> t _; apply: contra x'y => /mapP[t1 _ /rcons_inj[_ ->]]. Qed. Notation perms := permutations. Lemma permutationsE s : 0 < size s -> perm_eq (perms s) [seq x :: t | x <- undup s, t <- perms (rem x s)]. Proof. move=> nt_s; apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|x _|]; rewrite ?undup_uniq ?permutations_uniq //. by case=> [_ _] [x t] _ _ [-> ->]. rewrite mem_permutations; apply/idP/allpairsPdep=> [Dt | [x [t1 []]]]. rewrite -(perm_size Dt) in nt_s; case: t nt_s => // x t _ in Dt *. have s_x: x \in s by rewrite -(perm_mem Dt) mem_head. exists x, t; rewrite mem_undup mem_permutations; split=> //. by rewrite -(perm_cons x) (permPl Dt) perm_to_rem. rewrite mem_undup mem_permutations -(perm_cons x) => s_x Dt1 ->. by rewrite (permPl Dt1) perm_sym perm_to_rem. Qed. Lemma permutationsErot x s (le_x := fun t => iota 0 (index x t + 1)) : perm_eq (perms (x :: s)) [seq rot i (x :: t) | t <- perms s, i <- le_x t]. Proof. have take'x t i: i <= index x t -> i <= size t /\ x \notin take i t. move=> le_i_x; have le_i_t: i <= size t := leq_trans le_i_x (index_size x t). case: (nthP x) => // -[j lt_j_i /eqP]; rewrite size_takel // in lt_j_i. by rewrite nth_take // [_ == _](before_find x (leq_trans lt_j_i le_i_x)). pose xrot t i := rot i (x :: t); pose xrotV t := index x (rev (rot 1 t)). have xrotK t: {in le_x t, cancel (xrot t) xrotV}. move=> i; rewrite mem_iota addn1 /xrotV => /take'x[le_i_t ti'x]. rewrite -rotD ?rev_cat //= rev_cons cat_rcons index_cat mem_rev size_rev. by rewrite ifN // size_takel //= eqxx addn0. apply/uniq_perm=> [||t]; first exact: permutations_uniq. apply/allpairs_uniq_dep=> [|t _|]; rewrite ?permutations_uniq ?iota_uniq //. move=> _ _ /allpairsPdep[t [i [_ ? ->]]] /allpairsPdep[u [j [_ ? ->]]] Etu. have Eij: i = j by rewrite -(xrotK t i) // /xrot Etu xrotK. by move: Etu; rewrite Eij => /rot_inj[->]. rewrite mem_permutations; apply/esym; apply/allpairsPdep/idP=> [[u [i]] | Dt]. rewrite mem_permutations => -[Du _ /(canLR (rotK i))]; rewrite /rotr. by set j := (j in rot j _) => Dt; apply/perm_consP; exists j, u. pose r := rev (rot 1 t); pose i := index x r; pose u := rev (take i r). have r_x: x \in r by rewrite mem_rev mem_rot (perm_mem Dt) mem_head. have [v Duv]: {v | rot i (x :: u ++ v) = t}; first exists (rev (drop i.+1 r)). rewrite -rev_cat -rev_rcons -rot1_cons -cat_cons -(nth_index x r_x). by rewrite -drop_nth ?index_mem // rot_rot !rev_rot revK rotK rotrK. exists (u ++ v), i; rewrite mem_permutations -(perm_cons x) -(perm_rot i) Duv. rewrite mem_iota addn1 ltnS /= index_cat mem_rev size_rev. by have /take'x[le_i_t ti'x] := leqnn i; rewrite ifN ?size_takel ?leq_addr. Qed. Lemma size_permutations s : uniq s -> size (permutations s) = (size s)`!. Proof. move Dn: (size s) => n Us; elim: n s => [[]|n IHn s] //= in Dn Us *. rewrite (perm_size (permutationsE _)) ?Dn // undup_id // factS -Dn. rewrite -(size_iota 0 n`!) -(size_allpairs (fun=>id)) !size_allpairs_dep. by apply/congr1/eq_in_map=> x sx; rewrite size_iota IHn ?size_rem ?Dn ?rem_uniq. Qed. Lemma permutations_all_uniq s : uniq s -> all uniq (permutations s). Proof. by move=> Us; apply/allP=> t; rewrite mem_permutations => /perm_uniq->. Qed. Lemma perm_permutations s t : perm_eq s t -> perm_eq (permutations s) (permutations t). Proof. move=> Est; apply/uniq_perm; try exact: permutations_uniq. by move=> u; rewrite !mem_permutations (permPr Est). Qed. End Permutations.
IsLimit.lean
/- Copyright (c) 2018 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Kim Morrison, Floris van Doorn -/ import Mathlib.CategoryTheory.Adjunction.Basic import Mathlib.CategoryTheory.Limits.Cones import Batteries.Tactic.Congr /-! # Limits and colimits We set up the general theory of limits and colimits in a category. In this introduction we only describe the setup for limits; it is repeated, with slightly different names, for colimits. The main structures defined in this file is * `IsLimit c`, for `c : Cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, See also `CategoryTheory.Limits.HasLimits` which further builds: * `LimitCone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `HasLimit F`, asserting the mere existence of some limit cone for `F`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable section open CategoryTheory CategoryTheory.Category CategoryTheory.Functor Opposite namespace CategoryTheory.Limits -- declare the `v`'s first; see `CategoryTheory.Category` for an explanation universe v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variable {J : Type u₁} [Category.{v₁} J] {K : Type u₂} [Category.{v₂} K] variable {C : Type u₃} [Category.{v₃} C] variable {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. -/ @[stacks 002E] structure IsLimit (t : Cone F) where /-- There is a morphism from any cone point to `t.pt` -/ lift : ∀ s : Cone F, s.pt ⟶ t.pt /-- The map makes the triangle with the two natural transformations commute -/ fac : ∀ (s : Cone F) (j : J), lift s ≫ t.π.app j = s.π.app j := by cat_disch /-- It is the unique such map to do this -/ uniq : ∀ (s : Cone F) (m : s.pt ⟶ t.pt) (_ : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s := by cat_disch attribute [reassoc (attr := simp)] IsLimit.fac namespace IsLimit instance subsingleton {t : Cone F} : Subsingleton (IsLimit t) := ⟨by intro P Q; cases P; cases Q; congr; cat_disch⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cone point of any cone over `F` to the cone point of a limit cone over `G`. -/ def map {F G : J ⥤ C} (s : Cone F) {t : Cone G} (P : IsLimit t) (α : F ⟶ G) : s.pt ⟶ t.pt := P.lift ((Cones.postcompose α).obj s) @[reassoc (attr := simp)] theorem map_π {F G : J ⥤ C} (c : Cone F) {d : Cone G} (hd : IsLimit d) (α : F ⟶ G) (j : J) : hd.map c α ≫ d.π.app j = c.π.app j ≫ α.app j := fac _ _ _ @[simp] theorem lift_self {c : Cone F} (t : IsLimit c) : t.lift c = 𝟙 c.pt := (t.uniq _ _ fun _ => id_comp _).symm -- Repackaging the definition in terms of cone morphisms. /-- The universal morphism from any other cone to a limit cone. -/ @[simps] def liftConeMorphism {t : Cone F} (h : IsLimit t) (s : Cone F) : s ⟶ t where hom := h.lift s theorem uniq_cone_morphism {s t : Cone F} (h : IsLimit t) {f f' : s ⟶ t} : f = f' := have : ∀ {g : s ⟶ t}, g = h.liftConeMorphism s := by intro g; apply ConeMorphism.ext; exact h.uniq _ _ g.w this.trans this.symm /-- Restating the definition of a limit cone in terms of the ∃! operator. -/ theorem existsUnique {t : Cone F} (h : IsLimit t) (s : Cone F) : ∃! l : s.pt ⟶ t.pt, ∀ j, l ≫ t.π.app j = s.π.app j := ⟨h.lift s, h.fac s, h.uniq s⟩ /-- Noncomputably make a limit cone from the existence of unique factorizations. -/ def ofExistsUnique {t : Cone F} (ht : ∀ s : Cone F, ∃! l : s.pt ⟶ t.pt, ∀ j, l ≫ t.π.app j = s.π.app j) : IsLimit t := by choose s hs hs' using ht exact ⟨s, hs, hs'⟩ /-- Alternative constructor for `isLimit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ @[simps] def mkConeMorphism {t : Cone F} (lift : ∀ s : Cone F, s ⟶ t) (uniq : ∀ (s : Cone F) (m : s ⟶ t), m = lift s) : IsLimit t where lift s := (lift s).hom uniq s m w := have : ConeMorphism.mk m w = lift s := by apply uniq congrArg ConeMorphism.hom this /-- Limit cones on `F` are unique up to isomorphism. -/ @[simps] def uniqueUpToIso {s t : Cone F} (P : IsLimit s) (Q : IsLimit t) : s ≅ t where hom := Q.liftConeMorphism s inv := P.liftConeMorphism t hom_inv_id := P.uniq_cone_morphism inv_hom_id := Q.uniq_cone_morphism /-- Any cone morphism between limit cones is an isomorphism. -/ theorem hom_isIso {s t : Cone F} (P : IsLimit s) (Q : IsLimit t) (f : s ⟶ t) : IsIso f := ⟨⟨P.liftConeMorphism t, ⟨P.uniq_cone_morphism, Q.uniq_cone_morphism⟩⟩⟩ /-- Limits of `F` are unique up to isomorphism. -/ def conePointUniqueUpToIso {s t : Cone F} (P : IsLimit s) (Q : IsLimit t) : s.pt ≅ t.pt := (Cones.forget F).mapIso (uniqueUpToIso P Q) @[reassoc (attr := simp)] theorem conePointUniqueUpToIso_hom_comp {s t : Cone F} (P : IsLimit s) (Q : IsLimit t) (j : J) : (conePointUniqueUpToIso P Q).hom ≫ t.π.app j = s.π.app j := (uniqueUpToIso P Q).hom.w _ @[reassoc (attr := simp)] theorem conePointUniqueUpToIso_inv_comp {s t : Cone F} (P : IsLimit s) (Q : IsLimit t) (j : J) : (conePointUniqueUpToIso P Q).inv ≫ s.π.app j = t.π.app j := (uniqueUpToIso P Q).inv.w _ @[reassoc (attr := simp)] theorem lift_comp_conePointUniqueUpToIso_hom {r s t : Cone F} (P : IsLimit s) (Q : IsLimit t) : P.lift r ≫ (conePointUniqueUpToIso P Q).hom = Q.lift r := Q.uniq _ _ (by simp) @[reassoc (attr := simp)] theorem lift_comp_conePointUniqueUpToIso_inv {r s t : Cone F} (P : IsLimit s) (Q : IsLimit t) : Q.lift r ≫ (conePointUniqueUpToIso P Q).inv = P.lift r := P.uniq _ _ (by simp) /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def ofIsoLimit {r t : Cone F} (P : IsLimit r) (i : r ≅ t) : IsLimit t := IsLimit.mkConeMorphism (fun s => P.liftConeMorphism s ≫ i.hom) fun s m => by rw [← i.comp_inv_eq]; apply P.uniq_cone_morphism @[simp] theorem ofIsoLimit_lift {r t : Cone F} (P : IsLimit r) (i : r ≅ t) (s) : (P.ofIsoLimit i).lift s = P.lift s ≫ i.hom.hom := rfl /-- Isomorphism of cones preserves whether or not they are limiting cones. -/ def equivIsoLimit {r t : Cone F} (i : r ≅ t) : IsLimit r ≃ IsLimit t where toFun h := h.ofIsoLimit i invFun h := h.ofIsoLimit i.symm left_inv := by cat_disch right_inv := by cat_disch @[simp] theorem equivIsoLimit_apply {r t : Cone F} (i : r ≅ t) (P : IsLimit r) : equivIsoLimit i P = P.ofIsoLimit i := rfl @[simp] theorem equivIsoLimit_symm_apply {r t : Cone F} (i : r ≅ t) (P : IsLimit t) : (equivIsoLimit i).symm P = P.ofIsoLimit i.symm := rfl /-- If the canonical morphism from a cone point to a limiting cone point is an iso, then the first cone was limiting also. -/ def ofPointIso {r t : Cone F} (P : IsLimit r) [i : IsIso (P.lift t)] : IsLimit t := ofIsoLimit P (by haveI : IsIso (P.liftConeMorphism t).hom := i haveI : IsIso (P.liftConeMorphism t) := Cones.cone_iso_of_hom_iso _ symm apply asIso (P.liftConeMorphism t)) variable {t : Cone F} theorem hom_lift (h : IsLimit t) {W : C} (m : W ⟶ t.pt) : m = h.lift { pt := W, π := { app := fun b => m ≫ t.π.app b } } := h.uniq { pt := W, π := { app := fun b => m ≫ t.π.app b } } m fun _ => rfl /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ theorem hom_ext (h : IsLimit t) {W : C} {f f' : W ⟶ t.pt} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- Given a right adjoint functor between categories of cones, the image of a limit cone is a limit cone. -/ def ofRightAdjoint {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} {left : Cone F ⥤ Cone G} {right : Cone G ⥤ Cone F} (adj : left ⊣ right) {c : Cone G} (t : IsLimit c) : IsLimit (right.obj c) := mkConeMorphism (fun s => adj.homEquiv s c (t.liftConeMorphism _)) fun _ _ => (Adjunction.eq_homEquiv_apply _ _ _).2 t.uniq_cone_morphism /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def ofConeEquiv {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cone G ≌ Cone F) {c : Cone G} : IsLimit (h.functor.obj c) ≃ IsLimit c where toFun P := ofIsoLimit (ofRightAdjoint h.toAdjunction P) (h.unitIso.symm.app c) invFun := ofRightAdjoint h.symm.toAdjunction left_inv := by cat_disch right_inv := by cat_disch @[simp] theorem ofConeEquiv_apply_desc {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cone G ≌ Cone F) {c : Cone G} (P : IsLimit (h.functor.obj c)) (s) : (ofConeEquiv h P).lift s = ((h.unitIso.hom.app s).hom ≫ (h.inverse.map (P.liftConeMorphism (h.functor.obj s))).hom) ≫ (h.unitIso.inv.app c).hom := rfl @[simp] theorem ofConeEquiv_symm_apply_desc {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cone G ≌ Cone F) {c : Cone G} (P : IsLimit c) (s) : ((ofConeEquiv h).symm P).lift s = (h.counitIso.inv.app s).hom ≫ (h.functor.map (P.liftConeMorphism (h.inverse.obj s))).hom := rfl /-- A cone postcomposed with a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcomposeHomEquiv {F G : J ⥤ C} (α : F ≅ G) (c : Cone F) : IsLimit ((Cones.postcompose α.hom).obj c) ≃ IsLimit c := ofConeEquiv (Cones.postcomposeEquivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcomposeInvEquiv {F G : J ⥤ C} (α : F ≅ G) (c : Cone G) : IsLimit ((Cones.postcompose α.inv).obj c) ≃ IsLimit c := postcomposeHomEquiv α.symm c /-- Constructing an equivalence `IsLimit c ≃ IsLimit d` from a natural isomorphism between the underlying functors, and then an isomorphism between `c` transported along this and `d`. -/ def equivOfNatIsoOfIso {F G : J ⥤ C} (α : F ≅ G) (c : Cone F) (d : Cone G) (w : (Cones.postcompose α.hom).obj c ≅ d) : IsLimit c ≃ IsLimit d := (postcomposeHomEquiv α _).symm.trans (equivIsoLimit w) /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def conePointsIsoOfNatIso {F G : J ⥤ C} {s : Cone F} {t : Cone G} (P : IsLimit s) (Q : IsLimit t) (w : F ≅ G) : s.pt ≅ t.pt where hom := Q.map s w.hom inv := P.map t w.inv hom_inv_id := P.hom_ext (by simp) inv_hom_id := Q.hom_ext (by simp) @[reassoc] theorem conePointsIsoOfNatIso_hom_comp {F G : J ⥤ C} {s : Cone F} {t : Cone G} (P : IsLimit s) (Q : IsLimit t) (w : F ≅ G) (j : J) : (conePointsIsoOfNatIso P Q w).hom ≫ t.π.app j = s.π.app j ≫ w.hom.app j := by simp @[reassoc] theorem conePointsIsoOfNatIso_inv_comp {F G : J ⥤ C} {s : Cone F} {t : Cone G} (P : IsLimit s) (Q : IsLimit t) (w : F ≅ G) (j : J) : (conePointsIsoOfNatIso P Q w).inv ≫ s.π.app j = t.π.app j ≫ w.inv.app j := by simp @[reassoc] theorem lift_comp_conePointsIsoOfNatIso_hom {F G : J ⥤ C} {r s : Cone F} {t : Cone G} (P : IsLimit s) (Q : IsLimit t) (w : F ≅ G) : P.lift r ≫ (conePointsIsoOfNatIso P Q w).hom = Q.map r w.hom := Q.hom_ext (by simp) @[reassoc] theorem lift_comp_conePointsIsoOfNatIso_inv {F G : J ⥤ C} {r s : Cone G} {t : Cone F} (P : IsLimit t) (Q : IsLimit s) (w : F ≅ G) : Q.lift r ≫ (conePointsIsoOfNatIso P Q w).inv = P.map r w.inv := P.hom_ext (by simp) section Equivalence open CategoryTheory.Equivalence /-- If `s : Cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whiskerEquivalence {s : Cone F} (P : IsLimit s) (e : K ≌ J) : IsLimit (s.whisker e.functor) := ofRightAdjoint (Cones.whiskeringEquivalence e).symm.toAdjunction P /-- If `s : Cone F` whiskered by an equivalence `e` is a limit cone, so is `s`. -/ def ofWhiskerEquivalence {s : Cone F} (e : K ≌ J) (P : IsLimit (s.whisker e.functor)) : IsLimit s := equivIsoLimit ((Cones.whiskeringEquivalence e).unitIso.app s).symm (ofRightAdjoint (Cones.whiskeringEquivalence e).toAdjunction P) /-- Given an equivalence of diagrams `e`, `s` is a limit cone iff `s.whisker e.functor` is. -/ def whiskerEquivalenceEquiv {s : Cone F} (e : K ≌ J) : IsLimit s ≃ IsLimit (s.whisker e.functor) := ⟨fun h => h.whiskerEquivalence e, ofWhiskerEquivalence e, by cat_disch, by cat_disch⟩ /-- A limit cone extended by an isomorphism is a limit cone. -/ def extendIso {s : Cone F} {X : C} (i : X ⟶ s.pt) [IsIso i] (hs : IsLimit s) : IsLimit (s.extend i) := IsLimit.ofIsoLimit hs (Cones.extendIso s (asIso i)).symm /-- A cone is a limit cone if its extension by an isomorphism is. -/ def ofExtendIso {s : Cone F} {X : C} (i : X ⟶ s.pt) [IsIso i] (hs : IsLimit (s.extend i)) : IsLimit s := IsLimit.ofIsoLimit hs (Cones.extendIso s (asIso i)) /-- A cone is a limit cone iff its extension by an isomorphism is. -/ def extendIsoEquiv {s : Cone F} {X : C} (i : X ⟶ s.pt) [IsIso i] : IsLimit s ≃ IsLimit (s.extend i) := equivOfSubsingletonOfSubsingleton (extendIso i) (ofExtendIso i) /-- We can prove two cone points `(s : Cone F).pt` and `(t : Cone G).pt` are isomorphic if * both cones are limit cones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def conePointsIsoOfEquivalence {F : J ⥤ C} {s : Cone F} {G : K ⥤ C} {t : Cone G} (P : IsLimit s) (Q : IsLimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.pt ≅ t.pt := let w' : e.inverse ⋙ F ≅ G := (isoWhiskerLeft e.inverse w).symm ≪≫ invFunIdAssoc e G { hom := Q.lift ((Cones.equivalenceOfReindexing e.symm w').functor.obj s) inv := P.lift ((Cones.equivalenceOfReindexing e w).functor.obj t) hom_inv_id := by apply hom_ext P; intro j dsimp [w'] simp only [Limits.Cone.whisker_π, Limits.Cones.postcompose_obj_π, fac, whiskerLeft_app, assoc, id_comp, invFunIdAssoc_hom_app, fac_assoc, NatTrans.comp_app] rw [counit_app_functor, ← Functor.comp_map] have l : NatTrans.app w.hom j = NatTrans.app w.hom ((𝟭 J).obj j) := by dsimp rw [l, w.hom.naturality] simp inv_hom_id := by apply hom_ext Q cat_disch } end Equivalence /-- The universal property of a limit cone: a wap `W ⟶ t.pt` is the same as a cone on `F` with cone point `W`. -/ @[simps apply] def homEquiv (h : IsLimit t) {W : C} : (W ⟶ t.pt) ≃ ((Functor.const J).obj W ⟶ F) where toFun f := (t.extend f).π invFun π := h.lift (Cone.mk _ π) left_inv f := h.hom_ext (by simp) right_inv π := by cat_disch /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with cone point `W`. -/ def homIso (h : IsLimit t) (W : C) : ULift.{u₁} (W ⟶ t.pt : Type v₃) ≅ (const J).obj W ⟶ F := Equiv.toIso (Equiv.ulift.trans h.homEquiv) @[simp] theorem homIso_hom (h : IsLimit t) {W : C} (f : ULift.{u₁} (W ⟶ t.pt)) : (IsLimit.homIso h W).hom f = (t.extend f.down).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with cone point `W`. -/ def natIso (h : IsLimit t) : yoneda.obj t.pt ⋙ uliftFunctor.{u₁} ≅ F.cones := NatIso.ofComponents fun W => IsLimit.homIso h (unop W) /-- Another, more explicit, formulation of the universal property of a limit cone. See also `homIso`. -/ def homIso' (h : IsLimit t) (W : C) : ULift.{u₁} (W ⟶ t.pt : Type v₃) ≅ { p : ∀ j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.homIso W ≪≫ { hom := fun π => ⟨fun j => π.app j, fun f => by convert ← (π.naturality f).symm; apply id_comp⟩ inv := fun p => { app := fun j => p.1 j naturality := fun j j' f => by dsimp; rw [id_comp]; exact (p.2 f).symm } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def ofFaithful {t : Cone F} {D : Type u₄} [Category.{v₄} D] (G : C ⥤ D) [G.Faithful] (ht : IsLimit (mapCone G t)) (lift : ∀ s : Cone F, s.pt ⟶ t.pt) (h : ∀ s, G.map (lift s) = ht.lift (mapCone G s)) : IsLimit t := { lift fac := fun s j => by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac uniq := fun s m w => by apply G.map_injective; rw [h] refine ht.uniq (mapCone G s) _ fun j => ?_ convert ← congrArg (fun f => G.map f) (w j) apply G.map_comp } /-- If `F` and `G` are naturally isomorphic, then `F.mapCone c` being a limit implies `G.mapCone c` is also a limit. -/ def mapConeEquiv {D : Type u₄} [Category.{v₄} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : Cone K} (t : IsLimit (mapCone F c)) : IsLimit (mapCone G c) := by apply postcomposeInvEquiv (isoWhiskerLeft K h :) (mapCone G c) _ apply t.ofIsoLimit (postcomposeWhiskerLeftMapCone h.symm c).symm /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def isoUniqueConeMorphism {t : Cone F} : IsLimit t ≅ ∀ s, Unique (s ⟶ t) where hom h s := { default := h.liftConeMorphism s uniq := fun _ => h.uniq_cone_morphism } inv h := { lift := fun s => (h s).default.hom uniq := fun s f w => congrArg ConeMorphism.hom ((h s).uniq ⟨f, w⟩) } namespace OfNatIso variable {X : C} (h : F.cones.RepresentableBy X) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def coneOfHom {Y : C} (f : Y ⟶ X) : Cone F where pt := Y π := h.homEquiv f /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.pt ⟶ X`. -/ def homOfCone (s : Cone F) : s.pt ⟶ X := h.homEquiv.symm s.π @[simp] theorem coneOfHom_homOfCone (s : Cone F) : coneOfHom h (homOfCone h s) = s := by dsimp [coneOfHom, homOfCone] match s with | .mk s_pt s_π => congr exact h.homEquiv.apply_symm_apply s_π @[simp] theorem homOfCone_coneOfHom {Y : C} (f : Y ⟶ X) : homOfCone h (coneOfHom h f) = f := by simp [coneOfHom, homOfCone] /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limitCone : Cone F := coneOfHom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ theorem coneOfHom_fac {Y : C} (f : Y ⟶ X) : coneOfHom h f = (limitCone h).extend f := by dsimp [coneOfHom, limitCone, Cone.extend] congr conv_lhs => rw [← Category.comp_id f] exact h.homEquiv_comp f (𝟙 X) /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ theorem cone_fac (s : Cone F) : (limitCone h).extend (homOfCone h s) = s := by rw [← coneOfHom_homOfCone h s] conv_lhs => simp only [homOfCone_coneOfHom] apply (coneOfHom_fac _ _).symm end OfNatIso section open OfNatIso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def ofRepresentableBy {X : C} (h : F.cones.RepresentableBy X) : IsLimit (limitCone h) where lift s := homOfCone h s fac s j := by have h := cone_fac h s cases s injection h with h₁ h₂ simp only at h₂ conv_rhs => rw [← h₂] rfl uniq s m w := by rw [← homOfCone_coneOfHom h m] congr rw [coneOfHom_fac] dsimp [Cone.extend]; cases s; congr with j; exact w j @[deprecated (since := "2025-05-09")] alias ofNatIso := ofRepresentableBy /-- Given a limit cone, `F.cones` is representable by the point of the cone. -/ def representableBy (hc : IsLimit t) : F.cones.RepresentableBy t.pt where homEquiv := hc.homEquiv homEquiv_comp {X X'} f g := NatTrans.ext <| funext fun j ↦ by simp end end IsLimit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. -/ @[stacks 002F] structure IsColimit (t : Cocone F) where /-- `t.pt` maps to all other cocone covertices -/ desc : ∀ s : Cocone F, t.pt ⟶ s.pt /-- The map `desc` makes the diagram with the natural transformations commute -/ fac : ∀ (s : Cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j := by cat_disch /-- `desc` is the unique such map -/ uniq : ∀ (s : Cocone F) (m : t.pt ⟶ s.pt) (_ : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s := by cat_disch attribute [reassoc (attr := simp)] IsColimit.fac namespace IsColimit instance subsingleton {t : Cocone F} : Subsingleton (IsColimit t) := ⟨by intro P Q; cases P; cases Q; congr; cat_disch⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cocone point of a colimit cocone over `F` to the cocone point of any cocone over `G`. -/ def map {F G : J ⥤ C} {s : Cocone F} (P : IsColimit s) (t : Cocone G) (α : F ⟶ G) : s.pt ⟶ t.pt := P.desc ((Cocones.precompose α).obj t) @[reassoc (attr := simp)] theorem ι_map {F G : J ⥤ C} {c : Cocone F} (hc : IsColimit c) (d : Cocone G) (α : F ⟶ G) (j : J) : c.ι.app j ≫ IsColimit.map hc d α = α.app j ≫ d.ι.app j := fac _ _ _ @[simp] theorem desc_self {t : Cocone F} (h : IsColimit t) : h.desc t = 𝟙 t.pt := (h.uniq _ _ fun _ => comp_id _).symm -- Repackaging the definition in terms of cocone morphisms. /-- The universal morphism from a colimit cocone to any other cocone. -/ @[simps] def descCoconeMorphism {t : Cocone F} (h : IsColimit t) (s : Cocone F) : t ⟶ s where hom := h.desc s theorem uniq_cocone_morphism {s t : Cocone F} (h : IsColimit t) {f f' : t ⟶ s} : f = f' := have : ∀ {g : t ⟶ s}, g = h.descCoconeMorphism s := by intro g; ext; exact h.uniq _ _ g.w this.trans this.symm /-- Restating the definition of a colimit cocone in terms of the ∃! operator. -/ theorem existsUnique {t : Cocone F} (h : IsColimit t) (s : Cocone F) : ∃! d : t.pt ⟶ s.pt, ∀ j, t.ι.app j ≫ d = s.ι.app j := ⟨h.desc s, h.fac s, h.uniq s⟩ /-- Noncomputably make a colimit cocone from the existence of unique factorizations. -/ def ofExistsUnique {t : Cocone F} (ht : ∀ s : Cocone F, ∃! d : t.pt ⟶ s.pt, ∀ j, t.ι.app j ≫ d = s.ι.app j) : IsColimit t := by choose s hs hs' using ht exact ⟨s, hs, hs'⟩ /-- Alternative constructor for `IsColimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ @[simps] def mkCoconeMorphism {t : Cocone F} (desc : ∀ s : Cocone F, t ⟶ s) (uniq' : ∀ (s : Cocone F) (m : t ⟶ s), m = desc s) : IsColimit t where desc s := (desc s).hom uniq s m w := have : CoconeMorphism.mk m w = desc s := by apply uniq' congrArg CoconeMorphism.hom this /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simps] def uniqueUpToIso {s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) : s ≅ t where hom := P.descCoconeMorphism t inv := Q.descCoconeMorphism s hom_inv_id := P.uniq_cocone_morphism inv_hom_id := Q.uniq_cocone_morphism /-- Any cocone morphism between colimit cocones is an isomorphism. -/ theorem hom_isIso {s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) (f : s ⟶ t) : IsIso f := ⟨⟨Q.descCoconeMorphism s, ⟨P.uniq_cocone_morphism, Q.uniq_cocone_morphism⟩⟩⟩ /-- Colimits of `F` are unique up to isomorphism. -/ def coconePointUniqueUpToIso {s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) : s.pt ≅ t.pt := (Cocones.forget F).mapIso (uniqueUpToIso P Q) @[reassoc (attr := simp)] theorem comp_coconePointUniqueUpToIso_hom {s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) (j : J) : s.ι.app j ≫ (coconePointUniqueUpToIso P Q).hom = t.ι.app j := (uniqueUpToIso P Q).hom.w _ @[reassoc (attr := simp)] theorem comp_coconePointUniqueUpToIso_inv {s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) (j : J) : t.ι.app j ≫ (coconePointUniqueUpToIso P Q).inv = s.ι.app j := (uniqueUpToIso P Q).inv.w _ @[reassoc (attr := simp)] theorem coconePointUniqueUpToIso_hom_desc {r s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) : (coconePointUniqueUpToIso P Q).hom ≫ Q.desc r = P.desc r := P.uniq _ _ (by simp) @[reassoc (attr := simp)] theorem coconePointUniqueUpToIso_inv_desc {r s t : Cocone F} (P : IsColimit s) (Q : IsColimit t) : (coconePointUniqueUpToIso P Q).inv ≫ P.desc r = Q.desc r := Q.uniq _ _ (by simp) /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def ofIsoColimit {r t : Cocone F} (P : IsColimit r) (i : r ≅ t) : IsColimit t := IsColimit.mkCoconeMorphism (fun s => i.inv ≫ P.descCoconeMorphism s) fun s m => by rw [i.eq_inv_comp]; apply P.uniq_cocone_morphism @[simp] theorem ofIsoColimit_desc {r t : Cocone F} (P : IsColimit r) (i : r ≅ t) (s) : (P.ofIsoColimit i).desc s = i.inv.hom ≫ P.desc s := rfl /-- Isomorphism of cocones preserves whether or not they are colimiting cocones. -/ def equivIsoColimit {r t : Cocone F} (i : r ≅ t) : IsColimit r ≃ IsColimit t where toFun h := h.ofIsoColimit i invFun h := h.ofIsoColimit i.symm left_inv := by cat_disch right_inv := by cat_disch @[simp] theorem equivIsoColimit_apply {r t : Cocone F} (i : r ≅ t) (P : IsColimit r) : equivIsoColimit i P = P.ofIsoColimit i := rfl @[simp] theorem equivIsoColimit_symm_apply {r t : Cocone F} (i : r ≅ t) (P : IsColimit t) : (equivIsoColimit i).symm P = P.ofIsoColimit i.symm := rfl /-- If the canonical morphism to a cocone point from a colimiting cocone point is an iso, then the first cocone was colimiting also. -/ def ofPointIso {r t : Cocone F} (P : IsColimit r) [i : IsIso (P.desc t)] : IsColimit t := ofIsoColimit P (by haveI : IsIso (P.descCoconeMorphism t).hom := i haveI : IsIso (P.descCoconeMorphism t) := Cocones.cocone_iso_of_hom_iso _ apply asIso (P.descCoconeMorphism t)) variable {t : Cocone F} theorem hom_desc (h : IsColimit t) {W : C} (m : t.pt ⟶ W) : m = h.desc { pt := W ι := { app := fun b => t.ι.app b ≫ m } } := h.uniq { pt := W ι := { app := fun b => t.ι.app b ≫ m } } m fun _ => rfl /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ theorem hom_ext (h : IsColimit t) {W : C} {f f' : t.pt ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- Given a left adjoint functor between categories of cocones, the image of a colimit cocone is a colimit cocone. -/ def ofLeftAdjoint {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} {left : Cocone G ⥤ Cocone F} {right : Cocone F ⥤ Cocone G} (adj : left ⊣ right) {c : Cocone G} (t : IsColimit c) : IsColimit (left.obj c) := mkCoconeMorphism (fun s => (adj.homEquiv c s).symm (t.descCoconeMorphism _)) fun _ _ => (Adjunction.homEquiv_apply_eq _ _ _).1 t.uniq_cocone_morphism /-- Given two functors which have equivalent categories of cocones, we can transport a colimiting cocone across the equivalence. -/ def ofCoconeEquiv {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cocone G ≌ Cocone F) {c : Cocone G} : IsColimit (h.functor.obj c) ≃ IsColimit c where toFun P := ofIsoColimit (ofLeftAdjoint h.symm.toAdjunction P) (h.unitIso.symm.app c) invFun := ofLeftAdjoint h.toAdjunction left_inv := by cat_disch right_inv := by cat_disch @[simp] theorem ofCoconeEquiv_apply_desc {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cocone G ≌ Cocone F) {c : Cocone G} (P : IsColimit (h.functor.obj c)) (s) : (ofCoconeEquiv h P).desc s = (h.unit.app c).hom ≫ (h.inverse.map (P.descCoconeMorphism (h.functor.obj s))).hom ≫ (h.unitInv.app s).hom := rfl @[simp] theorem ofCoconeEquiv_symm_apply_desc {D : Type u₄} [Category.{v₄} D] {G : K ⥤ D} (h : Cocone G ≌ Cocone F) {c : Cocone G} (P : IsColimit c) (s) : ((ofCoconeEquiv h).symm P).desc s = (h.functor.map (P.descCoconeMorphism (h.inverse.obj s))).hom ≫ (h.counit.app s).hom := rfl /-- A cocone precomposed with a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precomposeHomEquiv {F G : J ⥤ C} (α : F ≅ G) (c : Cocone G) : IsColimit ((Cocones.precompose α.hom).obj c) ≃ IsColimit c := ofCoconeEquiv (Cocones.precomposeEquivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precomposeInvEquiv {F G : J ⥤ C} (α : F ≅ G) (c : Cocone F) : IsColimit ((Cocones.precompose α.inv).obj c) ≃ IsColimit c := precomposeHomEquiv α.symm c /-- Constructing an equivalence `is_colimit c ≃ is_colimit d` from a natural isomorphism between the underlying functors, and then an isomorphism between `c` transported along this and `d`. -/ def equivOfNatIsoOfIso {F G : J ⥤ C} (α : F ≅ G) (c : Cocone F) (d : Cocone G) (w : (Cocones.precompose α.inv).obj c ≅ d) : IsColimit c ≃ IsColimit d := (precomposeInvEquiv α _).symm.trans (equivIsoColimit w) /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def coconePointsIsoOfNatIso {F G : J ⥤ C} {s : Cocone F} {t : Cocone G} (P : IsColimit s) (Q : IsColimit t) (w : F ≅ G) : s.pt ≅ t.pt where hom := P.map t w.hom inv := Q.map s w.inv hom_inv_id := P.hom_ext (by simp) inv_hom_id := Q.hom_ext (by simp) @[reassoc] theorem comp_coconePointsIsoOfNatIso_hom {F G : J ⥤ C} {s : Cocone F} {t : Cocone G} (P : IsColimit s) (Q : IsColimit t) (w : F ≅ G) (j : J) : s.ι.app j ≫ (coconePointsIsoOfNatIso P Q w).hom = w.hom.app j ≫ t.ι.app j := by simp @[reassoc] theorem comp_coconePointsIsoOfNatIso_inv {F G : J ⥤ C} {s : Cocone F} {t : Cocone G} (P : IsColimit s) (Q : IsColimit t) (w : F ≅ G) (j : J) : t.ι.app j ≫ (coconePointsIsoOfNatIso P Q w).inv = w.inv.app j ≫ s.ι.app j := by simp @[reassoc] theorem coconePointsIsoOfNatIso_hom_desc {F G : J ⥤ C} {s : Cocone F} {r t : Cocone G} (P : IsColimit s) (Q : IsColimit t) (w : F ≅ G) : (coconePointsIsoOfNatIso P Q w).hom ≫ Q.desc r = P.map _ w.hom := P.hom_ext (by simp) @[reassoc] theorem coconePointsIsoOfNatIso_inv_desc {F G : J ⥤ C} {s : Cocone G} {r t : Cocone F} (P : IsColimit t) (Q : IsColimit s) (w : F ≅ G) : (coconePointsIsoOfNatIso P Q w).inv ≫ P.desc r = Q.map _ w.inv := Q.hom_ext (by simp) section Equivalence open CategoryTheory.Equivalence /-- If `s : Cocone F` is a colimit cocone, so is `s` whiskered by an equivalence `e`. -/ def whiskerEquivalence {s : Cocone F} (P : IsColimit s) (e : K ≌ J) : IsColimit (s.whisker e.functor) := ofLeftAdjoint (Cocones.whiskeringEquivalence e).toAdjunction P /-- If `s : Cocone F` whiskered by an equivalence `e` is a colimit cocone, so is `s`. -/ def ofWhiskerEquivalence {s : Cocone F} (e : K ≌ J) (P : IsColimit (s.whisker e.functor)) : IsColimit s := equivIsoColimit ((Cocones.whiskeringEquivalence e).unitIso.app s).symm (ofLeftAdjoint (Cocones.whiskeringEquivalence e).symm.toAdjunction P) /-- Given an equivalence of diagrams `e`, `s` is a colimit cocone iff `s.whisker e.functor` is. -/ def whiskerEquivalenceEquiv {s : Cocone F} (e : K ≌ J) : IsColimit s ≃ IsColimit (s.whisker e.functor) := ⟨fun h => h.whiskerEquivalence e, ofWhiskerEquivalence e, by cat_disch, by cat_disch⟩ /-- A colimit cocone extended by an isomorphism is a colimit cocone. -/ def extendIso {s : Cocone F} {X : C} (i : s.pt ⟶ X) [IsIso i] (hs : IsColimit s) : IsColimit (s.extend i) := IsColimit.ofIsoColimit hs (Cocones.extendIso s (asIso i)) /-- A cocone is a colimit cocone if its extension by an isomorphism is. -/ def ofExtendIso {s : Cocone F} {X : C} (i : s.pt ⟶ X) [IsIso i] (hs : IsColimit (s.extend i)) : IsColimit s := IsColimit.ofIsoColimit hs (Cocones.extendIso s (asIso i)).symm /-- A cocone is a colimit cocone iff its extension by an isomorphism is. -/ def extendIsoEquiv {s : Cocone F} {X : C} (i : s.pt ⟶ X) [IsIso i] : IsColimit s ≃ IsColimit (s.extend i) := equivOfSubsingletonOfSubsingleton (extendIso i) (ofExtendIso i) /-- We can prove two cocone points `(s : Cocone F).pt` and `(t : Cocone G).pt` are isomorphic if * both cocones are colimit cocones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cocone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def coconePointsIsoOfEquivalence {F : J ⥤ C} {s : Cocone F} {G : K ⥤ C} {t : Cocone G} (P : IsColimit s) (Q : IsColimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.pt ≅ t.pt := let w' : e.inverse ⋙ F ≅ G := (isoWhiskerLeft e.inverse w).symm ≪≫ invFunIdAssoc e G { hom := P.desc ((Cocones.equivalenceOfReindexing e w).functor.obj t) inv := Q.desc ((Cocones.equivalenceOfReindexing e.symm w').functor.obj s) hom_inv_id := by apply hom_ext P; intro j dsimp [w'] simp only [Limits.Cocone.whisker_ι, fac, invFunIdAssoc_inv_app, whiskerLeft_app, assoc, comp_id, Limits.Cocones.precompose_obj_ι, fac_assoc, NatTrans.comp_app] rw [counitInv_app_functor, ← Functor.comp_map, ← w.inv.naturality_assoc] simp inv_hom_id := by apply hom_ext Q cat_disch } end Equivalence /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with cone point `W`. -/ def homEquiv (h : IsColimit t) {W : C} : (t.pt ⟶ W) ≃ (F ⟶ (const J).obj W) where toFun f := (t.extend f).ι invFun ι := h.desc { pt := W ι } left_inv f := h.hom_ext (by simp) right_inv ι := by cat_disch @[simp] lemma homEquiv_apply (h : IsColimit t) {W : C} (f : t.pt ⟶ W) : h.homEquiv f = (t.extend f).ι := rfl /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with cone point `W`. -/ def homIso (h : IsColimit t) (W : C) : ULift.{u₁} (t.pt ⟶ W : Type v₃) ≅ F ⟶ (const J).obj W := Equiv.toIso (Equiv.ulift.trans h.homEquiv) @[simp] theorem homIso_hom (h : IsColimit t) {W : C} (f : ULift (t.pt ⟶ W)) : (IsColimit.homIso h W).hom f = (t.extend f.down).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with cone point `W`. -/ def natIso (h : IsColimit t) : coyoneda.obj (op t.pt) ⋙ uliftFunctor.{u₁} ≅ F.cocones := NatIso.ofComponents (IsColimit.homIso h) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `homIso`. -/ def homIso' (h : IsColimit t) (W : C) : ULift.{u₁} (t.pt ⟶ W : Type v₃) ≅ { p : ∀ j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.homIso W ≪≫ { hom := fun ι => ⟨fun j => ι.app j, fun {j} {j'} f => by convert ← ι.naturality f; apply comp_id⟩ inv := fun p => { app := fun j => p.1 j naturality := fun j j' f => by dsimp; rw [comp_id]; exact p.2 f } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def ofFaithful {t : Cocone F} {D : Type u₄} [Category.{v₄} D] (G : C ⥤ D) [G.Faithful] (ht : IsColimit (mapCocone G t)) (desc : ∀ s : Cocone F, t.pt ⟶ s.pt) (h : ∀ s, G.map (desc s) = ht.desc (mapCocone G s)) : IsColimit t := { desc fac := fun s j => by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac uniq := fun s m w => by apply G.map_injective; rw [h] refine ht.uniq (mapCocone G s) _ fun j => ?_ convert ← congrArg (fun f => G.map f) (w j) apply G.map_comp } /-- If `F` and `G` are naturally isomorphic, then `F.mapCocone c` being a colimit implies `G.mapCocone c` is also a colimit. -/ def mapCoconeEquiv {D : Type u₄} [Category.{v₄} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : Cocone K} (t : IsColimit (mapCocone F c)) : IsColimit (mapCocone G c) := by apply IsColimit.ofIsoColimit _ (precomposeWhiskerLeftMapCocone h c) apply (precomposeInvEquiv (isoWhiskerLeft K h :) _).symm t /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def isoUniqueCoconeMorphism {t : Cocone F} : IsColimit t ≅ ∀ s, Unique (t ⟶ s) where hom h s := { default := h.descCoconeMorphism s uniq := fun _ => h.uniq_cocone_morphism } inv h := { desc := fun s => (h s).default.hom uniq := fun s f w => congrArg CoconeMorphism.hom ((h s).uniq ⟨f, w⟩) } namespace OfNatIso variable {X : C} (h : F.cocones.CorepresentableBy X) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def coconeOfHom {Y : C} (f : X ⟶ Y) : Cocone F where pt := Y ι := h.homEquiv f /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.pt`. -/ def homOfCocone (s : Cocone F) : X ⟶ s.pt := h.homEquiv.symm s.ι @[simp] theorem coconeOfHom_homOfCocone (s : Cocone F) : coconeOfHom h (homOfCocone h s) = s := by dsimp [coconeOfHom, homOfCocone] match s with | .mk s_pt s_ι => congr exact h.homEquiv.apply_symm_apply s_ι @[simp] theorem homOfCocone_coconeOfHom {Y : C} (f : X ⟶ Y) : homOfCocone h (coconeOfHom h f) = f := by simp [homOfCocone, coconeOfHom] @[deprecated (since := "2025-05-13")] alias homOfCocone_cooneOfHom := homOfCocone_coconeOfHom /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimitCocone : Cocone F := coconeOfHom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ theorem coconeOfHom_fac {Y : C} (f : X ⟶ Y) : coconeOfHom h f = (colimitCocone h).extend f := by dsimp [coconeOfHom, colimitCocone, Cocone.extend] congr conv_lhs => rw [← Category.id_comp f] exact h.homEquiv_comp f (𝟙 X) /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ theorem cocone_fac (s : Cocone F) : (colimitCocone h).extend (homOfCocone h s) = s := by rw [← coconeOfHom_homOfCocone h s] conv_lhs => simp only [homOfCocone_coconeOfHom] apply (coconeOfHom_fac _ _).symm end OfNatIso section open OfNatIso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def ofCorepresentableBy {X : C} (h : F.cocones.CorepresentableBy X) : IsColimit (colimitCocone h) where desc s := homOfCocone h s fac s j := by have h := cocone_fac h s cases s injection h with h₁ h₂ simp only at h₂ conv_rhs => rw [← h₂] rfl uniq s m w := by rw [← homOfCocone_coconeOfHom h m] congr rw [coconeOfHom_fac] dsimp [Cocone.extend]; cases s; congr with j; exact w j @[deprecated (since := "2025-05-09")] alias ofNatIso := ofCorepresentableBy /-- Given a colimit cocone, `F.cocones` is corepresentable by the point of the cocone. -/ def corepresentableBy (hc : IsColimit t) : F.cocones.CorepresentableBy t.pt where homEquiv := hc.homEquiv homEquiv_comp {X X'} f g := NatTrans.ext <| funext fun j ↦ by simp end end IsColimit end CategoryTheory.Limits
FiniteProductsOfBinaryProducts.lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import Mathlib.CategoryTheory.Limits.Preserves.Finite import Mathlib.CategoryTheory.Limits.Preserves.Shapes.BinaryProducts import Mathlib.CategoryTheory.Limits.Preserves.Shapes.Products /-! # Constructing finite products from binary products and terminal. If a category has binary products and a terminal object then it has finite products. If a functor preserves binary products and the terminal object then it preserves finite products. ## TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ universe v v' u u' noncomputable section open CategoryTheory CategoryTheory.Category CategoryTheory.Limits namespace CategoryTheory variable {J : Type v} [SmallCategory J] variable {C : Type u} [Category.{v} C] variable {D : Type u'} [Category.{v'} D] /-- Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.pt` and a binary fan on `c₁.pt` and `f 0`, we can build a fan for all `n+1`. In `extendFanIsLimit` we show that if the two given fans are limits, then this fan is also a limit. -/ @[simps!] def extendFan {n : ℕ} {f : Fin (n + 1) → C} (c₁ : Fan fun i : Fin n => f i.succ) (c₂ : BinaryFan (f 0) c₁.pt) : Fan f := Fan.mk c₂.pt (by refine Fin.cases ?_ ?_ · apply c₂.fst · intro i apply c₂.snd ≫ c₁.π.app ⟨i⟩) /-- Show that if the two given fans in `extendFan` are limits, then the constructed fan is also a limit. -/ def extendFanIsLimit {n : ℕ} (f : Fin (n + 1) → C) {c₁ : Fan fun i : Fin n => f i.succ} {c₂ : BinaryFan (f 0) c₁.pt} (t₁ : IsLimit c₁) (t₂ : IsLimit c₂) : IsLimit (extendFan c₁ c₂) where lift s := by apply (BinaryFan.IsLimit.lift' t₂ (s.π.app ⟨0⟩) _).1 apply t₁.lift ⟨_, Discrete.natTrans fun ⟨i⟩ => s.π.app ⟨i.succ⟩⟩ fac := fun s ⟨j⟩ => by refine Fin.inductionOn j ?_ ?_ · apply (BinaryFan.IsLimit.lift' t₂ _ _).2.1 · rintro i - dsimp only [extendFan_π_app] rw [Fin.cases_succ, ← assoc, (BinaryFan.IsLimit.lift' t₂ _ _).2.2, t₁.fac] rfl uniq s m w := by apply BinaryFan.IsLimit.hom_ext t₂ · rw [(BinaryFan.IsLimit.lift' t₂ _ _).2.1] apply w ⟨0⟩ · rw [(BinaryFan.IsLimit.lift' t₂ _ _).2.2] apply t₁.uniq ⟨_, _⟩ rintro ⟨j⟩ rw [assoc] dsimp only [Discrete.natTrans_app] rw [← w ⟨j.succ⟩] dsimp only [extendFan_π_app] rw [Fin.cases_succ] section variable [HasBinaryProducts C] [HasTerminal C] /-- If `C` has a terminal object and binary products, then it has a product for objects indexed by `Fin n`. This is a helper lemma for `hasFiniteProductsOfHasBinaryAndTerminal`, which is more general than this. -/ private theorem hasProduct_fin : ∀ (n : ℕ) (f : Fin n → C), HasProduct f | 0 => fun _ => letI : HasLimitsOfShape (Discrete (Fin 0)) C := hasLimitsOfShape_of_equivalence (Discrete.equivalence.{0} finZeroEquiv'.symm) inferInstance | n + 1 => fun f => haveI := hasProduct_fin n HasLimit.mk ⟨_, extendFanIsLimit f (limit.isLimit _) (limit.isLimit _)⟩ /-- If `C` has a terminal object and binary products, then it has finite products. -/ theorem hasFiniteProducts_of_has_binary_and_terminal : HasFiniteProducts C := ⟨fun n => ⟨fun K => by let that : (Discrete.functor fun n => K.obj ⟨n⟩) ≅ K := Discrete.natIso fun ⟨_⟩ => Iso.refl _ rw [← hasLimit_iff_of_iso that] apply hasProduct_fin⟩⟩ end section Preserves variable (F : C ⥤ D) variable [PreservesLimitsOfShape (Discrete WalkingPair) F] variable [PreservesLimitsOfShape (Discrete.{0} PEmpty) F] variable [HasFiniteProducts.{v} C] /-- If `F` preserves the terminal object and binary products, then it preserves products indexed by `Fin n` for any `n`. -/ lemma preservesFinOfPreservesBinaryAndTerminal : ∀ (n : ℕ) (f : Fin n → C), PreservesLimit (Discrete.functor f) F | 0 => fun f => by letI : PreservesLimitsOfShape (Discrete (Fin 0)) F := preservesLimitsOfShape_of_equiv.{0, 0} (Discrete.equivalence finZeroEquiv'.symm) _ infer_instance | n + 1 => by haveI := preservesFinOfPreservesBinaryAndTerminal n intro f apply preservesLimit_of_preserves_limit_cone (extendFanIsLimit f (limit.isLimit _) (limit.isLimit _)) _ apply (isLimitMapConeFanMkEquiv _ _ _).symm _ let this := extendFanIsLimit (fun i => F.obj (f i)) (isLimitOfHasProductOfPreservesLimit F _) (isLimitOfHasBinaryProductOfPreservesLimit F _ _) refine IsLimit.ofIsoLimit this ?_ apply Cones.ext _ _ · apply Iso.refl _ rintro ⟨j⟩ refine Fin.inductionOn j ?_ ?_ · apply (Category.id_comp _).symm · rintro i _ dsimp [extendFan_π_app, Iso.refl_hom, Fan.mk_π_app] change F.map _ ≫ _ = 𝟙 _ ≫ _ simp only [id_comp, ← F.map_comp] rfl /-- If `F` preserves the terminal object and binary products then it preserves finite products. -/ lemma Limits.PreservesFiniteProducts.of_preserves_binary_and_terminal : PreservesFiniteProducts F where preserves n := by refine ⟨fun {K} ↦ ?_⟩ let that : (Discrete.functor fun n => K.obj ⟨n⟩) ≅ K := Discrete.natIso fun ⟨i⟩ => Iso.refl _ haveI := preservesFinOfPreservesBinaryAndTerminal F n fun n => K.obj ⟨n⟩ apply preservesLimit_of_iso_diagram F that @[deprecated (since := "2025-04-20")] alias preservesFiniteProducts_of_preserves_binary_and_terminal := PreservesFiniteProducts.of_preserves_binary_and_terminal @[deprecated PreservesFiniteProducts.of_preserves_binary_and_terminal (since := "2025-04-22")] lemma preservesShape_fin_of_preserves_binary_and_terminal (n : ℕ) : PreservesLimitsOfShape (Discrete (Fin n)) F := have : PreservesFiniteProducts F := .of_preserves_binary_and_terminal _; inferInstance end Preserves /-- Given `n+1` objects of `C`, a cofan for the last `n` with point `c₁.pt` and a binary cofan on `c₁.X` and `f 0`, we can build a cofan for all `n+1`. In `extendCofanIsColimit` we show that if the two given cofans are colimits, then this cofan is also a colimit. -/ @[simps!] def extendCofan {n : ℕ} {f : Fin (n + 1) → C} (c₁ : Cofan fun i : Fin n => f i.succ) (c₂ : BinaryCofan (f 0) c₁.pt) : Cofan f := Cofan.mk c₂.pt (by refine Fin.cases ?_ ?_ · apply c₂.inl · intro i apply c₁.ι.app ⟨i⟩ ≫ c₂.inr) /-- Show that if the two given cofans in `extendCofan` are colimits, then the constructed cofan is also a colimit. -/ def extendCofanIsColimit {n : ℕ} (f : Fin (n + 1) → C) {c₁ : Cofan fun i : Fin n => f i.succ} {c₂ : BinaryCofan (f 0) c₁.pt} (t₁ : IsColimit c₁) (t₂ : IsColimit c₂) : IsColimit (extendCofan c₁ c₂) where desc s := by apply (BinaryCofan.IsColimit.desc' t₂ (s.ι.app ⟨0⟩) _).1 apply t₁.desc ⟨_, Discrete.natTrans fun i => s.ι.app ⟨i.as.succ⟩⟩ fac s := by rintro ⟨j⟩ refine Fin.inductionOn j ?_ ?_ · apply (BinaryCofan.IsColimit.desc' t₂ _ _).2.1 · rintro i - dsimp only [extendCofan_ι_app] rw [Fin.cases_succ, assoc, (BinaryCofan.IsColimit.desc' t₂ _ _).2.2, t₁.fac] rfl uniq s m w := by apply BinaryCofan.IsColimit.hom_ext t₂ · rw [(BinaryCofan.IsColimit.desc' t₂ _ _).2.1] apply w ⟨0⟩ · rw [(BinaryCofan.IsColimit.desc' t₂ _ _).2.2] apply t₁.uniq ⟨_, _⟩ rintro ⟨j⟩ dsimp only [Discrete.natTrans_app] rw [← w ⟨j.succ⟩] dsimp only [extendCofan_ι_app] rw [Fin.cases_succ, assoc] section variable [HasBinaryCoproducts C] [HasInitial C] /-- If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by `Fin n`. This is a helper lemma for `hasCofiniteProductsOfHasBinaryAndTerminal`, which is more general than this. -/ private theorem hasCoproduct_fin : ∀ (n : ℕ) (f : Fin n → C), HasCoproduct f | 0 => fun _ => letI : HasColimitsOfShape (Discrete (Fin 0)) C := hasColimitsOfShape_of_equivalence (Discrete.equivalence.{0} finZeroEquiv'.symm) inferInstance | n + 1 => fun f => haveI := hasCoproduct_fin n HasColimit.mk ⟨_, extendCofanIsColimit f (colimit.isColimit _) (colimit.isColimit _)⟩ /-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/ theorem hasFiniteCoproducts_of_has_binary_and_initial : HasFiniteCoproducts C := ⟨fun n => ⟨fun K => by let that : K ≅ Discrete.functor fun n => K.obj ⟨n⟩ := Discrete.natIso fun ⟨_⟩ => Iso.refl _ rw [hasColimit_iff_of_iso that] apply hasCoproduct_fin⟩⟩ end section Preserves variable (F : C ⥤ D) variable [PreservesColimitsOfShape (Discrete WalkingPair) F] variable [PreservesColimitsOfShape (Discrete.{0} PEmpty) F] variable [HasFiniteCoproducts.{v} C] /-- If `F` preserves the initial object and binary coproducts, then it preserves products indexed by `Fin n` for any `n`. -/ lemma preserves_fin_of_preserves_binary_and_initial : ∀ (n : ℕ) (f : Fin n → C), PreservesColimit (Discrete.functor f) F | 0 => fun f => by letI : PreservesColimitsOfShape (Discrete (Fin 0)) F := preservesColimitsOfShape_of_equiv.{0, 0} (Discrete.equivalence finZeroEquiv'.symm) _ infer_instance | n + 1 => by haveI := preserves_fin_of_preserves_binary_and_initial n intro f apply preservesColimit_of_preserves_colimit_cocone (extendCofanIsColimit f (colimit.isColimit _) (colimit.isColimit _)) _ apply (isColimitMapCoconeCofanMkEquiv _ _ _).symm _ let this := extendCofanIsColimit (fun i => F.obj (f i)) (isColimitOfHasCoproductOfPreservesColimit F _) (isColimitOfHasBinaryCoproductOfPreservesColimit F _ _) refine IsColimit.ofIsoColimit this ?_ apply Cocones.ext _ _ · apply Iso.refl _ rintro ⟨j⟩ refine Fin.inductionOn j ?_ ?_ · apply Category.comp_id · rintro i _ dsimp [extendCofan_ι_app, Iso.refl_hom, Cofan.mk_ι_app] rw [comp_id, ← F.map_comp] /-- If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape `Discrete (Fin n)`. -/ lemma preservesShape_fin_of_preserves_binary_and_initial (n : ℕ) : PreservesColimitsOfShape (Discrete (Fin n)) F where preservesColimit {K} := by let that : (Discrete.functor fun n => K.obj ⟨n⟩) ≅ K := Discrete.natIso fun ⟨i⟩ => Iso.refl _ haveI := preserves_fin_of_preserves_binary_and_initial F n fun n => K.obj ⟨n⟩ apply preservesColimit_of_iso_diagram F that /-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/ lemma preservesFiniteCoproductsOfPreservesBinaryAndInitial (J : Type*) [Finite J] : PreservesColimitsOfShape (Discrete J) F := let ⟨n, ⟨e⟩⟩ := Finite.exists_equiv_fin J have := preservesShape_fin_of_preserves_binary_and_initial F n preservesColimitsOfShape_of_equiv (Discrete.equivalence e).symm _ end Preserves end CategoryTheory
Rat.lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Algebra.Order.Ring.Unbundled.Rat /-! # The rational numbers form a linear ordered field This file constructs the order on `ℚ` and proves that `ℚ` is a discrete, linearly ordered commutative ring. `ℚ` is in fact a linearly ordered field, but this fact is located in `Data.Rat.Field` instead of here because we need the order on `ℚ` to define `ℚ≥0`, which we itself need to define `Field`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, order, ordering -/ assert_not_exists Field Finset Set.Icc GaloisConnection namespace Rat instance instIsOrderedAddMonoid : IsOrderedAddMonoid ℚ where add_le_add_left := fun _ _ ab _ => Rat.add_le_add_left.2 ab instance instZeroLEOneClass : ZeroLEOneClass ℚ where zero_le_one := by decide instance instIsStrictOrderedRing : IsStrictOrderedRing ℚ := .of_mul_pos fun _ _ ha hb ↦ (Rat.mul_nonneg ha.le hb.le).lt_of_ne' (mul_ne_zero ha.ne' hb.ne') end Rat
OpenNhds.lean
/- Copyright (c) 2019 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.Topology.Category.TopCat.Opens import Mathlib.Data.Set.Subsingleton /-! # The category of open neighborhoods of a point Given an object `X` of the category `TopCat` of topological spaces and a point `x : X`, this file builds the type `OpenNhds x` of open neighborhoods of `x` in `X` and endows it with the partial order given by inclusion and the corresponding category structure (as a full subcategory of the poset category `Set X`). This is used in `Topology.Sheaves.Stalks` to build the stalk of a sheaf at `x` as a limit over `OpenNhds x`. ## Main declarations Besides `OpenNhds`, the main constructions here are: * `inclusion (x : X)`: the obvious functor `OpenNhds x ⥤ Opens X` * `functorNhds`: An open map `f : X ⟶ Y` induces a functor `OpenNhds x ⥤ OpenNhds (f x)` * `adjunctionNhds`: An open map `f : X ⟶ Y` induces an adjunction between `OpenNhds x` and `OpenNhds (f x)`. -/ open CategoryTheory TopologicalSpace Opposite Topology universe u variable {X Y : TopCat.{u}} (f : X ⟶ Y) namespace TopologicalSpace /-- The type of open neighbourhoods of a point `x` in a (bundled) topological space. -/ def OpenNhds (x : X) := ObjectProperty.FullSubcategory fun U : Opens X => x ∈ U namespace OpenNhds variable {x : X} {U V W : OpenNhds x} instance partialOrder (x : X) : PartialOrder (OpenNhds x) where le U V := U.1 ≤ V.1 le_refl _ := le_rfl le_trans _ _ _ := le_trans le_antisymm _ _ i j := ObjectProperty.FullSubcategory.ext <| le_antisymm i j instance (x : X) : Lattice (OpenNhds x) := { OpenNhds.partialOrder x with inf := fun U V => ⟨U.1 ⊓ V.1, ⟨U.2, V.2⟩⟩ le_inf := fun U V W => @le_inf _ _ U.1.1 V.1.1 W.1.1 inf_le_left := fun U V => @inf_le_left _ _ U.1.1 V.1.1 inf_le_right := fun U V => @inf_le_right _ _ U.1.1 V.1.1 sup := fun U V => ⟨U.1 ⊔ V.1, Set.mem_union_left V.1.1 U.2⟩ sup_le := fun U V W => @sup_le _ _ U.1.1 V.1.1 W.1.1 le_sup_left := fun U V => @le_sup_left _ _ U.1.1 V.1.1 le_sup_right := fun U V => @le_sup_right _ _ U.1.1 V.1.1 } instance (x : X) : OrderTop (OpenNhds x) where top := ⟨⊤, trivial⟩ le_top _ := by dsimp [LE.le]; exact le_top instance (x : X) : Inhabited (OpenNhds x) := ⟨⊤⟩ instance openNhdsCategory (x : X) : Category.{u} (OpenNhds x) := inferInstance instance opensNhds.instFunLike : FunLike (U ⟶ V) U.1 V.1 where coe f := Set.inclusion f.le coe_injective' := by rintro ⟨⟨_⟩⟩ _ _; congr! @[simp] lemma apply_mk (f : U ⟶ V) (y : X) (hy) : f ⟨y, hy⟩ = ⟨y, f.le hy⟩ := rfl @[simp] lemma val_apply (f : U ⟶ V) (y : U.1) : (f y : X) = y := rfl @[simp, norm_cast] lemma coe_id (f : U ⟶ U) : ⇑f = id := rfl lemma id_apply (f : U ⟶ U) (y : U.1) : f y = y := rfl @[simp] lemma comp_apply (f : U ⟶ V) (g : V ⟶ W) (x : U.1) : (f ≫ g) x = g (f x) := rfl /-- The inclusion `U ⊓ V ⟶ U` as a morphism in the category of open sets. -/ def infLELeft {x : X} (U V : OpenNhds x) : U ⊓ V ⟶ U := homOfLE inf_le_left /-- The inclusion `U ⊓ V ⟶ V` as a morphism in the category of open sets. -/ def infLERight {x : X} (U V : OpenNhds x) : U ⊓ V ⟶ V := homOfLE inf_le_right /-- The inclusion functor from open neighbourhoods of `x` to open sets in the ambient topological space. -/ def inclusion (x : X) : OpenNhds x ⥤ Opens X := ObjectProperty.ι _ @[simp] theorem inclusion_obj (x : X) (U) (p) : (inclusion x).obj ⟨U, p⟩ = U := rfl theorem isOpenEmbedding {x : X} (U : OpenNhds x) : IsOpenEmbedding U.1.inclusion' := U.1.isOpenEmbedding /-- The preimage functor from neighborhoods of `f x` to neighborhoods of `x`. -/ def map (x : X) : OpenNhds (f x) ⥤ OpenNhds x where obj U := ⟨(Opens.map f).obj U.1, U.2⟩ map i := (Opens.map f).map i @[simp] theorem map_obj (x : X) (U) (q) : (map f x).obj ⟨U, q⟩ = ⟨(Opens.map f).obj U, q⟩ := rfl @[simp] theorem map_id_obj (x : X) (U) : (map (𝟙 X) x).obj U = U := rfl @[simp] theorem map_id_obj' (x : X) (U) (p) (q) : (map (𝟙 X) x).obj ⟨⟨U, p⟩, q⟩ = ⟨⟨U, p⟩, q⟩ := rfl @[simp] theorem map_id_obj_unop (x : X) (U : (OpenNhds x)ᵒᵖ) : (map (𝟙 X) x).obj (unop U) = unop U := by simp @[simp] theorem op_map_id_obj (x : X) (U : (OpenNhds x)ᵒᵖ) : (map (𝟙 X) x).op.obj U = U := by simp /-- `Opens.map f` and `OpenNhds.map f` form a commuting square (up to natural isomorphism) with the inclusion functors into `Opens X`. -/ @[simps! hom_app inv_app] def inclusionMapIso (x : X) : inclusion (f x) ⋙ Opens.map f ≅ map f x ⋙ inclusion x := NatIso.ofComponents fun U => { hom := 𝟙 _, inv := 𝟙 _ } @[simp] theorem inclusionMapIso_hom (x : X) : (inclusionMapIso f x).hom = 𝟙 _ := rfl @[simp] theorem inclusionMapIso_inv (x : X) : (inclusionMapIso f x).inv = 𝟙 _ := rfl end OpenNhds end TopologicalSpace namespace IsOpenMap open TopologicalSpace variable {f} /-- An open map `f : X ⟶ Y` induces a functor `OpenNhds x ⥤ OpenNhds (f x)`. -/ @[simps] def functorNhds (h : IsOpenMap f) (x : X) : OpenNhds x ⥤ OpenNhds (f x) where obj U := ⟨h.functor.obj U.1, ⟨x, U.2, rfl⟩⟩ map i := h.functor.map i /-- An open map `f : X ⟶ Y` induces an adjunction between `OpenNhds x` and `OpenNhds (f x)`. -/ def adjunctionNhds (h : IsOpenMap f) (x : X) : IsOpenMap.functorNhds h x ⊣ OpenNhds.map f x where unit := { app := fun _ => homOfLE fun x hxU => ⟨x, hxU, rfl⟩ } counit := { app := fun _ => homOfLE fun _ ⟨_, hfxV, hxy⟩ => hxy ▸ hfxV } end IsOpenMap namespace Topology.IsInducing open TopologicalSpace variable {f} /-- An inducing map `f : X ⟶ Y` induces a functor `open_nhds x ⥤ open_nhds (f x)`. -/ @[simps] def functorNhds (h : IsInducing f) (x : X) : OpenNhds x ⥤ OpenNhds (f x) where obj U := ⟨h.functor.obj U.1, (h.mem_functorObj_iff U.1).mpr U.2⟩ map := h.functor.map /-- An inducing map `f : X ⟶ Y` induces an adjunction between `open_nhds x` and `open_nhds (f x)`. -/ def adjunctionNhds (h : IsInducing f) (x : X) : OpenNhds.map f x ⊣ h.functorNhds x where unit := { app := fun U => homOfLE (h.adjunction.unit.app U.1).le } counit := { app := fun U => homOfLE (h.adjunction.counit.app U.1).le } end Topology.IsInducing
Bases.lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import Mathlib.Algebra.Algebra.Basic import Mathlib.Algebra.Module.Submodule.Pointwise import Mathlib.Topology.Algebra.FilterBasis import Mathlib.Topology.Algebra.Nonarchimedean.Basic /-! # Neighborhood bases for non-archimedean rings and modules This files contains special families of filter bases on rings and modules that give rise to non-archimedean topologies. The main definition is `RingSubgroupsBasis` which is a predicate on a family of additive subgroups of a ring. The predicate ensures there is a topology `RingSubgroupsBasis.topology` which is compatible with a ring structure and admits the given family as a basis of neighborhoods of zero. In particular the given subgroups become open subgroups (bundled in `RingSubgroupsBasis.openAddSubgroup`) and we get a non-archimedean topological ring (`RingSubgroupsBasis.nonarchimedean`). A special case of this construction is given by `SubmodulesBasis` where the subgroups are sub-modules in a commutative algebra. This important example gives rise to the adic topology (studied in its own file). -/ open Set Filter Function Lattice open Topology Filter Pointwise /-- A family of additive subgroups on a ring `A` is a subgroups basis if it satisfies some axioms ensuring there is a topology on `A` which is compatible with the ring structure and admits this family as a basis of neighborhoods of zero. -/ structure RingSubgroupsBasis {A ι : Type*} [Ring A] (B : ι → AddSubgroup A) : Prop where /-- Condition for `B` to be a filter basis on `A`. -/ inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j /-- For each set `B` in the submodule basis on `A`, there is another basis element `B'` such that the set-theoretic product `B' * B'` is in `B`. -/ mul : ∀ i, ∃ j, (B j : Set A) * B j ⊆ B i /-- For any element `x : A` and any set `B` in the submodule basis on `A`, there is another basis element `B'` such that `B' * x` is in `B`. -/ leftMul : ∀ x : A, ∀ i, ∃ j, (B j : Set A) ⊆ (x * ·) ⁻¹' B i /-- For any element `x : A` and any set `B` in the submodule basis on `A`, there is another basis element `B'` such that `x * B'` is in `B`. -/ rightMul : ∀ x : A, ∀ i, ∃ j, (B j : Set A) ⊆ (· * x) ⁻¹' B i namespace RingSubgroupsBasis variable {A ι : Type*} [Ring A] theorem of_comm {A ι : Type*} [CommRing A] (B : ι → AddSubgroup A) (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (mul : ∀ i, ∃ j, (B j : Set A) * B j ⊆ B i) (leftMul : ∀ x : A, ∀ i, ∃ j, (B j : Set A) ⊆ (fun y : A => x * y) ⁻¹' B i) : RingSubgroupsBasis B := { inter mul leftMul rightMul := fun x i ↦ (leftMul x i).imp fun j hj ↦ by simpa only [mul_comm] using hj } /-- Every subgroups basis on a ring leads to a ring filter basis. -/ def toRingFilterBasis [Nonempty ι] {B : ι → AddSubgroup A} (hB : RingSubgroupsBasis B) : RingFilterBasis A where sets := { U | ∃ i, U = B i } nonempty := by inhabit ι exact ⟨B default, default, rfl⟩ inter_sets := by rintro _ _ ⟨i, rfl⟩ ⟨j, rfl⟩ obtain ⟨k, hk⟩ := hB.inter i j use B k constructor · use k · exact hk zero' := by rintro _ ⟨i, rfl⟩ exact (B i).zero_mem add' := by rintro _ ⟨i, rfl⟩ use B i constructor · use i · rintro x ⟨y, y_in, z, z_in, rfl⟩ exact (B i).add_mem y_in z_in neg' := by rintro _ ⟨i, rfl⟩ use B i constructor · use i · intro x x_in exact (B i).neg_mem x_in conj' := by rintro x₀ _ ⟨i, rfl⟩ use B i constructor · use i · simp mul' := by rintro _ ⟨i, rfl⟩ obtain ⟨k, hk⟩ := hB.mul i use B k constructor · use k · exact hk mul_left' := by rintro x₀ _ ⟨i, rfl⟩ obtain ⟨k, hk⟩ := hB.leftMul x₀ i use B k constructor · use k · exact hk mul_right' := by rintro x₀ _ ⟨i, rfl⟩ obtain ⟨k, hk⟩ := hB.rightMul x₀ i use B k constructor · use k · exact hk variable [Nonempty ι] {B : ι → AddSubgroup A} (hB : RingSubgroupsBasis B) theorem mem_addGroupFilterBasis_iff {V : Set A} : V ∈ hB.toRingFilterBasis.toAddGroupFilterBasis ↔ ∃ i, V = B i := Iff.rfl theorem mem_addGroupFilterBasis (i) : (B i : Set A) ∈ hB.toRingFilterBasis.toAddGroupFilterBasis := ⟨i, rfl⟩ /-- The topology defined from a subgroups basis, admitting the given subgroups as a basis of neighborhoods of zero. -/ def topology : TopologicalSpace A := hB.toRingFilterBasis.toAddGroupFilterBasis.topology theorem hasBasis_nhds_zero : HasBasis (@nhds A hB.topology 0) (fun _ => True) fun i => B i := ⟨by intro s rw [hB.toRingFilterBasis.toAddGroupFilterBasis.nhds_zero_hasBasis.mem_iff] constructor · rintro ⟨-, ⟨i, rfl⟩, hi⟩ exact ⟨i, trivial, hi⟩ · rintro ⟨i, -, hi⟩ exact ⟨B i, ⟨i, rfl⟩, hi⟩⟩ theorem hasBasis_nhds (a : A) : HasBasis (@nhds A hB.topology a) (fun _ => True) fun i => { b | b - a ∈ B i } := ⟨by intro s rw [(hB.toRingFilterBasis.toAddGroupFilterBasis.nhds_hasBasis a).mem_iff] simp only [true_and] constructor · rintro ⟨-, ⟨i, rfl⟩, hi⟩ use i suffices h : { b : A | b - a ∈ B i } = (fun y => a + y) '' ↑(B i) by rw [h] assumption simp only [image_add_left, neg_add_eq_sub] ext b simp · rintro ⟨i, hi⟩ use B i constructor · use i · rw [image_subset_iff] rintro b b_in apply hi simpa using b_in⟩ /-- Given a subgroups basis, the basis elements as open additive subgroups in the associated topology. -/ def openAddSubgroup (i : ι) : @OpenAddSubgroup A _ hB.topology := let _ := hB.topology { B i with isOpen' := by rw [isOpen_iff_mem_nhds] intro a a_in rw [(hB.hasBasis_nhds a).mem_iff] use i, trivial rintro b b_in simpa using (B i).add_mem a_in b_in } -- see Note [nonarchimedean non instances] theorem nonarchimedean : @NonarchimedeanRing A _ hB.topology := by letI := hB.topology constructor intro U hU obtain ⟨i, -, hi : (B i : Set A) ⊆ U⟩ := hB.hasBasis_nhds_zero.mem_iff.mp hU exact ⟨hB.openAddSubgroup i, hi⟩ end RingSubgroupsBasis variable {ι R A : Type*} [CommRing R] [CommRing A] [Algebra R A] /-- A family of submodules in a commutative `R`-algebra `A` is a submodules basis if it satisfies some axioms ensuring there is a topology on `A` which is compatible with the ring structure and admits this family as a basis of neighborhoods of zero. -/ structure SubmodulesRingBasis (B : ι → Submodule R A) : Prop where /-- Condition for `B` to be a filter basis on `A`. -/ inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j /-- For any element `a : A` and any set `B` in the submodule basis on `A`, there is another basis element `B'` such that `a • B'` is in `B`. -/ leftMul : ∀ (a : A) (i), ∃ j, a • B j ≤ B i /-- For each set `B` in the submodule basis on `A`, there is another basis element `B'` such that the set-theoretic product `B' * B'` is in `B`. -/ mul : ∀ i, ∃ j, (B j : Set A) * B j ⊆ B i namespace SubmodulesRingBasis variable {B : ι → Submodule R A} (hB : SubmodulesRingBasis B) theorem toRing_subgroups_basis (hB : SubmodulesRingBasis B) : RingSubgroupsBasis fun i => (B i).toAddSubgroup := by apply RingSubgroupsBasis.of_comm (fun i => (B i).toAddSubgroup) hB.inter hB.mul intro a i rcases hB.leftMul a i with ⟨j, hj⟩ use j rintro b (b_in : b ∈ B j) exact hj ⟨b, b_in, rfl⟩ /-- The topology associated to a basis of submodules in an algebra. -/ def topology [Nonempty ι] (hB : SubmodulesRingBasis B) : TopologicalSpace A := hB.toRing_subgroups_basis.topology end SubmodulesRingBasis variable {M : Type*} [AddCommGroup M] [Module R M] /-- A family of submodules in an `R`-module `M` is a submodules basis if it satisfies some axioms ensuring there is a topology on `M` which is compatible with the module structure and admits this family as a basis of neighborhoods of zero. -/ structure SubmodulesBasis [TopologicalSpace R] (B : ι → Submodule R M) : Prop where /-- Condition for `B` to be a filter basis on `M`. -/ inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j /-- For any element `m : M` and any set `B` in the basis, `a • m` lies in `B` for all `a` sufficiently close to `0`. -/ smul : ∀ (m : M) (i : ι), ∀ᶠ a in 𝓝 (0 : R), a • m ∈ B i namespace SubmodulesBasis variable [TopologicalSpace R] [Nonempty ι] {B : ι → Submodule R M} (hB : SubmodulesBasis B) /-- The image of a submodules basis is a module filter basis. -/ def toModuleFilterBasis : ModuleFilterBasis R M where sets := { U | ∃ i, U = B i } nonempty := by inhabit ι exact ⟨B default, default, rfl⟩ inter_sets := by rintro _ _ ⟨i, rfl⟩ ⟨j, rfl⟩ obtain ⟨k, hk⟩ := hB.inter i j use B k constructor · use k · exact hk zero' := by rintro _ ⟨i, rfl⟩ exact (B i).zero_mem add' := by rintro _ ⟨i, rfl⟩ use B i constructor · use i · rintro x ⟨y, y_in, z, z_in, rfl⟩ exact (B i).add_mem y_in z_in neg' := by rintro _ ⟨i, rfl⟩ use B i constructor · use i · intro x x_in exact (B i).neg_mem x_in conj' := by rintro x₀ _ ⟨i, rfl⟩ use B i constructor · use i · simp smul' := by rintro _ ⟨i, rfl⟩ use univ constructor · exact univ_mem · use B i constructor · use i · rintro _ ⟨a, -, m, hm, rfl⟩ exact (B i).smul_mem _ hm smul_left' := by rintro x₀ _ ⟨i, rfl⟩ use B i constructor · use i · intro m exact (B i).smul_mem _ smul_right' := by rintro m₀ _ ⟨i, rfl⟩ exact hB.smul m₀ i /-- The topology associated to a basis of submodules in a module. -/ def topology : TopologicalSpace M := hB.toModuleFilterBasis.toAddGroupFilterBasis.topology /-- Given a submodules basis, the basis elements as open additive subgroups in the associated topology. -/ def openAddSubgroup (i : ι) : @OpenAddSubgroup M _ hB.topology := let _ := hB.topology { (B i).toAddSubgroup with isOpen' := by letI := hB.topology rw [isOpen_iff_mem_nhds] intro a a_in rw [(hB.toModuleFilterBasis.toAddGroupFilterBasis.nhds_hasBasis a).mem_iff] use B i constructor · use i · rintro - ⟨b, b_in, rfl⟩ exact (B i).add_mem a_in b_in } -- see Note [nonarchimedean non instances] theorem nonarchimedean (hB : SubmodulesBasis B) : @NonarchimedeanAddGroup M _ hB.topology := by letI := hB.topology constructor intro U hU obtain ⟨-, ⟨i, rfl⟩, hi : (B i : Set M) ⊆ U⟩ := hB.toModuleFilterBasis.toAddGroupFilterBasis.nhds_zero_hasBasis.mem_iff.mp hU exact ⟨hB.openAddSubgroup i, hi⟩ library_note "nonarchimedean non instances"/-- The non archimedean subgroup basis lemmas cannot be instances because some instances (such as `MeasureTheory.AEEqFun.instAddMonoid` or `IsTopologicalAddGroup.toContinuousAdd`) cause the search for `@IsTopologicalAddGroup β ?m1 ?m2`, i.e. a search for a topological group where the topology/group structure are unknown. -/ end SubmodulesBasis section /- In this section, we check that in an `R`-algebra `A` over a ring equipped with a topology, a basis of `R`-submodules which is compatible with the topology on `R` is also a submodule basis in the sense of `R`-modules (forgetting about the ring structure on `A`) and those two points of view definitionaly gives the same topology on `A`. -/ variable [TopologicalSpace R] {B : ι → Submodule R A} (hB : SubmodulesRingBasis B) (hsmul : ∀ (m : A) (i : ι), ∀ᶠ a : R in 𝓝 0, a • m ∈ B i) include hB hsmul theorem SubmodulesRingBasis.toSubmodulesBasis : SubmodulesBasis B := { inter := hB.inter smul := hsmul } example [Nonempty ι] : hB.topology = (hB.toSubmodulesBasis hsmul).topology := rfl end /-- Given a ring filter basis on a commutative ring `R`, define a compatibility condition on a family of submodules of an `R`-module `M`. This compatibility condition allows to get a topological module structure. -/ structure RingFilterBasis.SubmodulesBasis (BR : RingFilterBasis R) (B : ι → Submodule R M) : Prop where /-- Condition for `B` to be a filter basis on `M`. -/ inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j /-- For any element `m : M` and any set `B i` in the submodule basis on `M`, there is a `U` in the ring filter basis on `R` such that `U * m` is in `B i`. -/ smul : ∀ (m : M) (i : ι), ∃ U ∈ BR, U ⊆ (· • m) ⁻¹' B i theorem RingFilterBasis.submodulesBasisIsBasis (BR : RingFilterBasis R) {B : ι → Submodule R M} (hB : BR.SubmodulesBasis B) : @_root_.SubmodulesBasis ι R _ M _ _ BR.topology B := let _ := BR.topology { inter := hB.inter smul := by letI := BR.topology intro m i rcases hB.smul m i with ⟨V, V_in, hV⟩ exact mem_of_superset (BR.toAddGroupFilterBasis.mem_nhds_zero V_in) hV } /-- The module filter basis associated to a ring filter basis and a compatible submodule basis. This allows to build a topological module structure compatible with the given module structure and the topology associated to the given ring filter basis. -/ def RingFilterBasis.moduleFilterBasis [Nonempty ι] (BR : RingFilterBasis R) {B : ι → Submodule R M} (hB : BR.SubmodulesBasis B) : @ModuleFilterBasis R M _ BR.topology _ _ := @SubmodulesBasis.toModuleFilterBasis ι R _ M _ _ BR.topology _ _ (BR.submodulesBasisIsBasis hB)
Imo1962Q1.lean
/- Copyright (c) 2020 Kevin Lacker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Lacker -/ import Mathlib.Data.Nat.Digits.Lemmas /-! # IMO 1962 Q1 Find the smallest natural number $n$ which has the following properties: (a) Its decimal representation has 6 as the last digit. (b) If the last digit 6 is erased and placed in front of the remaining digits, the resulting number is four times as large as the original number $n$. Since Lean does not explicitly express problems of the form "find the smallest number satisfying X", we define the problem as a predicate, and then prove a particular number is the smallest member of a set satisfying it. -/ namespace Imo1962Q1 open Nat def ProblemPredicate (n : ℕ) : Prop := (digits 10 n).headI = 6 ∧ ofDigits 10 ((digits 10 n).tail.concat 6) = 4 * n /-! First, it's inconvenient to work with digits, so let's simplify them out of the problem. -/ abbrev ProblemPredicate' (c n : ℕ) : Prop := n = 10 * c + 6 ∧ 6 * 10 ^ (digits 10 c).length + c = 4 * n lemma without_digits {n : ℕ} (hn : ProblemPredicate n) : ∃ c : ℕ, ProblemPredicate' c n := by use n / 10 rcases n with - | n · have hpp : ¬ProblemPredicate 0 := by simp [ProblemPredicate] contradiction · rw [ProblemPredicate, digits_def' (by decide : 2 ≤ 10) n.succ_pos, List.headI, List.tail_cons, List.concat_eq_append] at hn constructor · rw [← hn.left, div_add_mod (n + 1) 10] · rw [← hn.right, ofDigits_append, ofDigits_digits, ofDigits_singleton, add_comm, mul_comm] /-! Now we can eliminate possibilities for `(digits 10 c).length` until we get to the one that works. -/ lemma case_0_digits {c n : ℕ} (hc : (digits 10 c).length = 0) : ¬ProblemPredicate' c n := by intro hpp have hpow : 6 * 10 ^ 0 = 6 * 10 ^ (digits 10 c).length := by rw [hc] omega lemma case_1_digits {c n : ℕ} (hc : (digits 10 c).length = 1) : ¬ProblemPredicate' c n := by intro hpp have hpow : 6 * 10 ^ 1 = 6 * 10 ^ (digits 10 c).length := by rw [hc] omega lemma case_2_digits {c n : ℕ} (hc : (digits 10 c).length = 2) : ¬ProblemPredicate' c n := by intro hpp have hpow : 6 * 10 ^ 2 = 6 * 10 ^ (digits 10 c).length := by rw [hc] omega lemma case_3_digits {c n : ℕ} (hc : (digits 10 c).length = 3) : ¬ProblemPredicate' c n := by intro hpp have hpow : 6 * 10 ^ 3 = 6 * 10 ^ (digits 10 c).length := by rw [hc] omega lemma case_4_digits {c n : ℕ} (hc : (digits 10 c).length = 4) : ¬ProblemPredicate' c n := by intro hpp have hpow : 6 * 10 ^ 4 = 6 * 10 ^ (digits 10 c).length := by rw [hc] omega /-- Putting this inline causes a deep recursion error, so we separate it out. -/ private lemma helper_5_digits {c : ℤ} (hc : 6 * 10 ^ 5 + c = 4 * (10 * c + 6)) : c = 15384 := by omega lemma case_5_digits {c n : ℕ} (hc : (digits 10 c).length = 5) (hpp : ProblemPredicate' c n) : c = 15384 := by have hpow : 6 * 10 ^ 5 + c = 6 * 10 ^ (digits 10 c).length + c := by rw [hc] have hmul : 6 * 10 ^ 5 + c = 4 * (10 * c + 6) := by rw [hpow, hpp.right, hpp.left] zify at * exact helper_5_digits hmul /-- `linarith` fails on numbers this large, so this lemma spells out some of the arithmetic that normally would be automated. -/ lemma case_more_digits {c n : ℕ} (hc : (digits 10 c).length ≥ 6) (hpp : ProblemPredicate' c n) : n ≥ 153846 := by have hnz : c ≠ 0 := by intro hc0 have hcl : (digits 10 c).length = 0 := by simp [hc0] exact case_0_digits hcl hpp calc n ≥ 10 * c := le.intro hpp.left.symm _ ≥ 10 ^ (digits 10 c).length := base_pow_length_digits_le 10 c (by decide) hnz _ ≥ 10 ^ 6 := pow_right_mono₀ (by decide) hc _ ≥ 153846 := by simp /-! Now we combine these cases to show that 153846 is the smallest solution. -/ lemma satisfied_by_153846 : ProblemPredicate 153846 := by norm_num [ProblemPredicate] decide lemma no_smaller_solutions (n : ℕ) (hn : ProblemPredicate n) : n ≥ 153846 := by have ⟨c, hcn⟩ := without_digits hn cases lt_or_ge (digits 10 c).length 6 with | inl => interval_cases hc : (digits 10 c).length · exfalso; exact case_0_digits hc hcn · exfalso; exact case_1_digits hc hcn · exfalso; exact case_2_digits hc hcn · exfalso; exact case_3_digits hc hcn · exfalso; exact case_4_digits hc hcn · exact (case_5_digits hc hcn ▸ hcn.left).ge | inr hge => exact case_more_digits hge hcn end Imo1962Q1 open Imo1962Q1 theorem imo1962_q1 : IsLeast {n | ProblemPredicate n} 153846 := ⟨satisfied_by_153846, no_smaller_solutions⟩
LanguageMap.lean
/- Copyright (c) 2021 Aaron Anderson, Jesse Michael Han, Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jesse Michael Han, Floris van Doorn -/ import Mathlib.ModelTheory.Basic /-! # Language Maps Maps between first-order languages in the style of the [Flypitch project](https://flypitch.github.io/), as well as several important maps between structures. ## Main Definitions - A `FirstOrder.Language.LHom`, denoted `L →ᴸ L'`, is a map between languages, sending the symbols of one to symbols of the same kind and arity in the other. - A `FirstOrder.Language.LEquiv`, denoted `L ≃ᴸ L'`, is an invertible language homomorphism. - `FirstOrder.Language.withConstants` is defined so that if `M` is an `L.Structure` and `A : Set M`, `L.withConstants A`, denoted `L[[A]]`, is a language which adds constant symbols for elements of `A` to `L`. ## References For the Flypitch project: - [J. Han, F. van Doorn, *A formal proof of the independence of the continuum hypothesis*] [flypitch_cpp] - [J. Han, F. van Doorn, *A formalization of forcing and the unprovability of the continuum hypothesis*][flypitch_itp] -/ universe u v u' v' w w' namespace FirstOrder namespace Language open Structure Cardinal variable (L : Language.{u, v}) (L' : Language.{u', v'}) {M : Type w} [L.Structure M] /-- A language homomorphism maps the symbols of one language to symbols of another. -/ structure LHom where /-- The mapping of functions -/ onFunction : ∀ ⦃n⦄, L.Functions n → L'.Functions n := by exact fun {n} => isEmptyElim /-- The mapping of relations -/ onRelation : ∀ ⦃n⦄, L.Relations n → L'.Relations n :=by exact fun {n} => isEmptyElim @[inherit_doc FirstOrder.Language.LHom] infixl:10 " →ᴸ " => LHom -- \^L variable {L L'} namespace LHom variable (ϕ : L →ᴸ L') /-- Pulls a structure back along a language map. -/ def reduct (M : Type*) [L'.Structure M] : L.Structure M where funMap f xs := funMap (ϕ.onFunction f) xs RelMap r xs := RelMap (ϕ.onRelation r) xs /-- The identity language homomorphism. -/ @[simps] protected def id (L : Language) : L →ᴸ L := ⟨fun _n => id, fun _n => id⟩ instance : Inhabited (L →ᴸ L) := ⟨LHom.id L⟩ /-- The inclusion of the left factor into the sum of two languages. -/ @[simps] protected def sumInl : L →ᴸ L.sum L' := ⟨fun _n => Sum.inl, fun _n => Sum.inl⟩ /-- The inclusion of the right factor into the sum of two languages. -/ @[simps] protected def sumInr : L' →ᴸ L.sum L' := ⟨fun _n => Sum.inr, fun _n => Sum.inr⟩ variable (L L') /-- The inclusion of an empty language into any other language. -/ @[simps] protected def ofIsEmpty [L.IsAlgebraic] [L.IsRelational] : L →ᴸ L' where variable {L L'} {L'' : Language} @[ext] protected theorem funext {F G : L →ᴸ L'} (h_fun : F.onFunction = G.onFunction) (h_rel : F.onRelation = G.onRelation) : F = G := by obtain ⟨Ff, Fr⟩ := F obtain ⟨Gf, Gr⟩ := G simp only [mk.injEq] exact And.intro h_fun h_rel instance [L.IsAlgebraic] [L.IsRelational] : Unique (L →ᴸ L') := ⟨⟨LHom.ofIsEmpty L L'⟩, fun _ => LHom.funext (Subsingleton.elim _ _) (Subsingleton.elim _ _)⟩ /-- The composition of two language homomorphisms. -/ @[simps] def comp (g : L' →ᴸ L'') (f : L →ᴸ L') : L →ᴸ L'' := ⟨fun _n F => g.1 (f.1 F), fun _ R => g.2 (f.2 R)⟩ -- added ᴸ to avoid clash with function composition @[inherit_doc] local infixl:60 " ∘ᴸ " => LHom.comp @[simp] theorem id_comp (F : L →ᴸ L') : LHom.id L' ∘ᴸ F = F := by cases F rfl @[simp] theorem comp_id (F : L →ᴸ L') : F ∘ᴸ LHom.id L = F := by cases F rfl theorem comp_assoc {L3 : Language} (F : L'' →ᴸ L3) (G : L' →ᴸ L'') (H : L →ᴸ L') : F ∘ᴸ G ∘ᴸ H = F ∘ᴸ (G ∘ᴸ H) := rfl section SumElim variable (ψ : L'' →ᴸ L') /-- A language map defined on two factors of a sum. -/ @[simps] protected def sumElim : L.sum L'' →ᴸ L' where onFunction _n := Sum.elim (fun f => ϕ.onFunction f) fun f => ψ.onFunction f onRelation _n := Sum.elim (fun f => ϕ.onRelation f) fun f => ψ.onRelation f theorem sumElim_comp_inl (ψ : L'' →ᴸ L') : ϕ.sumElim ψ ∘ᴸ LHom.sumInl = ϕ := LHom.funext (funext fun _ => rfl) (funext fun _ => rfl) theorem sumElim_comp_inr (ψ : L'' →ᴸ L') : ϕ.sumElim ψ ∘ᴸ LHom.sumInr = ψ := LHom.funext (funext fun _ => rfl) (funext fun _ => rfl) theorem sumElim_inl_inr : LHom.sumInl.sumElim LHom.sumInr = LHom.id (L.sum L') := LHom.funext (funext fun _ => Sum.elim_inl_inr) (funext fun _ => Sum.elim_inl_inr) theorem comp_sumElim {L3 : Language} (θ : L' →ᴸ L3) : θ ∘ᴸ ϕ.sumElim ψ = (θ ∘ᴸ ϕ).sumElim (θ ∘ᴸ ψ) := LHom.funext (funext fun _n => Sum.comp_elim _ _ _) (funext fun _n => Sum.comp_elim _ _ _) end SumElim section SumMap variable {L₁ L₂ : Language} (ψ : L₁ →ᴸ L₂) /-- The map between two sum-languages induced by maps on the two factors. -/ @[simps] def sumMap : L.sum L₁ →ᴸ L'.sum L₂ where onFunction _n := Sum.map (fun f => ϕ.onFunction f) fun f => ψ.onFunction f onRelation _n := Sum.map (fun f => ϕ.onRelation f) fun f => ψ.onRelation f @[simp] theorem sumMap_comp_inl : ϕ.sumMap ψ ∘ᴸ LHom.sumInl = LHom.sumInl ∘ᴸ ϕ := LHom.funext (funext fun _ => rfl) (funext fun _ => rfl) @[simp] theorem sumMap_comp_inr : ϕ.sumMap ψ ∘ᴸ LHom.sumInr = LHom.sumInr ∘ᴸ ψ := LHom.funext (funext fun _ => rfl) (funext fun _ => rfl) end SumMap /-- A language homomorphism is injective when all the maps between symbol types are. -/ protected structure Injective : Prop where onFunction {n} : Function.Injective fun f : L.Functions n => onFunction ϕ f onRelation {n} : Function.Injective fun R : L.Relations n => onRelation ϕ R /-- Pulls an `L`-structure along a language map `ϕ : L →ᴸ L'`, and then expands it to an `L'`-structure arbitrarily. -/ noncomputable def defaultExpansion (ϕ : L →ᴸ L') [∀ (n) (f : L'.Functions n), Decidable (f ∈ Set.range fun f : L.Functions n => onFunction ϕ f)] [∀ (n) (r : L'.Relations n), Decidable (r ∈ Set.range fun r : L.Relations n => onRelation ϕ r)] (M : Type*) [Inhabited M] [L.Structure M] : L'.Structure M where funMap {n} f xs := if h' : f ∈ Set.range fun f : L.Functions n => onFunction ϕ f then funMap h'.choose xs else default RelMap {n} r xs := if h' : r ∈ Set.range fun r : L.Relations n => onRelation ϕ r then RelMap h'.choose xs else default /-- A language homomorphism is an expansion on a structure if it commutes with the interpretation of all symbols on that structure. -/ class IsExpansionOn (M : Type*) [L.Structure M] [L'.Structure M] : Prop where map_onFunction : ∀ {n} (f : L.Functions n) (x : Fin n → M), funMap (ϕ.onFunction f) x = funMap f x := by exact fun {n} => isEmptyElim map_onRelation : ∀ {n} (R : L.Relations n) (x : Fin n → M), RelMap (ϕ.onRelation R) x = RelMap R x := by exact fun {n} => isEmptyElim @[simp] theorem map_onFunction {M : Type*} [L.Structure M] [L'.Structure M] [ϕ.IsExpansionOn M] {n} (f : L.Functions n) (x : Fin n → M) : funMap (ϕ.onFunction f) x = funMap f x := IsExpansionOn.map_onFunction f x @[simp] theorem map_onRelation {M : Type*} [L.Structure M] [L'.Structure M] [ϕ.IsExpansionOn M] {n} (R : L.Relations n) (x : Fin n → M) : RelMap (ϕ.onRelation R) x = RelMap R x := IsExpansionOn.map_onRelation R x instance id_isExpansionOn (M : Type*) [L.Structure M] : IsExpansionOn (LHom.id L) M := ⟨fun _ _ => rfl, fun _ _ => rfl⟩ instance ofIsEmpty_isExpansionOn (M : Type*) [L.Structure M] [L'.Structure M] [L.IsAlgebraic] [L.IsRelational] : IsExpansionOn (LHom.ofIsEmpty L L') M where instance sumElim_isExpansionOn {L'' : Language} (ψ : L'' →ᴸ L') (M : Type*) [L.Structure M] [L'.Structure M] [L''.Structure M] [ϕ.IsExpansionOn M] [ψ.IsExpansionOn M] : (ϕ.sumElim ψ).IsExpansionOn M := ⟨fun f _ => Sum.casesOn f (by simp) (by simp), fun R _ => Sum.casesOn R (by simp) (by simp)⟩ instance sumMap_isExpansionOn {L₁ L₂ : Language} (ψ : L₁ →ᴸ L₂) (M : Type*) [L.Structure M] [L'.Structure M] [L₁.Structure M] [L₂.Structure M] [ϕ.IsExpansionOn M] [ψ.IsExpansionOn M] : (ϕ.sumMap ψ).IsExpansionOn M := ⟨fun f _ => Sum.casesOn f (by simp) (by simp), fun R _ => Sum.casesOn R (by simp) (by simp)⟩ instance sumInl_isExpansionOn (M : Type*) [L.Structure M] [L'.Structure M] : (LHom.sumInl : L →ᴸ L.sum L').IsExpansionOn M := ⟨fun _f _ => rfl, fun _R _ => rfl⟩ instance sumInr_isExpansionOn (M : Type*) [L.Structure M] [L'.Structure M] : (LHom.sumInr : L' →ᴸ L.sum L').IsExpansionOn M := ⟨fun _f _ => rfl, fun _R _ => rfl⟩ @[simp] theorem funMap_sumInl [(L.sum L').Structure M] [(LHom.sumInl : L →ᴸ L.sum L').IsExpansionOn M] {n} {f : L.Functions n} {x : Fin n → M} : @funMap (L.sum L') M _ n (Sum.inl f) x = funMap f x := (LHom.sumInl : L →ᴸ L.sum L').map_onFunction f x @[simp] theorem funMap_sumInr [(L'.sum L).Structure M] [(LHom.sumInr : L →ᴸ L'.sum L).IsExpansionOn M] {n} {f : L.Functions n} {x : Fin n → M} : @funMap (L'.sum L) M _ n (Sum.inr f) x = funMap f x := (LHom.sumInr : L →ᴸ L'.sum L).map_onFunction f x theorem sumInl_injective : (LHom.sumInl : L →ᴸ L.sum L').Injective := ⟨fun h => Sum.inl_injective h, fun h => Sum.inl_injective h⟩ theorem sumInr_injective : (LHom.sumInr : L' →ᴸ L.sum L').Injective := ⟨fun h => Sum.inr_injective h, fun h => Sum.inr_injective h⟩ instance (priority := 100) isExpansionOn_reduct (ϕ : L →ᴸ L') (M : Type*) [L'.Structure M] : @IsExpansionOn L L' ϕ M (ϕ.reduct M) _ := letI := ϕ.reduct M ⟨fun _f _ => rfl, fun _R _ => rfl⟩ theorem Injective.isExpansionOn_default {ϕ : L →ᴸ L'} [∀ (n) (f : L'.Functions n), Decidable (f ∈ Set.range fun f : L.Functions n => ϕ.onFunction f)] [∀ (n) (r : L'.Relations n), Decidable (r ∈ Set.range fun r : L.Relations n => ϕ.onRelation r)] (h : ϕ.Injective) (M : Type*) [Inhabited M] [L.Structure M] : @IsExpansionOn L L' ϕ M _ (ϕ.defaultExpansion M) := by letI := ϕ.defaultExpansion M refine ⟨fun {n} f xs => ?_, fun {n} r xs => ?_⟩ · have hf : ϕ.onFunction f ∈ Set.range fun f : L.Functions n => ϕ.onFunction f := ⟨f, rfl⟩ refine (dif_pos hf).trans ?_ rw [h.onFunction hf.choose_spec] · have hr : ϕ.onRelation r ∈ Set.range fun r : L.Relations n => ϕ.onRelation r := ⟨r, rfl⟩ refine (dif_pos hr).trans ?_ rw [h.onRelation hr.choose_spec] end LHom /-- A language equivalence maps the symbols of one language to symbols of another bijectively. -/ structure LEquiv (L L' : Language) where /-- The forward language homomorphism -/ toLHom : L →ᴸ L' /-- The inverse language homomorphism -/ invLHom : L' →ᴸ L left_inv : invLHom.comp toLHom = LHom.id L right_inv : toLHom.comp invLHom = LHom.id L' @[inherit_doc] infixl:10 " ≃ᴸ " => LEquiv -- \^L namespace LEquiv variable (L) in /-- The identity equivalence from a first-order language to itself. -/ @[simps] protected def refl : L ≃ᴸ L := ⟨LHom.id L, LHom.id L, LHom.comp_id _, LHom.comp_id _⟩ instance : Inhabited (L ≃ᴸ L) := ⟨LEquiv.refl L⟩ variable {L'' : Language} (e' : L' ≃ᴸ L'') (e : L ≃ᴸ L') /-- The inverse of an equivalence of first-order languages. -/ @[simps] protected def symm : L' ≃ᴸ L := ⟨e.invLHom, e.toLHom, e.right_inv, e.left_inv⟩ /-- The composition of equivalences of first-order languages. -/ @[simps, trans] protected def trans (e : L ≃ᴸ L') (e' : L' ≃ᴸ L'') : L ≃ᴸ L'' := ⟨e'.toLHom.comp e.toLHom, e.invLHom.comp e'.invLHom, by rw [LHom.comp_assoc, ← LHom.comp_assoc e'.invLHom, e'.left_inv, LHom.id_comp, e.left_inv], by rw [LHom.comp_assoc, ← LHom.comp_assoc e.toLHom, e.right_inv, LHom.id_comp, e'.right_inv]⟩ end LEquiv section ConstantsOn variable (α : Type u') /-- The type of functions for a language consisting only of constant symbols. -/ @[simp] def constantsOnFunc : ℕ → Type u' | 0 => α | (_ + 1) => PEmpty /-- A language with constants indexed by a type. -/ @[simps] def constantsOn : Language.{u', 0} := ⟨constantsOnFunc α, fun _ => Empty⟩ variable {α} theorem constantsOn_constants : (constantsOn α).Constants = α := rfl instance isAlgebraic_constantsOn : IsAlgebraic (constantsOn α) := by unfold constantsOn infer_instance instance isEmpty_functions_constantsOn_succ {n : ℕ} : IsEmpty ((constantsOn α).Functions (n + 1)) := inferInstanceAs (IsEmpty PEmpty) instance isRelational_constantsOn [_ie : IsEmpty α] : IsRelational (constantsOn α) := fun n => Nat.casesOn n _ie inferInstance theorem card_constantsOn : (constantsOn α).card = #α := by simp [card_eq_card_functions_add_card_relations, sum_nat_eq_add_sum_succ] /-- Gives a `constantsOn α` structure to a type by assigning each constant a value. -/ def constantsOn.structure (f : α → M) : (constantsOn α).Structure M where funMap := fun {n} c _ => match n, c with | 0, c => f c variable {β : Type v'} /-- A map between index types induces a map between constant languages. -/ def LHom.constantsOnMap (f : α → β) : constantsOn α →ᴸ constantsOn β where onFunction := fun {n} c => match n, c with | 0, c => f c theorem constantsOnMap_isExpansionOn {f : α → β} {fα : α → M} {fβ : β → M} (h : fβ ∘ f = fα) : @LHom.IsExpansionOn _ _ (LHom.constantsOnMap f) M (constantsOn.structure fα) (constantsOn.structure fβ) := by letI := constantsOn.structure fα letI := constantsOn.structure fβ exact ⟨fun {n} => Nat.casesOn n (fun F _x => (congr_fun h F :)) fun n F => isEmptyElim F, fun R => isEmptyElim R⟩ end ConstantsOn section WithConstants variable (L) section variable (α : Type w') /-- Extends a language with a constant for each element of a parameter set in `M`. -/ def withConstants : Language.{max u w', v} := L.sum (constantsOn α) @[inherit_doc FirstOrder.Language.withConstants] scoped[FirstOrder] notation:95 L "[[" α "]]" => Language.withConstants L α @[simp] theorem card_withConstants : L[[α]].card = Cardinal.lift.{w'} L.card + Cardinal.lift.{max u v} #α := by rw [withConstants, card_sum, card_constantsOn] /-- The language map adding constants. -/ @[simps!] def lhomWithConstants : L →ᴸ L[[α]] := LHom.sumInl theorem lhomWithConstants_injective : (L.lhomWithConstants α).Injective := LHom.sumInl_injective variable {α} /-- The constant symbol indexed by a particular element. -/ protected def con (a : α) : L[[α]].Constants := Sum.inr a variable {L} (α) /-- Adds constants to a language map. -/ def LHom.addConstants {L' : Language} (φ : L →ᴸ L') : L[[α]] →ᴸ L'[[α]] := φ.sumMap (LHom.id _) instance paramsStructure (A : Set α) : (constantsOn A).Structure α := constantsOn.structure (↑) variable (L) /-- The language map removing an empty constant set. -/ @[simps] def LEquiv.addEmptyConstants [ie : IsEmpty α] : L ≃ᴸ L[[α]] where toLHom := lhomWithConstants L α invLHom := LHom.sumElim (LHom.id L) (LHom.ofIsEmpty (constantsOn α) L) left_inv := by rw [lhomWithConstants, LHom.sumElim_comp_inl] right_inv := by simp only [LHom.comp_sumElim, lhomWithConstants, LHom.comp_id] exact _root_.trans (congr rfl (Subsingleton.elim _ _)) LHom.sumElim_inl_inr variable {α} {β : Type*} @[simp] theorem withConstants_funMap_sumInl [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {n} {f : L.Functions n} {x : Fin n → M} : @funMap (L[[α]]) M _ n (Sum.inl f) x = funMap f x := (lhomWithConstants L α).map_onFunction f x @[simp] theorem withConstants_relMap_sumInl [L[[α]].Structure M] [(lhomWithConstants L α).IsExpansionOn M] {n} {R : L.Relations n} {x : Fin n → M} : @RelMap (L[[α]]) M _ n (Sum.inl R) x = RelMap R x := (lhomWithConstants L α).map_onRelation R x @[deprecated (since := "2025-02-21")] alias withConstants_funMap_sum_inl := withConstants_funMap_sumInl @[deprecated (since := "2025-02-21")] alias withConstants_relMap_sum_inl := withConstants_relMap_sumInl /-- The language map extending the constant set. -/ def lhomWithConstantsMap (f : α → β) : L[[α]] →ᴸ L[[β]] := LHom.sumMap (LHom.id L) (LHom.constantsOnMap f) @[simp] theorem LHom.map_constants_comp_sumInl {f : α → β} : (L.lhomWithConstantsMap f).comp LHom.sumInl = L.lhomWithConstants β := by ext <;> rfl end open FirstOrder instance constantsOnSelfStructure : (constantsOn M).Structure M := constantsOn.structure id instance withConstantsSelfStructure : L[[M]].Structure M := Language.sumStructure _ _ M instance withConstants_self_expansion : (lhomWithConstants L M).IsExpansionOn M := ⟨fun _ _ => rfl, fun _ _ => rfl⟩ variable (α : Type*) [(constantsOn α).Structure M] instance withConstantsStructure : L[[α]].Structure M := Language.sumStructure _ _ _ instance withConstants_expansion : (L.lhomWithConstants α).IsExpansionOn M := ⟨fun _ _ => rfl, fun _ _ => rfl⟩ instance addEmptyConstants_is_expansion_on' : (LEquiv.addEmptyConstants L (∅ : Set M)).toLHom.IsExpansionOn M := L.withConstants_expansion _ instance addEmptyConstants_symm_isExpansionOn : (LEquiv.addEmptyConstants L (∅ : Set M)).symm.toLHom.IsExpansionOn M := LHom.sumElim_isExpansionOn _ _ _ instance addConstants_expansion {L' : Language} [L'.Structure M] (φ : L →ᴸ L') [φ.IsExpansionOn M] : (φ.addConstants α).IsExpansionOn M := LHom.sumMap_isExpansionOn _ _ M @[simp] theorem withConstants_funMap_sumInr {a : α} {x : Fin 0 → M} : @funMap (L[[α]]) M _ 0 (Sum.inr a : L[[α]].Functions 0) x = L.con a := by rw [Unique.eq_default x] exact (LHom.sumInr : constantsOn α →ᴸ L.sum _).map_onFunction _ _ @[deprecated (since := "2025-02-21")] alias withConstants_funMap_sum_inr := withConstants_funMap_sumInr variable {α} (A : Set M) @[simp] theorem coe_con {a : A} : (L.con a : M) = a := rfl variable {A} {B : Set M} (h : A ⊆ B) instance constantsOnMap_inclusion_isExpansionOn : (LHom.constantsOnMap (Set.inclusion h)).IsExpansionOn M := constantsOnMap_isExpansionOn rfl instance map_constants_inclusion_isExpansionOn : (L.lhomWithConstantsMap (Set.inclusion h)).IsExpansionOn M := LHom.sumMap_isExpansionOn _ _ _ end WithConstants end Language end FirstOrder
CheckCompositions.lean
/- Copyright (c) 2025 Lean FRO, LLC. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.Category.Basic /-! The `check_compositions` tactic, which checks the typing of categorical compositions in the goal, reporting discrepancies at "instances and reducible" transparency. Reports from this tactic do not necessarily indicate a problem, although typically `simp` should reduce rather than increase the reported discrepancies. `check_compositions` may be useful in diagnosing uses of `erw` in the category theory library. -/ namespace Mathlib.Tactic.CheckCompositions open CategoryTheory open Lean Meta Elab Tactic /-- Find appearances of `CategoryStruct.comp C inst X Y Z f g`, and apply `f` to each. -/ def forEachComposition (e : Expr) (f : Expr → MetaM Unit) : MetaM Unit := do e.forEach (fun e ↦ if e.isAppOfArity ``CategoryStruct.comp 7 then f e else pure ()) /-- Given a composition `CategoryStruct.comp _ _ X Y Z f g`, infer the types of `f` and `g` and check whether their sources and targets agree, at "instances and reducible" transparency, with `X`, `Y`, and `Z`, reporting any discrepancies. -/ def checkComposition (e : Expr) : MetaM Unit := do match_expr e with | CategoryStruct.comp _ _ X Y Z f g => match_expr ← inferType f with | Quiver.Hom _ _ X' Y' => withReducibleAndInstances do if !(← isDefEq X' X) then logInfo m!"In composition\n {e}\nthe source of\n {f}\nis\n {X'}\nbut should be\n {X}" if !(← isDefEq Y' Y) then logInfo m!"In composition\n {e}\nthe target of\n {f}\nis\n {Y'}\nbut should be\n {Y}" | _ => throwError "In composition\n {e}\nthe type of\n {f}\nis not a morphism." match_expr ← inferType g with | Quiver.Hom _ _ Y' Z' => withReducibleAndInstances do if !(← isDefEq Y' Y) then logInfo m!"In composition\n {e}\nthe source of\n {g}\nis\n {Y'}\nbut should be\n {Y}" if !(← isDefEq Z' Z) then logInfo m!"In composition\n {e}\nthe target of\n {g}\nis\n {Z'}\nbut should be\n {Z}" | _ => throwError "In composition\n {e}\nthe type of\n {g}\nis not a morphism." | _ => throwError "{e} is not a composition." /-- Check the typing of categorical compositions in an expression. -/ def checkCompositions (e : Expr) : MetaM Unit := do forEachComposition e checkComposition /-- Check the typing of categorical compositions in the goal. -/ def checkCompositionsTac : TacticM Unit := withMainContext do let e ← getMainTarget checkCompositions e /-- For each composition `f ≫ g` in the goal, which internally is represented as `CategoryStruct.comp C inst X Y Z f g`, infer the types of `f` and `g` and check whether their sources and targets agree with `X`, `Y`, and `Z` at "instances and reducible" transparency, reporting any discrepancies. An example: ``` example (j : J) : colimit.ι ((F ⋙ G) ⋙ H) j ≫ (preservesColimitIso (G ⋙ H) F).inv = H.map (G.map (colimit.ι F j)) := by -- We know which lemma we want to use, and it's even a simp lemma, but `rw` -- won't let us apply it fail_if_success rw [ι_preservesColimitIso_inv] fail_if_success rw [ι_preservesColimitIso_inv (G ⋙ H)] fail_if_success simp only [ι_preservesColimitIso_inv] -- This would work: -- erw [ι_preservesColimitIso_inv (G ⋙ H)] -- `check_compositions` checks if the two morphisms we're composing are -- composed by abusing defeq, and indeed it tells us that we are abusing -- definitional associativity of composition of functors here: it prints -- the following. -- info: In composition -- colimit.ι ((F ⋙ G) ⋙ H) j ≫ (preservesColimitIso (G ⋙ H) F).inv -- the source of -- (preservesColimitIso (G ⋙ H) F).inv -- is -- colimit (F ⋙ G ⋙ H) -- but should be -- colimit ((F ⋙ G) ⋙ H) check_compositions -- In this case, we can "fix" this by reassociating in the goal, but -- usually at this point the right thing to do is to back off and -- check how we ended up with a bad goal in the first place. dsimp only [Functor.assoc] -- This would work now, but it is not needed, because simp works as well -- rw [ι_preservesColimitIso_inv] simp ``` -/ elab "check_compositions" : tactic => checkCompositionsTac end Mathlib.Tactic.CheckCompositions
BundledHom.lean
/- Copyright (c) 2019 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison, Yury Kudryashov -/ import Mathlib.CategoryTheory.ConcreteCategory.Basic import Mathlib.CategoryTheory.ConcreteCategory.Bundled /-! # Category instances for algebraic structures that use bundled homs. Many algebraic structures in Lean initially used unbundled homs (e.g. a bare function between types, along with an `IsMonoidHom` typeclass), but the general trend is towards using bundled homs. This file provides a basic infrastructure to define concrete categories using bundled homs, and define forgetful functors between them. -/ universe u namespace CategoryTheory variable {c : Type u → Type u} (hom : ∀ ⦃α β : Type u⦄ (_ : c α) (_ : c β), Type u) /-- Class for bundled homs. Note that the arguments order follows that of lemmas for `MonoidHom`. This way we can use `⟨@MonoidHom.toFun, @MonoidHom.id ...⟩` in an instance. -/ structure BundledHom where /-- the underlying map of a bundled morphism -/ toFun : ∀ {α β : Type u} (Iα : c α) (Iβ : c β), hom Iα Iβ → α → β /-- the identity as a bundled morphism -/ id : ∀ {α : Type u} (I : c α), hom I I /-- composition of bundled morphisms -/ comp : ∀ {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ), hom Iβ Iγ → hom Iα Iβ → hom Iα Iγ /-- a bundled morphism is determined by the underlying map -/ hom_ext : ∀ {α β : Type u} (Iα : c α) (Iβ : c β), Function.Injective (toFun Iα Iβ) := by cat_disch /-- compatibility with identities -/ id_toFun : ∀ {α : Type u} (I : c α), toFun I I (id I) = _root_.id := by cat_disch /-- compatibility with the composition -/ comp_toFun : ∀ {α β γ : Type u} (Iα : c α) (Iβ : c β) (Iγ : c γ) (f : hom Iα Iβ) (g : hom Iβ Iγ), toFun Iα Iγ (comp Iα Iβ Iγ g f) = toFun Iβ Iγ g ∘ toFun Iα Iβ f := by cat_disch attribute [class] BundledHom attribute [simp] BundledHom.id_toFun BundledHom.comp_toFun namespace BundledHom variable [𝒞 : BundledHom hom] set_option synthInstance.checkSynthOrder false in /-- Every `@BundledHom c _` defines a category with objects in `Bundled c`. This instance generates the type-class problem `BundledHom ?m`. Currently that is not a problem, as there are almost no instances of `BundledHom`. -/ instance category : Category (Bundled c) where Hom := fun X Y => hom X.str Y.str id := fun X => BundledHom.id 𝒞 (α := X) X.str comp := fun {X Y Z} f g => BundledHom.comp 𝒞 (α := X) (β := Y) (γ := Z) X.str Y.str Z.str g f comp_id _ := by apply 𝒞.hom_ext; simp assoc _ _ _ := by apply 𝒞.hom_ext; cat_disch id_comp _ := by apply 𝒞.hom_ext; simp /-- A category given by `BundledHom` is a concrete category. -/ instance hasForget : HasForget.{u} (Bundled c) where forget := { obj := fun X => X map := fun {X Y} f => 𝒞.toFun X.str Y.str f map_id := fun X => 𝒞.id_toFun X.str map_comp := fun f g => by erw [𝒞.comp_toFun]; rfl } forget_faithful := { map_injective := by (intros; apply 𝒞.hom_ext) } /-- This unification hint helps `rw` to figure out how to apply statements about abstract concrete categories to specific concrete categories. Crucially, it fires also at `reducible` levels so `rw` can use it (and we don't have to use `erw`). -/ unif_hint (C : Bundled c) where ⊢ (CategoryTheory.forget (Bundled c)).obj C =?= Bundled.α C variable {hom} attribute [local instance] HasForget.instFunLike /-- A version of `HasForget₂.mk'` for categories defined using `@BundledHom`. -/ def mkHasForget₂ {d : Type u → Type u} {hom_d : ∀ ⦃α β : Type u⦄ (_ : d α) (_ : d β), Type u} [BundledHom hom_d] (obj : ∀ ⦃α⦄, c α → d α) (map : ∀ {X Y : Bundled c}, (X ⟶ Y) → (Bundled.map @obj X ⟶ (Bundled.map @obj Y))) (h_map : ∀ {X Y : Bundled c} (f : X ⟶ Y), ⇑(map f) = ⇑f) : HasForget₂ (Bundled c) (Bundled d) := HasForget₂.mk' (Bundled.map @obj) (fun _ => rfl) map (by intros X Y f rw [heq_eq_eq, forget_map_eq_coe, forget_map_eq_coe, h_map f]) variable {d : Type u → Type u} variable (hom) section /-- The `hom` corresponding to first forgetting along `F`, then taking the `hom` associated to `c`. For typical usage, see the construction of `CommMonCat` from `MonCat`. -/ abbrev MapHom (F : ∀ {α}, d α → c α) : ∀ ⦃α β : Type u⦄ (_ : d α) (_ : d β), Type u := fun _ _ iα iβ => hom (F iα) (F iβ) end /-- Construct the `CategoryTheory.BundledHom` induced by a map between type classes. This is useful for building categories such as `CommMonCat` from `MonCat`. -/ def map (F : ∀ {α}, d α → c α) : BundledHom (MapHom hom @F) where toFun _ _ {iα} {iβ} f := 𝒞.toFun (F iα) (F iβ) f id _ {iα} := 𝒞.id (F iα) comp := @fun _ _ _ iα iβ iγ f g => 𝒞.comp (F iα) (F iβ) (F iγ) f g hom_ext := @fun _ _ iα iβ _ _ h => 𝒞.hom_ext (F iα) (F iβ) h section /-- We use the empty `ParentProjection` class to label functions like `CommMonoid.toMonoid`, which we would like to use to automatically construct `BundledHom` instances from. Once we've set up `MonCat` as the category of bundled monoids, this allows us to set up `CommMonCat` by defining an instance ```instance : ParentProjection (CommMonoid.toMonoid) := ⟨⟩``` -/ class ParentProjection (F : ∀ {α}, d α → c α) : Prop end -- The `ParentProjection` typeclass is just a marker, so won't be used. @[nolint unusedArguments] instance bundledHomOfParentProjection (F : ∀ {α}, d α → c α) [ParentProjection @F] : BundledHom (MapHom hom @F) := map hom @F instance forget₂ (F : ∀ {α}, d α → c α) [ParentProjection @F] : HasForget₂ (Bundled d) (Bundled c) where forget₂ := { obj := fun X => ⟨X, F X.2⟩ map := @fun _ _ f => f } instance forget₂_full (F : ∀ {α}, d α → c α) [ParentProjection @F] : Functor.Full (CategoryTheory.forget₂ (Bundled d) (Bundled c)) where map_surjective f := ⟨f, rfl⟩ end BundledHom end CategoryTheory
RightAngle.lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import Mathlib.Analysis.SpecialFunctions.Trigonometric.Arctan import Mathlib.Geometry.Euclidean.Angle.Unoriented.Affine /-! # Right-angled triangles This file proves basic geometrical results about distances and angles in (possibly degenerate) right-angled triangles in real inner product spaces and Euclidean affine spaces. ## Implementation notes Results in this file are generally given in a form with only those non-degeneracy conditions needed for the particular result, rather than requiring affine independence of the points of a triangle unnecessarily. ## References * https://en.wikipedia.org/wiki/Pythagorean_theorem -/ noncomputable section open scoped EuclideanGeometry open scoped Real open scoped RealInnerProductSpace namespace InnerProductGeometry variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] /-- Pythagorean theorem, if-and-only-if vector angle form. -/ theorem norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := by rw [norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero] exact inner_eq_zero_iff_angle_eq_pi_div_two x y /-- Pythagorean theorem, vector angle form. -/ theorem norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ‖x + y‖ * ‖x + y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/ theorem norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ ↔ angle x y = π / 2 := by rw [norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero] exact inner_eq_zero_iff_angle_eq_pi_div_two x y /-- Pythagorean theorem, subtracting vectors, vector angle form. -/ theorem norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = π / 2) : ‖x - y‖ * ‖x - y‖ = ‖x‖ * ‖x‖ + ‖y‖ * ‖y‖ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h /-- An angle in a right-angled triangle expressed using `arccos`. -/ theorem angle_add_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x + y) = Real.arccos (‖x‖ / ‖x + y‖) := by rw [angle, inner_add_right, h, add_zero, real_inner_self_eq_norm_mul_norm] by_cases hx : ‖x‖ = 0; · simp [hx] rw [div_mul_eq_div_div, mul_self_div_self] /-- An angle in a right-angled triangle expressed using `arcsin`. -/ theorem angle_add_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : angle x (x + y) = Real.arcsin (‖y‖ / ‖x + y‖) := by have hxy : ‖x + y‖ ^ 2 ≠ 0 := by rw [pow_two, norm_add_sq_eq_norm_sq_add_norm_sq_real h, ne_comm] refine ne_of_lt ?_ rcases h0 with (h0 | h0) · exact Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _) · exact Left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_eq_arcsin (div_nonneg (norm_nonneg _) (norm_nonneg _)), div_pow, one_sub_div hxy] nth_rw 1 [pow_two] rw [norm_add_sq_eq_norm_sq_add_norm_sq_real h, pow_two, add_sub_cancel_left, ← pow_two, ← div_pow, Real.sqrt_sq (div_nonneg (norm_nonneg _) (norm_nonneg _))] /-- An angle in a right-angled triangle expressed using `arctan`. -/ theorem angle_add_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x + y) = Real.arctan (‖y‖ / ‖x‖) := by rw [angle_add_eq_arcsin_of_inner_eq_zero h (Or.inl h0), Real.arctan_eq_arcsin, ← div_mul_eq_div_div, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h] nth_rw 3 [← Real.sqrt_sq (norm_nonneg x)] rw_mod_cast [← Real.sqrt_mul (sq_nonneg _), div_pow, pow_two, pow_two, mul_add, mul_one, mul_div, mul_comm (‖x‖ * ‖x‖), ← mul_div, div_self (mul_self_pos.2 (norm_ne_zero_iff.2 h0)).ne', mul_one] /-- An angle in a non-degenerate right-angled triangle is positive. -/ theorem angle_add_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : 0 < angle x (x + y) := by rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_pos, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h] by_cases hx : x = 0; · simp [hx] rw [div_lt_one (Real.sqrt_pos.2 (Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 hx)) (mul_self_nonneg _))), Real.lt_sqrt (norm_nonneg _), pow_two] simpa [hx] using h0 /-- An angle in a right-angled triangle is at most `π / 2`. -/ theorem angle_add_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x + y) ≤ π / 2 := by rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_le_pi_div_two] exact div_nonneg (norm_nonneg _) (norm_nonneg _) /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/ theorem angle_add_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x + y) < π / 2 := by rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.arccos_lt_pi_div_two, norm_add_eq_sqrt_iff_real_inner_eq_zero.2 h] exact div_pos (norm_pos_iff.2 h0) (Real.sqrt_pos.2 (Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _))) /-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/ theorem cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.cos (angle x (x + y)) = ‖x‖ / ‖x + y‖ := by rw [angle_add_eq_arccos_of_inner_eq_zero h, Real.cos_arccos (le_trans (by simp) (div_nonneg (norm_nonneg _) (norm_nonneg _))) (div_le_one_of_le₀ _ (norm_nonneg _))] rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _), norm_add_sq_eq_norm_sq_add_norm_sq_real h] exact le_add_of_nonneg_right (mul_self_nonneg _) /-- The sine of an angle in a right-angled triangle as a ratio of sides. -/ theorem sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : Real.sin (angle x (x + y)) = ‖y‖ / ‖x + y‖ := by rw [angle_add_eq_arcsin_of_inner_eq_zero h h0, Real.sin_arcsin (le_trans (by simp) (div_nonneg (norm_nonneg _) (norm_nonneg _))) (div_le_one_of_le₀ _ (norm_nonneg _))] rw [mul_self_le_mul_self_iff (norm_nonneg _) (norm_nonneg _), norm_add_sq_eq_norm_sq_add_norm_sq_real h] exact le_add_of_nonneg_left (mul_self_nonneg _) /-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/ theorem tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.tan (angle x (x + y)) = ‖y‖ / ‖x‖ := by by_cases h0 : x = 0; · simp [h0] rw [angle_add_eq_arctan_of_inner_eq_zero h h0, Real.tan_arctan] /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side. -/ theorem cos_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.cos (angle x (x + y)) * ‖x + y‖ = ‖x‖ := by rw [cos_angle_add_of_inner_eq_zero h] by_cases hxy : ‖x + y‖ = 0 · have h' := norm_add_sq_eq_norm_sq_add_norm_sq_real h rw [hxy, zero_mul, eq_comm, add_eq_zero_iff_of_nonneg (mul_self_nonneg ‖x‖) (mul_self_nonneg ‖y‖), mul_self_eq_zero] at h' simp [h'.1] · exact div_mul_cancel₀ _ hxy /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side. -/ theorem sin_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.sin (angle x (x + y)) * ‖x + y‖ = ‖y‖ := by by_cases h0 : x = 0 ∧ y = 0; · simp [h0] rw [not_and_or] at h0 rw [sin_angle_add_of_inner_eq_zero h h0, div_mul_cancel₀] rw [← mul_self_ne_zero, norm_add_sq_eq_norm_sq_add_norm_sq_real h] refine (ne_of_lt ?_).symm rcases h0 with (h0 | h0) · exact Left.add_pos_of_pos_of_nonneg (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) (mul_self_nonneg _) · exact Left.add_pos_of_nonneg_of_pos (mul_self_nonneg _) (mul_self_pos.2 (norm_ne_zero_iff.2 h0)) /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side. -/ theorem tan_angle_add_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : Real.tan (angle x (x + y)) * ‖x‖ = ‖y‖ := by rw [tan_angle_add_of_inner_eq_zero h] rcases h0 with (h0 | h0) <;> simp [h0] /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse. -/ theorem norm_div_cos_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : ‖x‖ / Real.cos (angle x (x + y)) = ‖x + y‖ := by rw [cos_angle_add_of_inner_eq_zero h] rcases h0 with (h0 | h0) · rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] · simp [h0] /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse. -/ theorem norm_div_sin_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / Real.sin (angle x (x + y)) = ‖x + y‖ := by rcases h0 with (h0 | h0); · simp [h0] rw [sin_angle_add_of_inner_eq_zero h (Or.inr h0), div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side. -/ theorem norm_div_tan_angle_add_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / Real.tan (angle x (x + y)) = ‖x‖ := by rw [tan_angle_add_of_inner_eq_zero h] rcases h0 with (h0 | h0) · simp [h0] · rw [div_div_eq_mul_div, mul_comm, div_eq_mul_inv, mul_inv_cancel_right₀ (norm_ne_zero_iff.2 h0)] /-- An angle in a right-angled triangle expressed using `arccos`, version subtracting vectors. -/ theorem angle_sub_eq_arccos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x - y) = Real.arccos (‖x‖ / ‖x - y‖) := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, angle_add_eq_arccos_of_inner_eq_zero h] /-- An angle in a right-angled triangle expressed using `arcsin`, version subtracting vectors. -/ theorem angle_sub_eq_arcsin_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : angle x (x - y) = Real.arcsin (‖y‖ / ‖x - y‖) := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [or_comm, ← neg_ne_zero, or_comm] at h0 rw [sub_eq_add_neg, angle_add_eq_arcsin_of_inner_eq_zero h h0, norm_neg] /-- An angle in a right-angled triangle expressed using `arctan`, version subtracting vectors. -/ theorem angle_sub_eq_arctan_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x - y) = Real.arctan (‖y‖ / ‖x‖) := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, angle_add_eq_arctan_of_inner_eq_zero h h0, norm_neg] /-- An angle in a non-degenerate right-angled triangle is positive, version subtracting vectors. -/ theorem angle_sub_pos_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : 0 < angle x (x - y) := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [← neg_ne_zero] at h0 rw [sub_eq_add_neg] exact angle_add_pos_of_inner_eq_zero h h0 /-- An angle in a right-angled triangle is at most `π / 2`, version subtracting vectors. -/ theorem angle_sub_le_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : angle x (x - y) ≤ π / 2 := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg] exact angle_add_le_pi_div_two_of_inner_eq_zero h /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`, version subtracting vectors. -/ theorem angle_sub_lt_pi_div_two_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0) : angle x (x - y) < π / 2 := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg] exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0 /-- The cosine of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ theorem cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.cos (angle x (x - y)) = ‖x‖ / ‖x - y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, cos_angle_add_of_inner_eq_zero h] /-- The sine of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ theorem sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y ≠ 0) : Real.sin (angle x (x - y)) = ‖y‖ / ‖x - y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [or_comm, ← neg_ne_zero, or_comm] at h0 rw [sub_eq_add_neg, sin_angle_add_of_inner_eq_zero h h0, norm_neg] /-- The tangent of an angle in a right-angled triangle as a ratio of sides, version subtracting vectors. -/ theorem tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.tan (angle x (x - y)) = ‖y‖ / ‖x‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, tan_angle_add_of_inner_eq_zero h, norm_neg] /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side, version subtracting vectors. -/ theorem cos_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.cos (angle x (x - y)) * ‖x - y‖ = ‖x‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, cos_angle_add_mul_norm_of_inner_eq_zero h] /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side, version subtracting vectors. -/ theorem sin_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) : Real.sin (angle x (x - y)) * ‖x - y‖ = ‖y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [sub_eq_add_neg, sin_angle_add_mul_norm_of_inner_eq_zero h, norm_neg] /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side, version subtracting vectors. -/ theorem tan_angle_sub_mul_norm_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : Real.tan (angle x (x - y)) * ‖x‖ = ‖y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [← neg_eq_zero] at h0 rw [sub_eq_add_neg, tan_angle_add_mul_norm_of_inner_eq_zero h h0, norm_neg] /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse, version subtracting vectors. -/ theorem norm_div_cos_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x ≠ 0 ∨ y = 0) : ‖x‖ / Real.cos (angle x (x - y)) = ‖x - y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [← neg_eq_zero] at h0 rw [sub_eq_add_neg, norm_div_cos_angle_add_of_inner_eq_zero h h0] /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse, version subtracting vectors. -/ theorem norm_div_sin_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / Real.sin (angle x (x - y)) = ‖x - y‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [← neg_ne_zero] at h0 rw [sub_eq_add_neg, ← norm_neg, norm_div_sin_angle_add_of_inner_eq_zero h h0] /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side, version subtracting vectors. -/ theorem norm_div_tan_angle_sub_of_inner_eq_zero {x y : V} (h : ⟪x, y⟫ = 0) (h0 : x = 0 ∨ y ≠ 0) : ‖y‖ / Real.tan (angle x (x - y)) = ‖x‖ := by rw [← neg_eq_zero, ← inner_neg_right] at h rw [← neg_ne_zero] at h0 rw [sub_eq_add_neg, ← norm_neg, norm_div_tan_angle_add_of_inner_eq_zero h h0] end InnerProductGeometry namespace EuclideanGeometry open InnerProductGeometry variable {V : Type*} {P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P] [NormedAddTorsor V P] /-- **Pythagorean theorem**, if-and-only-if angle-at-point form. -/ theorem dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p₁ p₂ p₃ : P) : dist p₁ p₃ * dist p₁ p₃ = dist p₁ p₂ * dist p₁ p₂ + dist p₃ p₂ * dist p₃ p₂ ↔ ∠ p₁ p₂ p₃ = π / 2 := by erw [dist_comm p₃ p₂, dist_eq_norm_vsub V p₁ p₃, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₂ p₃, ← norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two, vsub_sub_vsub_cancel_right p₁, ← neg_vsub_eq_vsub_rev p₂ p₃, norm_neg] /-- An angle in a right-angled triangle expressed using `arccos`. -/ theorem angle_eq_arccos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : ∠ p₂ p₃ p₁ = Real.arccos (dist p₃ p₂ / dist p₁ p₃) := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arccos_of_inner_eq_zero h] /-- An angle in a right-angled triangle expressed using `arcsin`. -/ theorem angle_eq_arcsin_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = Real.arcsin (dist p₁ p₂ / dist p₁ p₃) := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [← @vsub_ne_zero V, @ne_comm _ p₃, ← @vsub_ne_zero V _ _ _ p₂, or_comm] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arcsin_of_inner_eq_zero h h0] /-- An angle in a right-angled triangle expressed using `arctan`. -/ theorem angle_eq_arctan_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ = Real.arctan (dist p₁ p₂ / dist p₃ p₂) := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [ne_comm, ← @vsub_ne_zero V] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, angle_add_eq_arctan_of_inner_eq_zero h h0] /-- An angle in a non-degenerate right-angled triangle is positive. -/ theorem angle_pos_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : 0 < ∠ p₂ p₃ p₁ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [← @vsub_ne_zero V, eq_comm, ← @vsub_eq_zero_iff_eq V, or_comm] at h0 rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm] exact angle_add_pos_of_inner_eq_zero h h0 /-- An angle in a right-angled triangle is at most `π / 2`. -/ theorem angle_le_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : ∠ p₂ p₃ p₁ ≤ π / 2 := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm] exact angle_add_le_pi_div_two_of_inner_eq_zero h /-- An angle in a non-degenerate right-angled triangle is less than `π / 2`. -/ theorem angle_lt_pi_div_two_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₃ ≠ p₂) : ∠ p₂ p₃ p₁ < π / 2 := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [ne_comm, ← @vsub_ne_zero V] at h0 rw [angle, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm] exact angle_add_lt_pi_div_two_of_inner_eq_zero h h0 /-- The cosine of an angle in a right-angled triangle as a ratio of sides. -/ theorem cos_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : Real.cos (∠ p₂ p₃ p₁) = dist p₃ p₂ / dist p₁ p₃ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, cos_angle_add_of_inner_eq_zero h] /-- The sine of an angle in a right-angled triangle as a ratio of sides. -/ theorem sin_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ ≠ p₂) : Real.sin (∠ p₂ p₃ p₁) = dist p₁ p₂ / dist p₁ p₃ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [← @vsub_ne_zero V, @ne_comm _ p₃, ← @vsub_ne_zero V _ _ _ p₂, or_comm] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, sin_angle_add_of_inner_eq_zero h h0] /-- The tangent of an angle in a right-angled triangle as a ratio of sides. -/ theorem tan_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : Real.tan (∠ p₂ p₃ p₁) = dist p₁ p₂ / dist p₃ p₂ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, tan_angle_add_of_inner_eq_zero h] /-- The cosine of an angle in a right-angled triangle multiplied by the hypotenuse equals the adjacent side. -/ theorem cos_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : Real.cos (∠ p₂ p₃ p₁) * dist p₁ p₃ = dist p₃ p₂ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, cos_angle_add_mul_norm_of_inner_eq_zero h] /-- The sine of an angle in a right-angled triangle multiplied by the hypotenuse equals the opposite side. -/ theorem sin_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) : Real.sin (∠ p₂ p₃ p₁) * dist p₁ p₃ = dist p₁ p₂ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, sin_angle_add_mul_norm_of_inner_eq_zero h] /-- The tangent of an angle in a right-angled triangle multiplied by the adjacent side equals the opposite side. -/ theorem tan_angle_mul_dist_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ = p₂ ∨ p₃ ≠ p₂) : Real.tan (∠ p₂ p₃ p₁) * dist p₃ p₂ = dist p₁ p₂ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [ne_comm, ← @vsub_ne_zero V, ← @vsub_eq_zero_iff_eq V, or_comm] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, tan_angle_add_mul_norm_of_inner_eq_zero h h0] /-- A side of a right-angled triangle divided by the cosine of the adjacent angle equals the hypotenuse. -/ theorem dist_div_cos_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ = p₂ ∨ p₃ ≠ p₂) : dist p₃ p₂ / Real.cos (∠ p₂ p₃ p₁) = dist p₁ p₃ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [ne_comm, ← @vsub_ne_zero V, ← @vsub_eq_zero_iff_eq V, or_comm] at h0 rw [angle, dist_eq_norm_vsub' V p₃ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_cos_angle_add_of_inner_eq_zero h h0] /-- A side of a right-angled triangle divided by the sine of the opposite angle equals the hypotenuse. -/ theorem dist_div_sin_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : dist p₁ p₂ / Real.sin (∠ p₂ p₃ p₁) = dist p₁ p₃ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [eq_comm, ← @vsub_ne_zero V, ← @vsub_eq_zero_iff_eq V, or_comm] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub V p₁ p₃, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_sin_angle_add_of_inner_eq_zero h h0] /-- A side of a right-angled triangle divided by the tangent of the opposite angle equals the adjacent side. -/ theorem dist_div_tan_angle_of_angle_eq_pi_div_two {p₁ p₂ p₃ : P} (h : ∠ p₁ p₂ p₃ = π / 2) (h0 : p₁ ≠ p₂ ∨ p₃ = p₂) : dist p₁ p₂ / Real.tan (∠ p₂ p₃ p₁) = dist p₃ p₂ := by rw [angle, ← inner_eq_zero_iff_angle_eq_pi_div_two, real_inner_comm, ← neg_eq_zero, ← inner_neg_left, neg_vsub_eq_vsub_rev] at h rw [eq_comm, ← @vsub_ne_zero V, ← @vsub_eq_zero_iff_eq V, or_comm] at h0 rw [angle, dist_eq_norm_vsub V p₁ p₂, dist_eq_norm_vsub' V p₃ p₂, ← vsub_add_vsub_cancel p₁ p₂ p₃, add_comm, norm_div_tan_angle_add_of_inner_eq_zero h h0] end EuclideanGeometry
RadonNikodym.lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Thomas Zhu -/ import Mathlib.MeasureTheory.Measure.Decomposition.RadonNikodym import Mathlib.MeasureTheory.VectorMeasure.Decomposition.Lebesgue /-! # Radon-Nikodym derivatives of vector measures This file contains results about Radon-Nikodym derivatives of signed measures that depend both on the Lebesgue decomposition of signed measures and the theory of Radon-Nikodym derivatives of usual measures. -/ namespace MeasureTheory variable {α : Type*} {m : MeasurableSpace α} open Measure VectorMeasure namespace SignedMeasure theorem withDensityᵥ_rnDeriv_eq (s : SignedMeasure α) (μ : Measure α) [SigmaFinite μ] (h : s ≪ᵥ μ.toENNRealVectorMeasure) : μ.withDensityᵥ (s.rnDeriv μ) = s := by rw [absolutelyContinuous_ennreal_iff, (_ : μ.toENNRealVectorMeasure.ennrealToMeasure = μ), totalVariation_absolutelyContinuous_iff] at h · ext1 i hi rw [withDensityᵥ_apply (integrable_rnDeriv _ _) hi, rnDeriv_def, integral_sub, setIntegral_toReal_rnDeriv h.1 i, setIntegral_toReal_rnDeriv h.2 i] · conv_rhs => rw [← s.toSignedMeasure_toJordanDecomposition] erw [VectorMeasure.sub_apply] rw [toSignedMeasure_apply_measurable hi, toSignedMeasure_apply_measurable hi, measureReal_def, measureReal_def] all_goals refine Integrable.integrableOn ?_ refine ⟨?_, hasFiniteIntegral_toReal_of_lintegral_ne_top ?_⟩ · apply Measurable.aestronglyMeasurable (by fun_prop) · exact (lintegral_rnDeriv_lt_top _ _).ne · exact equivMeasure.right_inv μ /-- The Radon-Nikodym theorem for signed measures. -/ theorem absolutelyContinuous_iff_withDensityᵥ_rnDeriv_eq (s : SignedMeasure α) (μ : Measure α) [SigmaFinite μ] : s ≪ᵥ μ.toENNRealVectorMeasure ↔ μ.withDensityᵥ (s.rnDeriv μ) = s := ⟨withDensityᵥ_rnDeriv_eq s μ, fun h => h ▸ withDensityᵥ_absolutelyContinuous _ _⟩ end SignedMeasure theorem withDensityᵥ_rnDeriv_smul {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] {μ ν : Measure α} [μ.HaveLebesgueDecomposition ν] [SigmaFinite μ] {f : α → E} (hμν : μ ≪ ν) (hf : Integrable f μ) : ν.withDensityᵥ (fun x ↦ (μ.rnDeriv ν x).toReal • f x) = μ.withDensityᵥ f := by rw [withDensityᵥ_smul_eq_withDensityᵥ_withDensity' (measurable_rnDeriv μ ν).aemeasurable (rnDeriv_lt_top μ ν) ((integrable_rnDeriv_smul_iff hμν).mpr hf), withDensity_rnDeriv_eq μ ν hμν] end MeasureTheory
OpenCover.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.Topology.Sets.Opens /-! # Open covers We define `IsOpenCover` as a predicate on indexed families of open sets in a topological space `X`, asserting that their union is `X`. This is an example of a declaration whose name is actually longer than its content; but giving it a name serves as a way of standardizing API. -/ open Set Topology namespace TopologicalSpace /-- An indexed family of open sets whose union is `X`. -/ def IsOpenCover {ι X : Type*} [TopologicalSpace X] (u : ι → Opens X) : Prop := iSup u = ⊤ variable {ι κ X Y : Type*} [TopologicalSpace X] {u : ι → Opens X} [TopologicalSpace Y] {v : κ → Opens Y} namespace IsOpenCover lemma mk (h : iSup u = ⊤) : IsOpenCover u := h lemma of_sets {v : ι → Set X} (h_open : ∀ i, IsOpen (v i)) (h_iUnion : ⋃ i, v i = univ) : IsOpenCover (fun i ↦ ⟨v i, h_open i⟩) := by simp [IsOpenCover, h_iUnion] lemma iSup_eq_top (hu : IsOpenCover u) : ⨆ i, u i = ⊤ := hu lemma iSup_set_eq_univ (hu : IsOpenCover u) : ⋃ i, (u i : Set X) = univ := by simpa [← SetLike.coe_set_eq] using hu.iSup_eq_top /-- Pullback of a covering of `Y` by a continuous map `X → Y`, giving a covering of `X` with the same index type. -/ lemma comap (hv : IsOpenCover v) (f : C(X, Y)) : IsOpenCover fun k ↦ (v k).comap f := by simp [IsOpenCover, ← preimage_iUnion, hv.iSup_set_eq_univ] lemma exists_mem (hu : IsOpenCover u) (a : X) : ∃ i, a ∈ u i := by simpa [← hu.iSup_set_eq_univ] using mem_univ a lemma exists_mem_nhds (hu : IsOpenCover u) (a : X) : ∃ i, (u i : Set X) ∈ 𝓝 a := match hu.exists_mem a with | ⟨i, hi⟩ => ⟨i, (u i).isOpen.mem_nhds hi⟩ lemma iUnion_inter (hu : IsOpenCover u) (s : Set X) : ⋃ i, s ∩ u i = s := by simp [← inter_iUnion, hu.iSup_set_eq_univ] lemma isTopologicalBasis (hu : IsOpenCover u) {B : ∀ i, Set (Set (u i))} (hB : ∀ i, IsTopologicalBasis (B i)) : IsTopologicalBasis (⋃ i, (Subtype.val '' ·) '' B i) := isTopologicalBasis_of_cover (fun i ↦ (u i).2) hu.iSup_set_eq_univ hB end IsOpenCover end TopologicalSpace
EqualizerProducts.lean
/- Copyright (c) 2020 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.Limits.Shapes.Equalizers import Mathlib.CategoryTheory.Limits.Shapes.Products import Mathlib.Topology.Sheaves.SheafCondition.PairwiseIntersections /-! # The sheaf condition in terms of an equalizer of products Here we set up the machinery for the "usual" definition of the sheaf condition, e.g. as in https://stacks.math.columbia.edu/tag/0072 in terms of an equalizer diagram where the two objects are `∏ᶜ F.obj (U i)` and `∏ᶜ F.obj (U i) ⊓ (U j)`. We show that this sheaf condition is equivalent to the "pairwise intersections" sheaf condition when the presheaf is valued in a category with products, and thereby equivalent to the default sheaf condition. -/ universe v' v u noncomputable section open CategoryTheory CategoryTheory.Limits TopologicalSpace Opposite TopologicalSpace.Opens namespace TopCat variable {C : Type u} [Category.{v} C] [HasProducts.{v'} C] variable {X : TopCat.{v'}} (F : Presheaf C X) {ι : Type v'} (U : ι → Opens X) namespace Presheaf namespace SheafConditionEqualizerProducts /-- The product of the sections of a presheaf over a family of open sets. -/ def piOpens : C := ∏ᶜ fun i : ι => F.obj (op (U i)) /-- The product of the sections of a presheaf over the pairwise intersections of a family of open sets. -/ def piInters : C := ∏ᶜ fun p : ι × ι => F.obj (op (U p.1 ⊓ U p.2)) /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U i` to `U i ⊓ U j`. -/ def leftRes : piOpens F U ⟶ piInters.{v'} F U := Pi.lift fun p : ι × ι => Pi.π _ p.1 ≫ F.map (infLELeft (U p.1) (U p.2)).op /-- The morphism `Π F.obj (U i) ⟶ Π F.obj (U i) ⊓ (U j)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def rightRes : piOpens F U ⟶ piInters.{v'} F U := Pi.lift fun p : ι × ι => Pi.π _ p.2 ≫ F.map (infLERight (U p.1) (U p.2)).op /-- The morphism `F.obj U ⟶ Π F.obj (U i)` whose components are given by the restriction maps from `U j` to `U i ⊓ U j`. -/ def res : F.obj (op (iSup U)) ⟶ piOpens.{v'} F U := Pi.lift fun i : ι => F.map (TopologicalSpace.Opens.leSupr U i).op @[simp, elementwise] theorem res_π (i : ι) : res F U ≫ limit.π _ ⟨i⟩ = F.map (Opens.leSupr U i).op := by rw [res, limit.lift_π, Fan.mk_π_app] @[elementwise] theorem w : res F U ≫ leftRes F U = res F U ≫ rightRes F U := by dsimp [res, leftRes, rightRes] -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext (fun _ => ?_) simp only [limit.lift_π, limit.lift_π_assoc, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rw [← F.map_comp] congr 1 /-- The equalizer diagram for the sheaf condition. -/ abbrev diagram : WalkingParallelPair ⥤ C := parallelPair (leftRes.{v'} F U) (rightRes F U) /-- The restriction map `F.obj U ⟶ Π F.obj (U i)` gives a cone over the equalizer diagram for the sheaf condition. The sheaf condition asserts this cone is a limit cone. -/ def fork : Fork.{v} (leftRes F U) (rightRes F U) := Fork.ofι _ (w F U) @[simp] theorem fork_pt : (fork F U).pt = F.obj (op (iSup U)) := rfl @[simp] theorem fork_ι : (fork F U).ι = res F U := rfl @[simp] theorem fork_π_app_walkingParallelPair_zero : (fork F U).π.app WalkingParallelPair.zero = res F U := rfl -- Porting note: Shortcut simplifier @[simp (high)] theorem fork_π_app_walkingParallelPair_one : (fork F U).π.app WalkingParallelPair.one = res F U ≫ leftRes F U := rfl variable {F} {G : Presheaf C X} /-- Isomorphic presheaves have isomorphic `piOpens` for any cover `U`. -/ @[simp] def piOpens.isoOfIso (α : F ≅ G) : piOpens F U ≅ piOpens.{v'} G U := Pi.mapIso fun _ => α.app _ /-- Isomorphic presheaves have isomorphic `piInters` for any cover `U`. -/ @[simp] def piInters.isoOfIso (α : F ≅ G) : piInters F U ≅ piInters.{v'} G U := Pi.mapIso fun _ => α.app _ /-- Isomorphic presheaves have isomorphic sheaf condition diagrams. -/ def diagram.isoOfIso (α : F ≅ G) : diagram F U ≅ diagram.{v'} G U := NatIso.ofComponents (by rintro ⟨⟩ · exact piOpens.isoOfIso U α · exact piInters.isoOfIso U α) (by rintro ⟨⟩ ⟨⟩ ⟨⟩ · simp · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext (fun _ => ?_) simp only [leftRes, piOpens.isoOfIso, piInters.isoOfIso, parallelPair_map_left, Functor.mapIso_hom, lim_map, limit.lift_map, limit.lift_π, Cones.postcompose_obj_π, NatTrans.comp_app, Fan.mk_π_app, Discrete.natIso_hom_app, Iso.app_hom, Category.assoc, NatTrans.naturality, limMap_π_assoc] · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext (fun _ => ?_) simp only [rightRes, piOpens.isoOfIso, piInters.isoOfIso, parallelPair_map_right, Functor.mapIso_hom, lim_map, limit.lift_map, limit.lift_π, Cones.postcompose_obj_π, NatTrans.comp_app, Fan.mk_π_app, Discrete.natIso_hom_app, Iso.app_hom, Category.assoc, NatTrans.naturality, limMap_π_assoc] · simp) /-- If `F G : Presheaf C X` are isomorphic presheaves, then the `fork F U`, the canonical cone of the sheaf condition diagram for `F`, is isomorphic to `fork F G` postcomposed with the corresponding isomorphism between sheaf condition diagrams. -/ def fork.isoOfIso (α : F ≅ G) : fork F U ≅ (Cones.postcompose (diagram.isoOfIso U α).inv).obj (fork G U) := by fapply Fork.ext · apply α.app · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext (fun _ => ?_) dsimp only [Fork.ι] -- Ugh, `simp` can't unfold abbreviations. simp only [res, diagram.isoOfIso, Iso.app_hom, piOpens.isoOfIso, Cones.postcompose_obj_π, NatTrans.comp_app, fork_π_app_walkingParallelPair_zero, NatIso.ofComponents_inv_app, Functor.mapIso_inv, lim_map, limit.lift_map, Category.assoc, limit.lift_π, Fan.mk_π_app, Discrete.natIso_inv_app, Iso.app_inv, NatTrans.naturality, Iso.hom_inv_id_app_assoc] end SheafConditionEqualizerProducts /-- The sheaf condition for a `F : Presheaf C X` requires that the morphism `F.obj U ⟶ ∏ᶜ F.obj (U i)` (where `U` is some open set which is the union of the `U i`) is the equalizer of the two morphisms `∏ᶜ F.obj (U i) ⟶ ∏ᶜ F.obj (U i) ⊓ (U j)`. -/ def IsSheafEqualizerProducts (F : Presheaf.{v', v, u} C X) : Prop := ∀ ⦃ι : Type v'⦄ (U : ι → Opens X), Nonempty (IsLimit (SheafConditionEqualizerProducts.fork F U)) /-! The remainder of this file shows that the "equalizer products" sheaf condition is equivalent to the "pairwise intersections" sheaf condition. -/ namespace SheafConditionPairwiseIntersections open CategoryTheory.Pairwise CategoryTheory.Pairwise.Hom /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivFunctorObj (c : Cone ((diagram U).op ⋙ F)) : Cone (SheafConditionEqualizerProducts.diagram F U) where pt := c.pt π := { app := fun Z => WalkingParallelPair.casesOn Z (Pi.lift fun i : ι => c.π.app (op (single i))) (Pi.lift fun b : ι × ι => c.π.app (op (pair b.1 b.2))) naturality := fun Y Z f => by cases Y <;> cases Z <;> cases f · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun i => ?_ dsimp simp only [limit.lift_π, Category.id_comp, Fan.mk_π_app, CategoryTheory.Functor.map_id, Category.assoc] dsimp simp only [limit.lift_π, Category.id_comp, Fan.mk_π_app] · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] have h := c.π.naturality (Quiver.Hom.op (Hom.left i j)) dsimp at h simpa using h · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [SheafConditionEqualizerProducts.rightRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] have h := c.π.naturality (Quiver.Hom.op (Hom.right i j)) dsimp at h simpa using h · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun i => ?_ dsimp simp only [limit.lift_π, Category.id_comp, Fan.mk_π_app, CategoryTheory.Functor.map_id, Category.assoc] dsimp simp only [limit.lift_π, Category.id_comp, Fan.mk_π_app] } section /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivFunctor : Limits.Cone ((diagram U).op ⋙ F) ⥤ Limits.Cone (SheafConditionEqualizerProducts.diagram F U) where obj c := coneEquivFunctorObj F U c map {c c'} f := { hom := f.hom w := fun j => by cases j <;> · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun i => ?_ simp only [Limits.Fan.mk_π_app, Limits.ConeMorphism.w, Limits.limit.lift_π, Category.assoc, coneEquivFunctorObj_π_app] } end /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivInverseObj (c : Limits.Cone (SheafConditionEqualizerProducts.diagram F U)) : Limits.Cone ((diagram U).op ⋙ F) where pt := c.pt π := { app := by intro x induction x with | op x => ?_ rcases x with (⟨i⟩ | ⟨i, j⟩) · exact c.π.app WalkingParallelPair.zero ≫ Pi.π _ i · exact c.π.app WalkingParallelPair.one ≫ Pi.π _ (i, j) naturality := by intro x y f induction x with | op x => ?_ induction y with | op y => ?_ have ef : f = f.unop.op := rfl revert ef generalize f.unop = f' rintro rfl rcases x with (⟨i⟩ | ⟨⟩) <;> rcases y with (⟨⟩ | ⟨j, j⟩) <;> rcases f' with ⟨⟩ · dsimp rw [F.map_id] simp · dsimp simp only [Category.id_comp, Category.assoc] have h := c.π.naturality WalkingParallelPairHom.left dsimp [SheafConditionEqualizerProducts.leftRes] at h simp only [Category.id_comp] at h have h' := h =≫ Pi.π _ (i, j) rw [h'] simp only [Category.assoc, limit.lift_π, Fan.mk_π_app] rfl · dsimp simp only [Category.id_comp, Category.assoc] have h := c.π.naturality WalkingParallelPairHom.right dsimp [SheafConditionEqualizerProducts.rightRes] at h simp only [Category.id_comp] at h have h' := h =≫ Pi.π _ (j, i) rw [h'] simp rfl · dsimp rw [F.map_id] simp } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivInverse : Limits.Cone (SheafConditionEqualizerProducts.diagram F U) ⥤ Limits.Cone ((diagram U).op ⋙ F) where obj c := coneEquivInverseObj F U c map {c c'} f := { hom := f.hom w := by intro x induction x with | op x => ?_ rcases x with (⟨i⟩ | ⟨i, j⟩) · dsimp dsimp only [Fork.ι] rw [← f.w WalkingParallelPair.zero, Category.assoc] · dsimp rw [← f.w WalkingParallelPair.one, Category.assoc] } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps] def coneEquivUnitIsoApp (c : Cone ((diagram U).op ⋙ F)) : (𝟭 (Cone ((diagram U).op ⋙ F))).obj c ≅ (coneEquivFunctor F U ⋙ coneEquivInverse F U).obj c where hom := { hom := 𝟙 _ w := fun j => by induction j with | op j => ?_ rcases j with ⟨⟩ <;> · dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } inv := { hom := 𝟙 _ w := fun j => by induction j with | op j => ?_ rcases j with ⟨⟩ <;> · dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivUnitIso : 𝟭 (Limits.Cone ((diagram U).op ⋙ F)) ≅ coneEquivFunctor F U ⋙ coneEquivInverse F U := NatIso.ofComponents (coneEquivUnitIsoApp F U) /-- Implementation of `SheafConditionPairwiseIntersections.coneEquiv`. -/ @[simps!] def coneEquivCounitIso : coneEquivInverse F U ⋙ coneEquivFunctor F U ≅ 𝟭 (Limits.Cone (SheafConditionEqualizerProducts.diagram F U)) := NatIso.ofComponents (fun c => { hom := { hom := 𝟙 _ w := by rintro ⟨_ | _⟩ · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨j⟩ => ?_ dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } inv := { hom := 𝟙 _ w := by rintro ⟨_ | _⟩ · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨j⟩ => ?_ dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [coneEquivInverse] simp only [Limits.Fan.mk_π_app, Category.id_comp, Limits.limit.lift_π] } }) fun {c d} f => by ext dsimp simp only [Category.comp_id, Category.id_comp] /-- Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram. -/ @[simps] def coneEquiv : Limits.Cone ((diagram U).op ⋙ F) ≌ Limits.Cone (SheafConditionEqualizerProducts.diagram F U) where functor := coneEquivFunctor F U inverse := coneEquivInverse F U unitIso := coneEquivUnitIso F U counitIso := coneEquivCounitIso F U /-- If `SheafConditionEqualizerProducts.fork` is an equalizer, then `F.mapCone (cone U)` is a limit cone. -/ def isLimitMapConeOfIsLimitSheafConditionFork (P : IsLimit (SheafConditionEqualizerProducts.fork F U)) : IsLimit (F.mapCone (cocone U).op) := IsLimit.ofIsoLimit ((IsLimit.ofConeEquiv (coneEquiv F U).symm).symm P) { hom := { hom := 𝟙 _ w := by intro x induction x with | op x => ?_ rcases x with ⟨⟩ · simp rfl · dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } inv := { hom := 𝟙 _ w := by intro x induction x with | op x => ?_ rcases x with ⟨⟩ · simp rfl · dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } } /-- If `F.mapCone (cone U)` is a limit cone, then `SheafConditionEqualizerProducts.fork` is an equalizer. -/ def isLimitSheafConditionForkOfIsLimitMapCone (Q : IsLimit (F.mapCone (cocone U).op)) : IsLimit (SheafConditionEqualizerProducts.fork F U) := IsLimit.ofIsoLimit ((IsLimit.ofConeEquiv (coneEquiv F U)).symm Q) { hom := { hom := 𝟙 _ w := by rintro ⟨⟩ · simp rfl · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } inv := { hom := 𝟙 _ w := by rintro ⟨⟩ · simp rfl · -- Porting note (https://github.com/leanprover-community/mathlib4/issues/11041): `ext` can't see `limit.hom_ext` applies here: refine limit.hom_ext fun ⟨i, j⟩ => ?_ dsimp [coneEquivInverse, SheafConditionEqualizerProducts.res, SheafConditionEqualizerProducts.leftRes] simp only [limit.lift_π, limit.lift_π_assoc, Category.id_comp, Fan.mk_π_app, Category.assoc] rw [← F.map_comp] rfl } } end SheafConditionPairwiseIntersections open SheafConditionPairwiseIntersections /-- The sheaf condition in terms of an equalizer diagram is equivalent to the default sheaf condition. -/ theorem isSheaf_iff_isSheafEqualizerProducts (F : Presheaf C X) : F.IsSheaf ↔ F.IsSheafEqualizerProducts := (isSheaf_iff_isSheafPairwiseIntersections F).trans <| Iff.intro (fun h _ U => ⟨isLimitSheafConditionForkOfIsLimitMapCone F U (h U).some⟩) fun h _ U => ⟨isLimitMapConeOfIsLimitSheafConditionFork F U (h U).some⟩ end Presheaf end TopCat
GrothendieckAbelian.lean
/- Copyright (c) 2024 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.Abelian.GrothendieckCategory.Basic import Mathlib.CategoryTheory.Generator.HomologicalComplex import Mathlib.Algebra.Homology.HomologicalComplexAbelian /-! # Homological complexes in a Grothendieck abelian category Let `c : ComplexShape ι` be a complex shape with no loop, and such that `Small.{w} ι`. Then, if `C` is a Grothendieck abelian category (with `IsGrothendieckAbelian.{w} C`), the category `HomologicalComplex C c` is Grothendieck abelian. -/ universe w w' t v u open CategoryTheory Limits namespace HomologicalComplex variable (C : Type u) [Category.{v} C] {ι : Type t} (c : ComplexShape ι) section HasZeroMorphisms variable [HasZeroMorphisms C] instance locallySmall [LocallySmall.{w} C] [Small.{w} ι] : LocallySmall.{w} (HomologicalComplex C c) where hom_small K L := by let emb (f : K ⟶ L) (i : Shrink.{w} ι) := (equivShrink.{w} _) (f.f ((equivShrink _).symm i)) have hemb : Function.Injective emb := fun f g h ↦ by ext i obtain ⟨i, rfl⟩ := (equivShrink.{w} _).symm.surjective i simpa [emb] using congr_fun h i apply small_of_injective hemb instance [HasFilteredColimitsOfSize.{w, w'} C] : HasFilteredColimitsOfSize.{w, w'} (HomologicalComplex C c) where HasColimitsOfShape J _ _ := by infer_instance instance hasExactColimitsOfShape (J : Type w) [Category.{w'} J] [HasFiniteLimits C] [HasColimitsOfShape J C] [HasExactColimitsOfShape J C] : HasExactColimitsOfShape J (HomologicalComplex C c) where preservesFiniteLimits := ⟨fun K _ _ ↦ ⟨fun {F} ↦ ⟨fun hc ↦ ⟨isLimitOfEval _ _ (fun i ↦ by let e := preservesColimitNatIso (J := J) (eval C c i) exact (IsLimit.postcomposeHomEquiv (Functor.isoWhiskerLeft F e) _).1 (IsLimit.ofIsoLimit (isLimitOfPreserves ((Functor.whiskeringRight J _ _).obj (eval C c i) ⋙ colim) hc) (Cones.ext (e.symm.app _) (fun k ↦ (NatIso.naturality_2 e.symm _).symm))))⟩⟩⟩⟩ instance ab5OfSize [HasFilteredColimitsOfSize.{w', w} C] [HasFiniteLimits C] [AB5OfSize.{w', w} C] : AB5OfSize.{w', w} (HomologicalComplex C c) where ofShape J _ _ := by infer_instance end HasZeroMorphisms instance isGrothendieckAbelian [Abelian C] [IsGrothendieckAbelian.{w} C] [c.HasNoLoop] [Small.{w} ι] : IsGrothendieckAbelian.{w} (HomologicalComplex C c) where hasSeparator := by have : HasCoproductsOfShape ι C := hasColimitsOfShape_of_equivalence (Discrete.equivalence (equivShrink.{w} ι)).symm infer_instance end HomologicalComplex
GlobalSections.lean
/- Copyright (c) 2025 Ben Eltschig. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ben Eltschig -/ import Mathlib.CategoryTheory.Sites.ConstantSheaf /-! # Global sections of sheaves In this file we define a global sections functor `Sheaf.Γ : Sheaf J A ⥤ A` and show that it is isomorphic to several other constructions when they exist, most notably evaluation of sheaves on a terminal object and `Functor.sectionsFunctor`. ## Main definitions / results * `HasGlobalSectionsFunctor J A`: typeclass stating that the constant sheaf functor `A ⥤ Sheaf J A` has a right-adjoint. * `Sheaf.Γ J A`: the global sections functor `Sheaf J A ⥤ A`, defined as the right-adjoint of the constant sheaf functor, whenever that exists. * `constantSheafΓAdj J A`: the adjunction between the constant sheaf functor and `Sheaf.Γ J A`. * `Sheaf.ΓNatIsoSheafSections J A hT`: on sites with a terminal object `T`, `Sheaf.Γ J A` exists and is isomorphic to the functor evaluating sheaves at `T`. * `Sheaf.ΓNatIsoLim J A`: when `A` has limits of shape `Cᵒᵖ`, `Sheaf.Γ J A` exists and is isomorphic to the functor taking each sheaf to the limit of its underlying presheaf. * `Sheaf.isLimitConeΓ F`: global sections are limits even when not all limits of shape `Cᵒᵖ` exist. * `Sheaf.ΓRes F U`: the restriction morphism from global sections of `F` to sections of `F` on `U`. * `Sheaf.natTransΓRes J A U`: the natural transformation from the global sections functor to the sections functor on `U`. * `Sheaf.ΓNatIsoSectionsFunctor J`: for sheaves of types, `Sheaf.Γ J A` is isomorphic to the functor taking each sheaf to the type of sections of its underlying presheaf in the sense of `Functor.sections`. * `Sheaf.ΓNatIsoCoyoneda J`: for sheaves of types, `Sheaf.Γ J A` is isomorphic to the coyoneda embedding of the terminal sheaf, i.e. the functor sending each sheaf `F` to the type of morphisms from the terminal sheaf to `F`. ## TODO * Generalise `Sheaf.ΓNatIsoSectionsFunctor` and `Sheaf.ΓNatIsoCoyoneda` from `Type max u v` to `Type max u v w`. This should hopefully be doable by relaxing the universe constraints of `instHasSheafifyOfHasFiniteLimits`. -/ universe u v w u₂ v₂ open CategoryTheory Limits Sheaf Opposite GrothendieckTopology namespace CategoryTheory variable {C : Type u} [Category.{v} C] (J : GrothendieckTopology C) (A : Type u₂) [Category.{v₂} A] [HasWeakSheafify J A] /-- Typeclass stating that the constant sheaf functor has a right adjoint. This right adjoint will then be called the global sections functor and written `Sheaf.Γ`. -/ abbrev HasGlobalSectionsFunctor := (constantSheaf J A).IsLeftAdjoint /-- We define the global sections functor as the right-adjoint of the constant sheaf functor whenever it exists. -/ noncomputable def Sheaf.Γ [HasGlobalSectionsFunctor J A] : Sheaf J A ⥤ A := (constantSheaf J A).rightAdjoint /-- The constant sheaf functor is by definition left-adjoint to the global sections functor. -/ noncomputable def constantSheafΓAdj [HasGlobalSectionsFunctor J A] : constantSheaf J A ⊣ Γ J A := Adjunction.ofIsLeftAdjoint (constantSheaf J A) instance [HasGlobalSectionsFunctor J A] : (Γ J A).IsRightAdjoint := by unfold Γ; infer_instance /-- Sites with a terminal object admit a global sections functor. -/ instance hasGlobalSectionsFunctor_of_hasTerminal [HasTerminal C] : HasGlobalSectionsFunctor J A := ⟨_, ⟨constantSheafAdj J A terminalIsTerminal⟩⟩ /-- On sites with a terminal object, the global sections functor is isomorphic to the functor of sections on that object. -/ noncomputable def Sheaf.ΓNatIsoSheafSections [HasTerminal C] {T : C} (hT : IsTerminal T) : Γ J A ≅ (sheafSections J A).obj (op T) := (constantSheafΓAdj J A).rightAdjointUniq (constantSheafAdj J A hT) /-- Every site `C` admits a global sections functor for `A`-valued sheaves when `A` has limits of shape `Cᵒᵖ`. -/ instance hasGlobalSectionsFunctor_of_hasLimitsOfShape [HasLimitsOfShape Cᵒᵖ A] : HasGlobalSectionsFunctor J A := ⟨sheafToPresheaf J A ⋙ lim, ⟨constLimAdj.comp (sheafificationAdjunction J A)⟩⟩ /-- Global sections of sheaves are naturally isomorphic to the limits of the underlying presheaves. Note that while `HasLimitsOfShape Cᵒᵖ A` is needed here to talk about `lim` as a functor, global sections are still limits without it - see `Sheaf.isLimitConeΓ`. -/ noncomputable def Sheaf.ΓNatIsoLim [HasLimitsOfShape Cᵒᵖ A] : Γ J A ≅ sheafToPresheaf J A ⋙ lim := (constantSheafΓAdj J A).rightAdjointUniq (constLimAdj.comp (sheafificationAdjunction J A)) variable {J A} /-- Natural transformations from a constant presheaf into a sheaf correspond to morphisms to its global sections. -/ noncomputable def Sheaf.ΓHomEquiv [HasGlobalSectionsFunctor J A] {X : A} {F : Sheaf J A} : ((Functor.const _).obj X ⟶ F.val) ≃ (X ⟶ (Γ J A).obj F) := ((sheafificationAdjunction J A).homEquiv _ _).symm.trans ((constantSheafΓAdj J A).homEquiv _ _) /-- Naturality lemma for `ΓHomEquiv` analogous to `Adjunction.homEquiv_naturality_left`. -/ lemma Sheaf.ΓHomEquiv_naturality_left [HasGlobalSectionsFunctor J A] {X' X : A} {F : Sheaf J A} (f : X' ⟶ X) (g : (Functor.const _).obj X ⟶ F.val) : ΓHomEquiv ((Functor.const _).map f ≫ g) = f ≫ ΓHomEquiv g := (congrArg _ ((sheafificationAdjunction J A).homEquiv_naturality_left_symm _ _)).trans ((constantSheafΓAdj J A).homEquiv_naturality_left _ _) /-- Naturality lemma for `ΓHomEquiv` analogous to `Adjunction.homEquiv_naturality_left_symm`. -/ lemma Sheaf.ΓHomEquiv_naturality_left_symm [HasGlobalSectionsFunctor J A] {X' X : A} {F : Sheaf J A} (f : X' ⟶ X) (g : X ⟶ (Γ J A).obj F) : ΓHomEquiv.symm (f ≫ g) = (Functor.const _).map f ≫ ΓHomEquiv.symm g := (congrArg _ ((constantSheafΓAdj J A).homEquiv_naturality_left_symm _ _)).trans ((sheafificationAdjunction J A).homEquiv_naturality_left _ _) /-- Naturality lemma for `ΓHomEquiv` analogous to `Adjunction.homEquiv_naturality_right`. -/ lemma Sheaf.ΓHomEquiv_naturality_right [HasGlobalSectionsFunctor J A] {X : A} {F F' : Sheaf J A} (f : (Functor.const _).obj X ⟶ F.val) (g : F ⟶ F') : ΓHomEquiv (f ≫ g.val) = ΓHomEquiv f ≫ (Γ J A).map g := (congrArg _ ((sheafificationAdjunction J A).homEquiv_naturality_right_symm _ _)).trans ((constantSheafΓAdj J A).homEquiv_naturality_right _ _) /-- Naturality lemma for `ΓHomEquiv` analogous to `Adjunction.homEquiv_naturality_right_symm`. -/ lemma Sheaf.ΓHomEquiv_naturality_right_symm [HasGlobalSectionsFunctor J A] {X : A} {F F' : Sheaf J A} (f : X ⟶ (Γ J A).obj F) (g : F ⟶ F') : ΓHomEquiv.symm (f ≫ (Γ J A).map g) = ΓHomEquiv.symm f ≫ g.val := (congrArg _ ((constantSheafΓAdj J A).homEquiv_naturality_right_symm _ _)).trans ((sheafificationAdjunction J A).homEquiv_naturality_right _ _) /-- The cone over a given sheaf whose cone point are the global sections and whose components are the restriction maps. -/ @[simps pt] noncomputable def Sheaf.coneΓ [HasGlobalSectionsFunctor J A] (F : Sheaf J A) : Cone F.val where pt := (Γ J A).obj F π := ΓHomEquiv.symm (𝟙 _) /-- The global sections cone `Sheaf.coneΓ` is limiting - that is, global sections are limits even when not all limits of shape `Cᵒᵖ` exist in `A`. -/ noncomputable def Sheaf.isLimitConeΓ [HasGlobalSectionsFunctor J A] (F : Sheaf J A) : IsLimit F.coneΓ where lift c := F.ΓHomEquiv c.π fac c j := by suffices h : ((Functor.const Cᵒᵖ).map (ΓHomEquiv c.π)) ≫ F.coneΓ.π = c.π from congr_app h j simp [coneΓ, ← ΓHomEquiv_naturality_left_symm] uniq c f hf := by replace hf : ((Functor.const Cᵒᵖ).map f) ≫ F.coneΓ.π = c.π := by ext j; exact hf j simpa [coneΓ, ← ΓHomEquiv_naturality_left_symm, Equiv.symm_apply_eq] using hf /-- The restriction map from global sections of `F` to sections on `U`. -/ noncomputable def Sheaf.ΓRes [HasGlobalSectionsFunctor J A] (F : Sheaf J A) (U : Cᵒᵖ) : (Γ J A).obj F ⟶ F.val.obj U := F.coneΓ.π.app U @[reassoc (attr := simp)] lemma Sheaf.ΓRes_map [HasGlobalSectionsFunctor J A] (F : Sheaf J A) {V U : Cᵒᵖ} (f : U ⟶ V) : F.ΓRes U ≫ F.val.map f = F.ΓRes V := F.coneΓ.w f @[simp] lemma Sheaf.coneΓ_π_app [HasGlobalSectionsFunctor J A] (F : Sheaf J A) (U : Cᵒᵖ) : F.coneΓ.π.app U = F.ΓRes U := rfl lemma Sheaf.ΓRes_naturality [HasGlobalSectionsFunctor J A] {F G : Sheaf J A} (f : F ⟶ G) (U : Cᵒᵖ) : (Γ J A).map f ≫ ΓRes G U = ΓRes F U ≫ f.val.app U := by refine .trans ?_ <| congr_app (ΓHomEquiv_naturality_right_symm _ _) U exact (congr_app (ΓHomEquiv_naturality_left_symm ((Γ J A).map f) (𝟙 _)) U).symm.trans (by simp) variable (J A) /-- The natural transformation from the global sections functor to the sections functor on any object `U`. -/ @[simps!] noncomputable def Sheaf.natTransΓRes [HasGlobalSectionsFunctor J A] (U : Cᵒᵖ) : Γ J A ⟶ (sheafSections J A).obj U where app F := ΓRes F U naturality _ _ f := ΓRes_naturality f U -- this is currently needed to obtain the instance `HasSheafify J (Type max u v)`. attribute [local instance] CategoryTheory.Types.instConcreteCategory attribute [local instance] CategoryTheory.Types.instFunLike /-- Global sections of a sheaf of types correspond to sections of the underlying presheaf. -/ noncomputable def Sheaf.ΓObjEquivSections [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] (F : Sheaf J (Type w)) : (Γ J (Type w)).obj F ≃ F.val.sections := (Equiv.trans (by exact (Equiv.funUnique PUnit _).symm) ΓHomEquiv.symm).trans (F.val.sectionsEquivHom PUnit).symm lemma Sheaf.ΓObjEquivSections_naturality [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] {F G : Sheaf J (Type w)} (f : F ⟶ G) (x : (Γ J _).obj F) : (ΓObjEquivSections J G) ((Γ J _).map f x) = (Functor.sectionsFunctor _).map f.val ((ΓObjEquivSections J F) x) := by dsimp [ΓObjEquivSections] exact (congr_arg _ (ΓHomEquiv_naturality_right_symm _ _)).trans (Functor.sectionsEquivHom_naturality_symm _ _ _) lemma Sheaf.ΓObjEquivSections_naturality_symm [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] {F G : Sheaf J (Type w)} (f : F ⟶ G) (x : F.val.sections) : (ΓObjEquivSections J G).symm ((Functor.sectionsFunctor _).map f.val x) = (Γ J _).map f ((ΓObjEquivSections J F).symm x) := congr_fun (ΓHomEquiv_naturality_right (F.val.sectionsEquivHom _ x) f) _ /-- For sheaves of types, the global sections functor is isomorphic to the sections functor on presheaves. -/ noncomputable def Sheaf.ΓNatIsoSectionsFunctor : Γ J (Type max u v) ≅ sheafToPresheaf J _ ⋙ Functor.sectionsFunctor _ := NatIso.ofComponents (fun F ↦ (ΓObjEquivSections J F).toIso) fun f ↦ by ext x exact ΓObjEquivSections_naturality J f x /-- Global sections of a sheaf of types `F` correspond to morphisms from a terminal sheaf to `F`. We use the constant sheaf on a singleton type as a specific choice of terminal sheaf here. -/ noncomputable def Sheaf.ΓObjEquivHom [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] (F : Sheaf J (Type w)) (X : Type w) [Unique X] : (Γ J (Type w)).obj F ≃ ((constantSheaf J (Type w)).obj X ⟶ F) := (Equiv.funUnique X _).symm.trans ((constantSheafΓAdj J (Type w)).homEquiv _ _).symm lemma Sheaf.ΓObjEquivHom_naturality [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] (X : Type w) [Unique X] {F G : Sheaf J (Type w)} (f : F ⟶ G) (x : (Γ J _).obj F) : (ΓObjEquivHom J G X) ((Γ J _).map f x) = (ΓObjEquivHom J F X) x ≫ f := (constantSheafΓAdj J _).homEquiv_naturality_right_symm _ _ lemma Sheaf.ΓObjEquivHom_naturality_symm [HasWeakSheafify J (Type w)] [HasGlobalSectionsFunctor J (Type w)] {X : Type w} [Unique X] {F G : Sheaf J (Type w)} (f : F ⟶ G) (x : (constantSheaf J _).obj X ⟶ F) : (ΓObjEquivHom J G X).symm (x ≫ f) = (Γ J _).map f ((ΓObjEquivHom J F X).symm x) := congr_fun ((constantSheafΓAdj J _).homEquiv_naturality_right x f) default /-- For sheaves of types, the global sections functor is isomorphic to the covariant hom functor of the terminal sheaf. -/ noncomputable def Sheaf.ΓNatIsoCoyoneda (X : Type max u v) [Unique X] : Γ J (Type max u v) ≅ coyoneda.obj (op ((constantSheaf J _).obj X)) := NatIso.ofComponents (fun F ↦ (F.ΓObjEquivHom J X).toIso) fun f ↦ by ext x exact ΓObjEquivHom_naturality J X f x end CategoryTheory
zmodp.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 choice eqtype ssrnat seq. From mathcomp Require Import div fintype bigop finset prime fingroup perm. From mathcomp Require Import ssralg finalg countalg. (******************************************************************************) (* Definition of the additive group and ring Zp, represented as 'I_p *) (******************************************************************************) (* Definitions: *) (* From fintype.v: *) (* 'I_p == the subtype of integers less than p, taken here as the type of *) (* the integers mod p. *) (* This file: *) (* inZp == the natural projection from nat into the integers mod p, *) (* represented as 'I_p. Here p is implicit, but MUST be of the *) (* form n.+1. *) (* The operations: *) (* Zp0 == the identity element for addition *) (* Zp1 == the identity element for multiplication, and a generator of *) (* additive group *) (* Zp_opp == inverse function for addition *) (* Zp_add == addition *) (* Zp_mul == multiplication *) (* Zp_inv == inverse function for multiplication *) (* Note that while 'I_n.+1 has canonical finZmodType and finGroupType *) (* structures, only 'I_n.+2 has a canonical ring structure (it has, in fact, *) (* a canonical finComUnitRing structure), and hence an associated *) (* multiplicative unit finGroupType. To mitigate the issues caused by the *) (* trivial "ring" (which is, indeed is NOT a ring in the ssralg/finalg *) (* formalization), we define additional notation: *) (* 'Z_p == the type of integers mod (max p 2); this is always a proper *) (* ring, by constructions. Note that 'Z_p is provably equal to *) (* 'I_p if p > 1, and convertible to 'I_p if p is of the form *) (* n.+2. *) (* Zp p == the subgroup of integers mod (max p 1) in 'Z_p; this is thus *) (* all of 'Z_p if p > 1, and else the trivial group. *) (* units_Zp p == the group of all units of 'Z_p -- i.e., the group of *) (* (multiplicative) automorphisms of Zp p. *) (* We show that Zp and units_Zp are abelian, and compute their orders. *) (* We use a similar technique to represent the prime fields: *) (* 'F_p == the finite field of integers mod the first prime divisor of *) (* maxn p 2. This is provably equal to 'Z_p and 'I_p if p is *) (* provably prime, and indeed convertible to the above if p is *) (* a concrete prime such as 2, 5 or 23. *) (* Note finally that due to the canonical structures it is possible to use *) (* 0%R instead of Zp0, and 1%R instead of Zp1 (for the latter, p must be of *) (* the form n.+2, and 1%R : nat will simplify to 1%N). *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Section ZpDef. (***********************************************************************) (* *) (* Mod p arithmetic on the finite set {0, 1, 2, ..., p - 1} *) (* *) (***********************************************************************) (* Operations on 'I_p without constraint on p. *) Section Generic. Variable p : nat. Implicit Types i j : 'I_p. Lemma Zp_opp_subproof i : (p - i) %% p < p. Proof. by case: p i => [[]//|k] i; apply/ltn_pmod. Qed. Definition Zp_opp i := Ordinal (Zp_opp_subproof i). Lemma Zp_add_subproof i j : (i + j) %% p < p. Proof. by case: p i j => [[]//|k] i j; apply/ltn_pmod. Qed. Definition Zp_add i j := Ordinal (Zp_add_subproof i j). Lemma Zp_mul_subproof i j : (i * j) %% p < p. Proof. by case: p i j => [[]//|k] i j; apply/ltn_pmod. Qed. Definition Zp_mul i j := Ordinal (Zp_mul_subproof i j). Lemma Zp_inv_subproof i : (egcdn i p).1 %% p < p. Proof. by case: p i => [[]//|k] i; apply/ltn_pmod. Qed. Definition Zp_inv i := if coprime p i then Ordinal (Zp_inv_subproof i) else i. Lemma Zp_addA : associative Zp_add. Proof. by move=> x y z; apply: val_inj; rewrite /= modnDml modnDmr addnA. Qed. Lemma Zp_addC : commutative Zp_add. Proof. by move=> x y; apply: val_inj; rewrite /= addnC. Qed. Lemma Zp_mulC : commutative Zp_mul. Proof. by move=> x y; apply: val_inj; rewrite /= mulnC. Qed. Lemma Zp_mulA : associative Zp_mul. Proof. by move=> x y z; apply: val_inj; rewrite /= modnMml modnMmr mulnA. Qed. Lemma Zp_mul_addr : right_distributive Zp_mul Zp_add. Proof. by move=> x y z; apply: val_inj; rewrite /= modnMmr modnDm mulnDr. Qed. Lemma Zp_mul_addl : left_distributive Zp_mul Zp_add. Proof. by move=> x y z; rewrite -!(Zp_mulC z) Zp_mul_addr. Qed. Lemma Zp_inv_out i : ~~ coprime p i -> Zp_inv i = i. Proof. by rewrite /Zp_inv => /negPf->. Qed. End Generic. Arguments Zp_opp {p}. Arguments Zp_add {p}. Arguments Zp_mul {p}. Arguments Zp_inv {p}. Variable p' : nat. Local Notation p := p'.+1. Implicit Types x y z : 'I_p. (* Standard injection; val (inZp i) = i %% p *) Definition inZp i := Ordinal (ltn_pmod i (ltn0Sn p')). Lemma modZp x : x %% p = x. Proof. by rewrite modn_small ?ltn_ord. Qed. Lemma valZpK x : inZp x = x. Proof. by apply: val_inj; rewrite /= modZp. Qed. (* Operations *) Definition Zp0 : 'I_p := ord0. Definition Zp1 := inZp 1. (* Additive group structure. *) Lemma Zp_add0z : left_id Zp0 Zp_add. Proof. by move=> x; apply: val_inj; rewrite /= modZp. Qed. Lemma Zp_addNz : left_inverse Zp0 Zp_opp Zp_add. Proof. by move=> x; apply: val_inj; rewrite /= modnDml subnK ?modnn // ltnW. Qed. HB.instance Definition _ := GRing.isZmodule.Build 'I_p (@Zp_addA _) (@Zp_addC _) Zp_add0z Zp_addNz. HB.instance Definition _ := [finGroupMixin of 'I_p for +%R]. (* Ring operations *) Lemma Zp_mul1z : left_id Zp1 Zp_mul. Proof. by move=> x; apply: val_inj; rewrite /= modnMml mul1n modZp. Qed. Lemma Zp_mulz1 : right_id Zp1 Zp_mul. Proof. by move=> x; rewrite Zp_mulC Zp_mul1z. Qed. Lemma Zp_mulVz x : coprime p x -> Zp_mul (Zp_inv x) x = Zp1. Proof. move=> co_p_x; apply: val_inj; rewrite /Zp_inv co_p_x /= modnMml. by rewrite -(chinese_modl co_p_x 1 0) /chinese addn0 mul1n mulnC. Qed. Lemma Zp_mulzV x : coprime p x -> Zp_mul x (Zp_inv x) = Zp1. Proof. by move=> Ux; rewrite /= Zp_mulC Zp_mulVz. Qed. Lemma Zp_intro_unit x y : Zp_mul y x = Zp1 -> coprime p x. Proof. case=> yx1; have:= coprimen1 p. by rewrite -coprime_modr -yx1 coprime_modr coprimeMr; case/andP. Qed. Lemma Zp_mulrn x n : x *+ n = inZp (x * n). Proof. apply: val_inj => /=; elim: n => [|n IHn]; first by rewrite muln0 modn_small. by rewrite !GRing.mulrS /= IHn modnDmr mulnS. Qed. Import GroupScope. Lemma Zp_mulgC : @commutative 'I_p _ mulg. Proof. exact: Zp_addC. Qed. Lemma Zp_abelian : abelian [set: 'I_p]. Proof. exact: FinRing.zmod_abelian. Qed. Lemma Zp_expg x n : x ^+ n = inZp (x * n). Proof. exact: Zp_mulrn. Qed. Lemma Zp1_expgz x : Zp1 ^+ x = x. Proof. rewrite Zp_expg; apply/val_inj. by move: (Zp_mul1z x) => /(congr1 val). Qed. Lemma Zp_cycle : setT = <[Zp1]>. Proof. by apply/setP=> x; rewrite -[x]Zp1_expgz inE groupX ?mem_gen ?set11. Qed. Lemma order_Zp1 : #[Zp1] = p. Proof. by rewrite orderE -Zp_cycle cardsT card_ord. Qed. End ZpDef. Arguments Zp0 {p'}. Arguments Zp1 {p'}. Arguments inZp {p'} i. Arguments valZpK {p'} x. (* We redefine fintype.ord1 to specialize it with 0 instead of ord0 *) (* since 'I_n is now canonically a zmodType *) Lemma ord1 : all_equal_to (0 : 'I_1). Proof. exact: ord1. Qed. Lemma lshift0 m n : lshift m (0 : 'I_n.+1) = (0 : 'I_(n + m).+1). Proof. exact: val_inj. Qed. Lemma rshift1 n : @rshift 1 n =1 lift (0 : 'I_n.+1). Proof. by move=> i; apply: val_inj. Qed. Lemma split1 n i : split (i : 'I_(1 + n)) = oapp (@inr _ _) (inl _ 0) (unlift 0 i). Proof. case: unliftP => [i'|] -> /=. by rewrite -rshift1 (unsplitK (inr _ _)). by rewrite -(lshift0 n 0) (unsplitK (inl _ _)). Qed. (* TODO: bigop is imported after zmodp in matrix.v and intdiv.v to prevent these warnings from triggering. We should restore the order of imports when these are removed. *) #[deprecated(since="mathcomp 2.3.0", note="Use bigop.big_ord1 instead.")] Notation big_ord1 := big_ord1 (only parsing). #[deprecated(since="mathcomp 2.3.0", note="Use bigop.big_ord1_cond instead.")] Notation big_ord1_cond := big_ord1_cond (only parsing). Section ZpNzRing. Variable p' : nat. Local Notation p := p'.+2. Lemma Zp_nontrivial : Zp1 != 0 :> 'I_p. Proof. by []. Qed. HB.instance Definition _ := GRing.Zmodule_isComNzRing.Build 'I_p (@Zp_mulA _) (@Zp_mulC _) (@Zp_mul1z _) (@Zp_mul_addl _) Zp_nontrivial. HB.instance Definition _ := GRing.ComNzRing_hasMulInverse.Build 'I_p (@Zp_mulVz _) (@Zp_intro_unit _) (@Zp_inv_out _). Lemma Zp_nat n : n%:R = inZp n :> 'I_p. Proof. by apply: val_inj; rewrite [n%:R]Zp_mulrn /= modnMml mul1n. Qed. Lemma natr_Zp (x : 'I_p) : x%:R = x. Proof. by rewrite Zp_nat valZpK. Qed. Lemma natr_negZp (x : 'I_p) : (- x)%:R = - x. Proof. by apply: val_inj; rewrite /= Zp_nat /= modn_mod. Qed. Import GroupScope. Lemma unit_Zp_mulgC : @commutative {unit 'I_p} _ mulg. Proof. by move=> u v; apply: val_inj; rewrite /= GRing.mulrC. Qed. Lemma unit_Zp_expg (u : {unit 'I_p}) n : val (u ^+ n) = inZp (val u ^ n) :> 'I_p. Proof. apply: val_inj => /=; elim: n => [|n IHn] //. by rewrite expgS /= IHn expnS modnMmr. Qed. End ZpNzRing. Definition Zp_trunc p := p.-2. Notation "''Z_' p" := 'I_(Zp_trunc p).+2 (at level 0, p at level 2, format "''Z_' p") : type_scope. Notation "''F_' p" := 'Z_(pdiv p) (at level 0, p at level 2, format "''F_' p") : type_scope. Arguments natr_Zp {p'} x. Section ZpNzRing. Import GRing.Theory. Lemma add_1_Zp p (x : 'Z_p) : 1 + x = ordS x. Proof. by case: p => [|[|p]] in x *; apply/val_inj. Qed. Lemma add_Zp_1 p (x : 'Z_p) : x + 1 = ordS x. Proof. by rewrite addrC add_1_Zp. Qed. Lemma sub_Zp_1 p (x : 'Z_p) : x - 1 = ord_pred x. Proof. by apply: (addIr 1); rewrite addrNK add_Zp_1 ord_predK. Qed. Lemma add_N1_Zp p (x : 'Z_p) : -1 + x = ord_pred x. Proof. by rewrite addrC sub_Zp_1. Qed. End ZpNzRing. Section Groups. Variable p : nat. Definition Zp := if p > 1 then [set: 'Z_p] else 1%g. Definition units_Zp := [set: {unit 'Z_p}]. Lemma Zp_cast : p > 1 -> (Zp_trunc p).+2 = p. Proof. by case: p => [|[]]. Qed. Lemma val_Zp_nat (p_gt1 : p > 1) n : (n%:R : 'Z_p) = (n %% p)%N :> nat. Proof. by rewrite Zp_nat /= Zp_cast. Qed. Lemma Zp_nat_mod (p_gt1 : p > 1)m : (m %% p)%:R = m%:R :> 'Z_p. Proof. by apply: ord_inj; rewrite !val_Zp_nat // modn_mod. Qed. Lemma pchar_Zp : p > 1 -> p%:R = 0 :> 'Z_p. Proof. by move=> p_gt1; rewrite -Zp_nat_mod ?modnn. Qed. Lemma unitZpE x : p > 1 -> ((x%:R : 'Z_p) \is a GRing.unit) = coprime p x. Proof. move=> p_gt1; rewrite qualifE /=. by rewrite val_Zp_nat ?Zp_cast ?coprime_modr. Qed. Lemma Zp_group_set : group_set Zp. Proof. by rewrite /Zp; case: (p > 1); apply: groupP. Qed. (* FIX ME : is this ok something similar is done in fingroup *) Canonical Zp_group := Group Zp_group_set. Lemma card_Zp : p > 0 -> #|Zp| = p. Proof. rewrite /Zp; case: p => [|[|p']] //= _; first by rewrite cards1. by rewrite cardsT card_ord. Qed. Lemma mem_Zp x : p > 1 -> x \in Zp. Proof. by rewrite /Zp => ->. Qed. Canonical units_Zp_group := [group of units_Zp]. Lemma card_units_Zp : p > 0 -> #|units_Zp| = totient p. Proof. move=> p_gt0; transitivity (totient p.-2.+2); last by case: p p_gt0 => [|[|p']]. rewrite cardsT card_sub -sum1_card big_mkcond /=. by rewrite totient_count_coprime big_mkord. Qed. Lemma units_Zp_abelian : abelian units_Zp. Proof. by apply/centsP=> u _ v _; apply: unit_Zp_mulgC. Qed. End Groups. #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Zp instead.")] Notation char_Zp := (pchar_Zp) (only parsing). (* Field structure for primes. *) Section PrimeField. Open Scope ring_scope. Variable p : nat. Section F_prime. Hypothesis p_pr : prime p. Lemma Fp_Zcast : Zp_trunc (pdiv p) = Zp_trunc p. Proof. by rewrite /pdiv primes_prime. Qed. Lemma Fp_cast : (Zp_trunc (pdiv p)).+2 = p. Proof. by rewrite Fp_Zcast ?Zp_cast ?prime_gt1. Qed. Lemma card_Fp : #|'F_p| = p. Proof. by rewrite card_ord Fp_cast. Qed. Lemma val_Fp_nat n : (n%:R : 'F_p) = (n %% p)%N :> nat. Proof. by rewrite Zp_nat /= Fp_cast. Qed. Lemma Fp_nat_mod m : (m %% p)%:R = m%:R :> 'F_p. Proof. by apply: ord_inj; rewrite !val_Fp_nat // modn_mod. Qed. Lemma pchar_Fp : p \in [pchar 'F_p]. Proof. by rewrite !inE -Fp_nat_mod p_pr ?modnn. Qed. Lemma pchar_Fp_0 : p%:R = 0 :> 'F_p. Proof. exact: GRing.pcharf0 pchar_Fp. Qed. Lemma unitFpE x : ((x%:R : 'F_p) \is a GRing.unit) = coprime p x. Proof. by rewrite pdiv_id // unitZpE // prime_gt1. Qed. End F_prime. Lemma Fp_fieldMixin : GRing.ComUnitRing_isField 'F_p. Proof. constructor => x nzx. rewrite qualifE /= prime_coprime ?gtnNdvd ?lt0n //. case: (ltnP 1 p) => [lt1p | ]; last by case: p => [|[|p']]. by rewrite Zp_cast ?prime_gt1 ?pdiv_prime. Qed. HB.instance Definition _ := Fp_fieldMixin. HB.instance Definition _ := FinRing.isField.Build 'F_p. End PrimeField. Section Sym. Import GRing. Lemma gen_tperm_step n (k : 'I_n.+1) : coprime n.+1 k -> <<[set tperm i (i + k) | i : 'I_n.+1]>>%g = [set: 'S_n.+1]. Proof. case: n k => [|n] k. move=> _; apply/eqP; rewrite eqEsubset subsetT/= -(gen_tperm 0)/= gen_subG. apply/subsetP => s /imsetP[/= [][|//] lt01 _ ->]. have ->: (Ordinal lt01) = 0 by apply/val_inj. by rewrite tperm1 group1. rewrite -unitZpE// natr_Zp => k_unit. apply/eqP; rewrite eqEsubset subsetT/= -(gen_tperm 0)/= gen_subG. apply/subsetP => s /imsetP[/= i _ ->]. rewrite -[i](mulVKr k_unit) -[_ * i]natr_Zp mulr_natr. elim: (val _) => //= {i} [|[|i] IHi]; first by rewrite tperm1 group1. by rewrite mulrSr mem_gen//; apply/imsetP; exists 0. have [->|kS2N0] := eqVneq (k *+ i.+2) 0; first by rewrite tperm1 group1. have kSSneqkS : k *+ i.+2 != k *+ i.+1. rewrite -subr_eq0 -mulrnBr// subSnn mulr1n. by apply: contraTneq k_unit => ->; rewrite unitr0. rewrite -(@tpermJ_tperm _ (k *+ i.+1)) 1?eq_sym//. rewrite groupJ// 1?tpermC// mulrSr 1?tpermC. by rewrite mem_gen//; apply/imsetP; exists (k *+ i.+1). Qed. Lemma perm_addr1X n m (j k : 'I_n.+1) : (perm (addrI m%R) ^+ j)%g k = m *+ j + k. Proof. by rewrite permX (eq_iter (permE _)) iter_addr. Qed. Lemma gen_tpermn_circular_shift n (i j : 'I_n.+2) (c := perm (addrI 1)) : coprime n.+2 (j - i)%R -> <<[set tperm i j ; c]>>%g = [set: 'S_n.+2]. Proof. move=> jBi_coprime; apply/eqP; rewrite eqEsubset subsetT/=. rewrite -(gen_tperm_step jBi_coprime) gen_subG. apply/subsetP => s /imsetP[/= k _ ->]. suff -> : tperm k (k + (j - i)) = (tperm i j ^ c ^+ (k - i)%R)%g. by rewrite groupJ ?groupX ?mem_gen ?inE ?eqxx ?orbT. by rewrite tpermJ !perm_addr1X natr_Zp addrNK addrAC addrA. Qed. End Sym. #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Fp instead.")] Notation char_Fp := (pchar_Fp) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use pchar_Fp_0 instead.")] Notation char_Fp_0 := (pchar_Fp_0) (only parsing).
Defs.lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.Group.Action.Basic import Mathlib.Algebra.Group.Pointwise.Set.Scalar import Mathlib.Algebra.Group.Subgroup.Defs import Mathlib.Algebra.Group.Submonoid.MulAction import Mathlib.Data.Set.BooleanAlgebra /-! # Definition of `orbit`, `fixedPoints` and `stabilizer` This file defines orbits, stabilizers, and other objects defined in terms of actions. ## Main definitions * `MulAction.orbit` * `MulAction.fixedPoints` * `MulAction.fixedBy` * `MulAction.stabilizer` -/ assert_not_exists MonoidWithZero DistribMulAction universe u v open Pointwise open Function namespace MulAction variable (M : Type u) [Monoid M] (α : Type v) [MulAction M α] {β : Type*} [MulAction M β] section Orbit variable {α} /-- The orbit of an element under an action. -/ @[to_additive /-- The orbit of an element under an action. -/] def orbit (a : α) := Set.range fun m : M => m • a variable {M} @[to_additive] theorem mem_orbit_iff {a₁ a₂ : α} : a₂ ∈ orbit M a₁ ↔ ∃ x : M, x • a₁ = a₂ := Iff.rfl @[to_additive (attr := simp)] theorem mem_orbit (a : α) (m : M) : m • a ∈ orbit M a := ⟨m, rfl⟩ @[to_additive] theorem mem_orbit_of_mem_orbit {a₁ a₂ : α} (m : M) (h : a₂ ∈ orbit M a₁) : m • a₂ ∈ orbit M a₁ := by obtain ⟨x, rfl⟩ := mem_orbit_iff.mp h simp [smul_smul] @[to_additive (attr := simp)] theorem mem_orbit_self (a : α) : a ∈ orbit M a := ⟨1, by simp⟩ @[to_additive] theorem orbit_nonempty (a : α) : Set.Nonempty (orbit M a) := Set.range_nonempty _ @[to_additive] theorem mapsTo_smul_orbit (m : M) (a : α) : Set.MapsTo (m • ·) (orbit M a) (orbit M a) := Set.range_subset_iff.2 fun m' => ⟨m * m', mul_smul _ _ _⟩ @[to_additive] theorem smul_orbit_subset (m : M) (a : α) : m • orbit M a ⊆ orbit M a := (mapsTo_smul_orbit m a).image_subset @[to_additive] theorem orbit_smul_subset (m : M) (a : α) : orbit M (m • a) ⊆ orbit M a := Set.range_subset_iff.2 fun m' => mul_smul m' m a ▸ mem_orbit _ _ @[to_additive] instance {a : α} : MulAction M (orbit M a) where smul m := (mapsTo_smul_orbit m a).restrict _ _ _ one_smul m := Subtype.ext (one_smul M (m : α)) mul_smul m m' a' := Subtype.ext (mul_smul m m' (a' : α)) @[to_additive (attr := simp)] theorem orbit.coe_smul {a : α} {m : M} {a' : orbit M a} : ↑(m • a') = m • (a' : α) := rfl @[to_additive] lemma orbit_submonoid_subset (S : Submonoid M) (a : α) : orbit S a ⊆ orbit M a := by rintro b ⟨g, rfl⟩ exact mem_orbit _ _ @[to_additive] lemma mem_orbit_of_mem_orbit_submonoid {S : Submonoid M} {a b : α} (h : a ∈ orbit S b) : a ∈ orbit M b := orbit_submonoid_subset S _ h end Orbit section FixedPoints /-- The set of elements fixed under the whole action. -/ @[to_additive /-- The set of elements fixed under the whole action. -/] def fixedPoints : Set α := { a : α | ∀ m : M, m • a = a } variable {M} in /-- `fixedBy m` is the set of elements fixed by `m`. -/ @[to_additive /-- `fixedBy m` is the set of elements fixed by `m`. -/] def fixedBy (m : M) : Set α := { x | m • x = x } @[to_additive] theorem fixed_eq_iInter_fixedBy : fixedPoints M α = ⋂ m : M, fixedBy α m := Set.ext fun _ => ⟨fun hx => Set.mem_iInter.2 fun m => hx m, fun hx m => (Set.mem_iInter.1 hx m :)⟩ variable {M α} @[to_additive (attr := simp)] theorem mem_fixedPoints {a : α} : a ∈ fixedPoints M α ↔ ∀ m : M, m • a = a := Iff.rfl @[to_additive (attr := simp)] theorem mem_fixedBy {m : M} {a : α} : a ∈ fixedBy α m ↔ m • a = a := Iff.rfl @[to_additive] theorem mem_fixedPoints' {a : α} : a ∈ fixedPoints M α ↔ ∀ a', a' ∈ orbit M a → a' = a := ⟨fun h _ h₁ => let ⟨m, hm⟩ := mem_orbit_iff.1 h₁ hm ▸ h m, fun h _ => h _ (mem_orbit _ _)⟩ end FixedPoints section Stabilizers variable {α} /-- The stabilizer of a point `a` as a submonoid of `M`. -/ @[to_additive /-- The stabilizer of a point `a` as an additive submonoid of `M`. -/] def stabilizerSubmonoid (a : α) : Submonoid M where carrier := { m | m • a = a } one_mem' := one_smul _ a mul_mem' {m m'} (ha : m • a = a) (hb : m' • a = a) := show (m * m') • a = a by rw [← smul_smul, hb, ha] variable {M} @[to_additive] instance [DecidableEq α] (a : α) : DecidablePred (· ∈ stabilizerSubmonoid M a) := fun _ => inferInstanceAs <| Decidable (_ = _) @[to_additive (attr := simp)] theorem mem_stabilizerSubmonoid_iff {a : α} {m : M} : m ∈ stabilizerSubmonoid M a ↔ m • a = a := Iff.rfl end Stabilizers end MulAction section FixedPoints variable (M : Type u) (α : Type v) [Monoid M] section Monoid variable [Monoid α] [MulDistribMulAction M α] /-- The submonoid of elements fixed under the whole action. -/ def FixedPoints.submonoid : Submonoid α where carrier := MulAction.fixedPoints M α one_mem' := smul_one mul_mem' ha hb _ := by rw [smul_mul', ha, hb] @[simp] lemma FixedPoints.mem_submonoid (a : α) : a ∈ submonoid M α ↔ ∀ m : M, m • a = a := Iff.rfl end Monoid section Group namespace FixedPoints variable [Group α] [MulDistribMulAction M α] /-- The subgroup of elements fixed under the whole action. -/ def subgroup : Subgroup α where __ := submonoid M α inv_mem' ha _ := by rw [smul_inv', ha] /-- The notation for `FixedPoints.subgroup`, chosen to resemble `αᴹ`. -/ scoped notation α "^*" M:51 => FixedPoints.subgroup M α @[simp] lemma mem_subgroup (a : α) : a ∈ α^*M ↔ ∀ m : M, m • a = a := Iff.rfl @[simp] lemma subgroup_toSubmonoid : (α^*M).toSubmonoid = submonoid M α := rfl end FixedPoints end Group end FixedPoints namespace MulAction variable {G α β : Type*} [Group G] [MulAction G α] [MulAction G β] section Orbit @[to_additive (attr := simp)] theorem orbit_smul (g : G) (a : α) : orbit G (g • a) = orbit G a := (orbit_smul_subset g a).antisymm <| calc orbit G a = orbit G (g⁻¹ • g • a) := by rw [inv_smul_smul] _ ⊆ orbit G (g • a) := orbit_smul_subset _ _ @[to_additive] theorem orbit_eq_iff {a b : α} : orbit G a = orbit G b ↔ a ∈ orbit G b := ⟨fun h => h ▸ mem_orbit_self _, fun ⟨_, hc⟩ => hc ▸ orbit_smul _ _⟩ @[to_additive] theorem mem_orbit_smul (g : G) (a : α) : a ∈ orbit G (g • a) := by simp only [orbit_smul, mem_orbit_self] @[to_additive] theorem smul_mem_orbit_smul (g h : G) (a : α) : g • a ∈ orbit G (h • a) := by simp only [orbit_smul, mem_orbit] @[to_additive] instance instMulAction (H : Subgroup G) : MulAction H α := inferInstanceAs (MulAction H.toSubmonoid α) @[to_additive] lemma subgroup_smul_def {H : Subgroup G} (a : H) (b : α) : a • b = (a : G) • b := rfl @[to_additive] lemma orbit_subgroup_subset (H : Subgroup G) (a : α) : orbit H a ⊆ orbit G a := orbit_submonoid_subset H.toSubmonoid a @[to_additive] lemma mem_orbit_of_mem_orbit_subgroup {H : Subgroup G} {a b : α} (h : a ∈ orbit H b) : a ∈ orbit G b := orbit_subgroup_subset H _ h @[to_additive] lemma mem_orbit_symm {a₁ a₂ : α} : a₁ ∈ orbit G a₂ ↔ a₂ ∈ orbit G a₁ := by simp_rw [← orbit_eq_iff, eq_comm] @[to_additive] lemma mem_subgroup_orbit_iff {H : Subgroup G} {x : α} {a b : orbit G x} : a ∈ MulAction.orbit H b ↔ (a : α) ∈ MulAction.orbit H (b : α) := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rcases h with ⟨g, rfl⟩ exact MulAction.mem_orbit _ g · rcases h with ⟨g, h⟩ dsimp at h rw [subgroup_smul_def, ← orbit.coe_smul, ← Subtype.ext_iff] at h subst h exact MulAction.mem_orbit _ g variable (G α) /-- The relation 'in the same orbit'. -/ @[to_additive /-- The relation 'in the same orbit'. -/] def orbitRel : Setoid α where r a b := a ∈ orbit G b iseqv := ⟨mem_orbit_self, fun {a b} => by simp [orbit_eq_iff.symm, eq_comm], fun {a b} => by simp +contextual [orbit_eq_iff.symm]⟩ variable {G α} @[to_additive] theorem orbitRel_apply {a b : α} : orbitRel G α a b ↔ a ∈ orbit G b := Iff.rfl /-- When you take a set `U` in `α`, push it down to the quotient, and pull back, you get the union of the orbit of `U` under `G`. -/ @[to_additive /-- When you take a set `U` in `α`, push it down to the quotient, and pull back, you get the union of the orbit of `U` under `G`. -/] theorem quotient_preimage_image_eq_union_mul (U : Set α) : letI := orbitRel G α Quotient.mk' ⁻¹' (Quotient.mk' '' U) = ⋃ g : G, (g • ·) '' U := by letI := orbitRel G α set f : α → Quotient (MulAction.orbitRel G α) := Quotient.mk' ext a constructor · rintro ⟨b, hb, hab⟩ obtain ⟨g, rfl⟩ := Quotient.exact hab rw [Set.mem_iUnion] exact ⟨g⁻¹, g • a, hb, inv_smul_smul g a⟩ · intro hx rw [Set.mem_iUnion] at hx obtain ⟨g, u, hu₁, hu₂⟩ := hx rw [Set.mem_preimage, Set.mem_image] refine ⟨g⁻¹ • a, ?_, by simp [f, orbitRel, Quotient.eq']⟩ rw [← hu₂] convert hu₁ simp only [inv_smul_smul] @[to_additive] theorem disjoint_image_image_iff {U V : Set α} : letI := orbitRel G α Disjoint (Quotient.mk' '' U) (Quotient.mk' '' V) ↔ ∀ x ∈ U, ∀ g : G, g • x ∉ V := by letI := orbitRel G α set f : α → Quotient (MulAction.orbitRel G α) := Quotient.mk' refine ⟨fun h a a_in_U g g_in_V => h.le_bot ⟨⟨a, a_in_U, Quotient.sound ⟨g⁻¹, ?_⟩⟩, ⟨g • a, g_in_V, rfl⟩⟩, ?_⟩ · simp · intro h rw [Set.disjoint_left] rintro _ ⟨b, hb₁, hb₂⟩ ⟨c, hc₁, hc₂⟩ obtain ⟨g, rfl⟩ := Quotient.exact (hc₂.trans hb₂.symm) exact h b hb₁ g hc₁ @[to_additive] theorem image_inter_image_iff (U V : Set α) : letI := orbitRel G α Quotient.mk' '' U ∩ Quotient.mk' '' V = ∅ ↔ ∀ x ∈ U, ∀ g : G, g • x ∉ V := Set.disjoint_iff_inter_eq_empty.symm.trans disjoint_image_image_iff variable (G α) /-- The quotient by `MulAction.orbitRel`, given a name to enable dot notation. -/ @[to_additive /-- The quotient by `AddAction.orbitRel`, given a name to enable dot notation. -/] abbrev orbitRel.Quotient : Type _ := _root_.Quotient <| orbitRel G α variable {G α} /-- The orbit corresponding to an element of the quotient by `MulAction.orbitRel` -/ @[to_additive /-- The orbit corresponding to an element of the quotient by `AddAction.orbitRel` -/] nonrec def orbitRel.Quotient.orbit (x : orbitRel.Quotient G α) : Set α := Quotient.liftOn' x (orbit G) fun _ _ => MulAction.orbit_eq_iff.2 @[to_additive (attr := simp)] theorem orbitRel.Quotient.orbit_mk (a : α) : orbitRel.Quotient.orbit (Quotient.mk'' a : orbitRel.Quotient G α) = MulAction.orbit G a := rfl @[to_additive] theorem orbitRel.Quotient.mem_orbit {a : α} {x : orbitRel.Quotient G α} : a ∈ x.orbit ↔ Quotient.mk'' a = x := by induction x using Quotient.inductionOn' rw [Quotient.eq''] rfl /-- Note that `hφ = Quotient.out_eq'` is a useful choice here. -/ @[to_additive /-- Note that `hφ = Quotient.out_eq'` is a useful choice here. -/] theorem orbitRel.Quotient.orbit_eq_orbit_out (x : orbitRel.Quotient G α) {φ : orbitRel.Quotient G α → α} (hφ : letI := orbitRel G α; RightInverse φ Quotient.mk') : orbitRel.Quotient.orbit x = MulAction.orbit G (φ x) := by conv_lhs => rw [← hφ x] rfl @[to_additive] lemma orbitRel.Quotient.orbit_injective : Injective (orbitRel.Quotient.orbit : orbitRel.Quotient G α → Set α) := by intro x y h simp_rw [orbitRel.Quotient.orbit_eq_orbit_out _ Quotient.out_eq', orbit_eq_iff, ← orbitRel_apply] at h simpa [← Quotient.eq''] using h @[to_additive (attr := simp)] lemma orbitRel.Quotient.orbit_inj {x y : orbitRel.Quotient G α} : x.orbit = y.orbit ↔ x = y := orbitRel.Quotient.orbit_injective.eq_iff @[to_additive] lemma orbitRel.quotient_eq_of_quotient_subgroup_eq {H : Subgroup G} {a b : α} (h : (⟦a⟧ : orbitRel.Quotient H α) = ⟦b⟧) : (⟦a⟧ : orbitRel.Quotient G α) = ⟦b⟧ := by rw [@Quotient.eq] at h ⊢ exact mem_orbit_of_mem_orbit_subgroup h @[to_additive] lemma orbitRel.quotient_eq_of_quotient_subgroup_eq' {H : Subgroup G} {a b : α} (h : (Quotient.mk'' a : orbitRel.Quotient H α) = Quotient.mk'' b) : (Quotient.mk'' a : orbitRel.Quotient G α) = Quotient.mk'' b := orbitRel.quotient_eq_of_quotient_subgroup_eq h @[to_additive] nonrec lemma orbitRel.Quotient.orbit_nonempty (x : orbitRel.Quotient G α) : Set.Nonempty x.orbit := by rw [orbitRel.Quotient.orbit_eq_orbit_out x Quotient.out_eq'] exact orbit_nonempty _ @[to_additive] nonrec lemma orbitRel.Quotient.mapsTo_smul_orbit (g : G) (x : orbitRel.Quotient G α) : Set.MapsTo (g • ·) x.orbit x.orbit := by rw [orbitRel.Quotient.orbit_eq_orbit_out x Quotient.out_eq'] exact mapsTo_smul_orbit g x.out @[to_additive] instance (x : orbitRel.Quotient G α) : MulAction G x.orbit where smul g := (orbitRel.Quotient.mapsTo_smul_orbit g x).restrict _ _ _ one_smul a := Subtype.ext (one_smul G (a : α)) mul_smul g g' a' := Subtype.ext (mul_smul g g' (a' : α)) @[to_additive (attr := simp)] lemma orbitRel.Quotient.orbit.coe_smul {g : G} {x : orbitRel.Quotient G α} {a : x.orbit} : ↑(g • a) = g • (a : α) := rfl @[to_additive (attr := norm_cast, simp)] lemma orbitRel.Quotient.mem_subgroup_orbit_iff {H : Subgroup G} {x : orbitRel.Quotient G α} {a b : x.orbit} : (a : α) ∈ MulAction.orbit H (b : α) ↔ a ∈ MulAction.orbit H b := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · rcases h with ⟨g, h⟩ dsimp at h rw [subgroup_smul_def, ← orbit.coe_smul, ← Subtype.ext_iff] at h subst h exact MulAction.mem_orbit _ g · rcases h with ⟨g, rfl⟩ exact MulAction.mem_orbit _ g @[to_additive] lemma orbitRel.Quotient.subgroup_quotient_eq_iff {H : Subgroup G} {x : orbitRel.Quotient G α} {a b : x.orbit} : (⟦a⟧ : orbitRel.Quotient H x.orbit) = ⟦b⟧ ↔ (⟦↑a⟧ : orbitRel.Quotient H α) = ⟦↑b⟧ := by simp_rw [← @Quotient.mk''_eq_mk, Quotient.eq''] exact orbitRel.Quotient.mem_subgroup_orbit_iff.symm @[to_additive] lemma orbitRel.Quotient.mem_subgroup_orbit_iff' {H : Subgroup G} {x : orbitRel.Quotient G α} {a b : x.orbit} {c : α} (h : (⟦a⟧ : orbitRel.Quotient H x.orbit) = ⟦b⟧) : (a : α) ∈ MulAction.orbit H c ↔ (b : α) ∈ MulAction.orbit H c := by simp_rw [mem_orbit_symm (a₂ := c)] convert Iff.rfl using 2 rw [orbit_eq_iff] suffices hb : ↑b ∈ orbitRel.Quotient.orbit (⟦a⟧ : orbitRel.Quotient H x.orbit) by rw [orbitRel.Quotient.orbit_eq_orbit_out (⟦a⟧ : orbitRel.Quotient H x.orbit) Quotient.out_eq'] at hb rw [orbitRel.Quotient.mem_subgroup_orbit_iff] convert hb using 1 rw [orbit_eq_iff, ← orbitRel_apply, ← Quotient.eq'', Quotient.out_eq', @Quotient.mk''_eq_mk] rw [orbitRel.Quotient.mem_orbit, h, @Quotient.mk''_eq_mk] variable (G) (α) local notation "Ω" => orbitRel.Quotient G α /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. This version is expressed in terms of `MulAction.orbitRel.Quotient.orbit` instead of `MulAction.orbit`, to avoid mentioning `Quotient.out`. -/ @[to_additive /-- Decomposition of a type `X` as a disjoint union of its orbits under an additive group action. This version is expressed in terms of `AddAction.orbitRel.Quotient.orbit` instead of `AddAction.orbit`, to avoid mentioning `Quotient.out`. -/] def selfEquivSigmaOrbits' : α ≃ Σ ω : Ω, ω.orbit := letI := orbitRel G α calc α ≃ Σ ω : Ω, { a // Quotient.mk' a = ω } := (Equiv.sigmaFiberEquiv Quotient.mk').symm _ ≃ Σ ω : Ω, ω.orbit := Equiv.sigmaCongrRight fun _ => Equiv.subtypeEquivRight fun _ => orbitRel.Quotient.mem_orbit.symm /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. -/ @[to_additive /-- Decomposition of a type `X` as a disjoint union of its orbits under an additive group action. -/] def selfEquivSigmaOrbits : α ≃ Σ ω : Ω, orbit G ω.out := (selfEquivSigmaOrbits' G α).trans <| Equiv.sigmaCongrRight fun _ => Equiv.setCongr <| orbitRel.Quotient.orbit_eq_orbit_out _ Quotient.out_eq' /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. Phrased as a set union. See `MulAction.selfEquivSigmaOrbits` for the type isomorphism. -/ @[to_additive /-- Decomposition of a type `X` as a disjoint union of its orbits under an additive group action. Phrased as a set union. See `AddAction.selfEquivSigmaOrbits` for the type isomorphism. -/] lemma univ_eq_iUnion_orbit : Set.univ (α := α) = ⋃ x : Ω, x.orbit := by ext x simp only [Set.mem_univ, Set.mem_iUnion, true_iff] exact ⟨Quotient.mk'' x, by simp⟩ end Orbit section Stabilizer variable (G) in /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup. -/ @[to_additive /-- The stabilizer of an element under an action, i.e. what sends the element to itself. An additive subgroup. -/] def stabilizer (a : α) : Subgroup G := { stabilizerSubmonoid G a with inv_mem' := fun {m} (ha : m • a = a) => show m⁻¹ • a = a by rw [inv_smul_eq_iff, ha] } @[to_additive] instance [DecidableEq α] (a : α) : DecidablePred (· ∈ stabilizer G a) := fun _ => inferInstanceAs <| Decidable (_ = _) @[to_additive (attr := simp)] theorem mem_stabilizer_iff {a : α} {g : G} : g ∈ stabilizer G a ↔ g • a = a := Iff.rfl @[to_additive] lemma le_stabilizer_smul_left [SMul α β] [IsScalarTower G α β] (a : α) (b : β) : stabilizer G a ≤ stabilizer G (a • b) := by simp_rw [SetLike.le_def, mem_stabilizer_iff, ← smul_assoc]; rintro a h; rw [h] -- This lemma does not need `MulAction G α`, only `SMul G α`. -- We use `G'` instead of `G` to locally reduce the typeclass assumptions. @[to_additive] lemma le_stabilizer_smul_right {G'} [Group G'] [SMul α β] [MulAction G' β] [SMulCommClass G' α β] (a : α) (b : β) : stabilizer G' b ≤ stabilizer G' (a • b) := by simp_rw [SetLike.le_def, mem_stabilizer_iff, smul_comm]; rintro a h; rw [h] @[to_additive (attr := simp)] lemma stabilizer_smul_eq_left [SMul α β] [IsScalarTower G α β] (a : α) (b : β) (h : Injective (· • b : α → β)) : stabilizer G (a • b) = stabilizer G a := by refine (le_stabilizer_smul_left _ _).antisymm' fun a ha ↦ ?_ simpa only [mem_stabilizer_iff, ← smul_assoc, h.eq_iff] using ha @[to_additive (attr := simp)] lemma stabilizer_smul_eq_right {α} [Group α] [MulAction α β] [SMulCommClass G α β] (a : α) (b : β) : stabilizer G (a • b) = stabilizer G b := (le_stabilizer_smul_right _ _).antisymm' <| (le_stabilizer_smul_right a⁻¹ _).trans_eq <| by rw [inv_smul_smul] @[to_additive (attr := simp)] lemma stabilizer_mul_eq_left [Group α] [IsScalarTower G α α] (a b : α) : stabilizer G (a * b) = stabilizer G a := stabilizer_smul_eq_left a _ <| mul_left_injective _ @[to_additive (attr := simp)] lemma stabilizer_mul_eq_right [Group α] [SMulCommClass G α α] (a b : α) : stabilizer G (a * b) = stabilizer G b := stabilizer_smul_eq_right a _ end Stabilizer end MulAction
Interval.lean
/- Copyright (c) 2024 Vincent Beffara. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Vincent Beffara -/ import Mathlib.Topology.CompactOpen import Mathlib.Topology.Order.ProjIcc /-! # Continuous bundled maps on intervals In this file we prove a few results about `ContinuousMap` when the domain is an interval. -/ open Set ContinuousMap Filter Topology namespace ContinuousMap variable {α : Type*} [LinearOrder α] [TopologicalSpace α] [OrderTopology α] variable {a b c : α} [Fact (a ≤ b)] [Fact (b ≤ c)] variable {E : Type*} [TopologicalSpace E] /-- The embedding into an interval from a sub-interval lying on the left, as a `ContinuousMap`. -/ def IccInclusionLeft : C(Icc a b, Icc a c) := .inclusion <| Icc_subset_Icc le_rfl Fact.out /-- The embedding into an interval from a sub-interval lying on the right, as a `ContinuousMap`. -/ def IccInclusionRight : C(Icc b c, Icc a c) := .inclusion <| Icc_subset_Icc Fact.out le_rfl /-- The map `projIcc` from `α` onto an interval in `α`, as a `ContinuousMap`. -/ def projIccCM : C(α, Icc a b) := ⟨projIcc a b Fact.out, continuous_projIcc⟩ /-- The extension operation from continuous maps on an interval to continuous maps on the whole type, as a `ContinuousMap`. -/ def IccExtendCM : C(C(Icc a b, E), C(α, E)) where toFun f := f.comp projIccCM continuous_toFun := continuous_precomp projIccCM @[simp] theorem IccExtendCM_of_mem {f : C(Icc a b, E)} {x : α} (hx : x ∈ Icc a b) : IccExtendCM f x = f ⟨x, hx⟩ := by simp [IccExtendCM, projIccCM, projIcc, hx.1, hx.2] /-- The concatenation of two continuous maps defined on adjacent intervals. If the values of the functions on the common bound do not agree, this is defined as an arbitrarily chosen constant map. See `concatCM` for the corresponding map on the subtype of compatible function pairs. -/ noncomputable def concat (f : C(Icc a b, E)) (g : C(Icc b c, E)) : C(Icc a c, E) := by by_cases hb : f ⊤ = g ⊥ · let h (t : α) : E := if t ≤ b then IccExtendCM f t else IccExtendCM g t suffices Continuous h from ⟨fun t => h t, by fun_prop⟩ apply Continuous.if_le (by fun_prop) (by fun_prop) continuous_id continuous_const rintro x rfl simpa [IccExtendCM, projIccCM] · exact .const _ (f ⊥) -- junk value variable {f : C(Icc a b, E)} {g : C(Icc b c, E)} theorem concat_comp_IccInclusionLeft (hb : f ⊤ = g ⊥) : (concat f g).comp IccInclusionLeft = f := by ext x simp [concat, IccExtendCM, hb, IccInclusionLeft, projIccCM, inclusion, x.2.2] theorem concat_comp_IccInclusionRight (hb : f ⊤ = g ⊥) : (concat f g).comp IccInclusionRight = g := by ext ⟨x, hx⟩ obtain rfl | hxb := eq_or_ne x b · simpa [concat, IccInclusionRight, IccExtendCM, projIccCM, inclusion, hb] · have h : ¬ x ≤ b := lt_of_le_of_ne hx.1 (Ne.symm hxb) |>.not_ge simp [concat, hb, IccInclusionRight, h, IccExtendCM, projIccCM, projIcc, inclusion, hx.2, hx.1] @[simp] theorem concat_left (hb : f ⊤ = g ⊥) {t : Icc a c} (ht : t ≤ b) : concat f g t = f ⟨t, t.2.1, ht⟩ := by nth_rewrite 2 [← concat_comp_IccInclusionLeft hb] rfl @[simp] theorem concat_right (hb : f ⊤ = g ⊥) {t : Icc a c} (ht : b ≤ t) : concat f g t = g ⟨t, ht, t.2.2⟩ := by nth_rewrite 2 [← concat_comp_IccInclusionRight hb] rfl theorem tendsto_concat {ι : Type*} {p : Filter ι} {F : ι → C(Icc a b, E)} {G : ι → C(Icc b c, E)} (hfg : ∀ᶠ i in p, (F i) ⊤ = (G i) ⊥) (hfg' : f ⊤ = g ⊥) (hf : Tendsto F p (𝓝 f)) (hg : Tendsto G p (𝓝 g)) : Tendsto (fun i => concat (F i) (G i)) p (𝓝 (concat f g)) := by rw [tendsto_nhds_compactOpen] at hf hg ⊢ rintro K hK U hU hfgU have h : b ∈ Icc a c := ⟨Fact.out, Fact.out⟩ let K₁ : Set (Icc a b) := projIccCM '' (Subtype.val '' (K ∩ Iic ⟨b, h⟩)) let K₂ : Set (Icc b c) := projIccCM '' (Subtype.val '' (K ∩ Ici ⟨b, h⟩)) have hK₁ : IsCompact K₁ := hK.inter_right isClosed_Iic |>.image continuous_subtype_val |>.image projIccCM.continuous have hK₂ : IsCompact K₂ := hK.inter_right isClosed_Ici |>.image continuous_subtype_val |>.image projIccCM.continuous have hfU : MapsTo f K₁ U := by rw [← concat_comp_IccInclusionLeft hfg'] apply hfgU.comp rintro x ⟨y, ⟨⟨z, hz⟩, ⟨h1, (h2 : z ≤ b)⟩, rfl⟩, rfl⟩ simpa [projIccCM, projIcc, h2, hz.1] using h1 have hgU : MapsTo g K₂ U := by rw [← concat_comp_IccInclusionRight hfg'] apply hfgU.comp rintro x ⟨y, ⟨⟨z, hz⟩, ⟨h1, (h2 : b ≤ z)⟩, rfl⟩, rfl⟩ simpa [projIccCM, projIcc, h2, hz.2] using h1 filter_upwards [hf K₁ hK₁ U hU hfU, hg K₂ hK₂ U hU hgU, hfg] with i hf hg hfg x hx by_cases hxb : x ≤ b · rw [concat_left hfg hxb] refine hf ⟨x, ⟨x, ⟨hx, hxb⟩, rfl⟩, ?_⟩ simp [projIccCM, projIcc, hxb, x.2.1] · replace hxb : b ≤ x := lt_of_not_ge hxb |>.le rw [concat_right hfg hxb] refine hg ⟨x, ⟨x, ⟨hx, hxb⟩, rfl⟩, ?_⟩ simp [projIccCM, projIcc, hxb, x.2.2] /-- The concatenation of compatible pairs of continuous maps on adjacent intervals, defined as a `ContinuousMap` on a subtype of the product. -/ noncomputable def concatCM : C({fg : C(Icc a b, E) × C(Icc b c, E) // fg.1 ⊤ = fg.2 ⊥}, C(Icc a c, E)) where toFun fg := concat fg.val.1 fg.val.2 continuous_toFun := by let S : Set (C(Icc a b, E) × C(Icc b c, E)) := {fg | fg.1 ⊤ = fg.2 ⊥} change Continuous (S.restrict concat.uncurry) refine continuousOn_iff_continuous_restrict.mp (fun fg hfg => ?_) refine tendsto_concat ?_ hfg ?_ ?_ · exact eventually_nhdsWithin_of_forall (fun _ => id) · exact tendsto_nhdsWithin_of_tendsto_nhds continuousAt_fst · exact tendsto_nhdsWithin_of_tendsto_nhds continuousAt_snd @[simp] theorem concatCM_left {x : Icc a c} (hx : x ≤ b) {fg : {fg : C(Icc a b, E) × C(Icc b c, E) // fg.1 ⊤ = fg.2 ⊥}} : concatCM fg x = fg.1.1 ⟨x.1, x.2.1, hx⟩ := by exact concat_left fg.2 hx @[simp] theorem concatCM_right {x : Icc a c} (hx : b ≤ x) {fg : {fg : C(Icc a b, E) × C(Icc b c, E) // fg.1 ⊤ = fg.2 ⊥}} : concatCM fg x = fg.1.2 ⟨x.1, hx, x.2.2⟩ := concat_right fg.2 hx end ContinuousMap
Basic.lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import Mathlib.Algebra.Group.Action.Units import Mathlib.Algebra.Group.Nat.Units import Mathlib.Algebra.GroupWithZero.Divisibility import Mathlib.Algebra.Ring.Divisibility.Basic import Mathlib.Algebra.Ring.Hom.Defs import Mathlib.Logic.Basic import Mathlib.Tactic.Ring /-! # Coprime elements of a ring or monoid ## Main definition * `IsCoprime x y`: that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors (`IsRelPrime`) are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. The two notions are equivalent in Bézout rings, see `isRelPrime_iff_isCoprime`. This file also contains lemmas about `IsRelPrime` parallel to `IsCoprime`. See also `RingTheory.Coprime.Lemmas` for further development of coprime elements. -/ universe u v section CommSemiring variable {R : Type u} [CommSemiring R] (x y z : R) /-- The proposition that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ def IsCoprime : Prop := ∃ a b, a * x + b * y = 1 variable {x y z} @[symm] theorem IsCoprime.symm (H : IsCoprime x y) : IsCoprime y x := let ⟨a, b, H⟩ := H ⟨b, a, by rw [add_comm, H]⟩ theorem isCoprime_comm : IsCoprime x y ↔ IsCoprime y x := ⟨IsCoprime.symm, IsCoprime.symm⟩ theorem isCoprime_self : IsCoprime x x ↔ IsUnit x := ⟨fun ⟨a, b, h⟩ => isUnit_of_mul_eq_one x (a + b) <| by rwa [mul_comm, add_mul], fun h => let ⟨b, hb⟩ := isUnit_iff_exists_inv'.1 h ⟨b, 0, by rwa [zero_mul, add_zero]⟩⟩ theorem isCoprime_zero_left : IsCoprime 0 x ↔ IsUnit x := ⟨fun ⟨a, b, H⟩ => isUnit_of_mul_eq_one x b <| by rwa [mul_zero, zero_add, mul_comm] at H, fun H => let ⟨b, hb⟩ := isUnit_iff_exists_inv'.1 H ⟨1, b, by rwa [one_mul, zero_add]⟩⟩ theorem isCoprime_zero_right : IsCoprime x 0 ↔ IsUnit x := isCoprime_comm.trans isCoprime_zero_left theorem not_isCoprime_zero_zero [Nontrivial R] : ¬IsCoprime (0 : R) 0 := mt isCoprime_zero_right.mp not_isUnit_zero lemma IsCoprime.intCast {R : Type*} [CommRing R] {a b : ℤ} (h : IsCoprime a b) : IsCoprime (a : R) (b : R) := by rcases h with ⟨u, v, H⟩ use u, v rw_mod_cast [H] exact Int.cast_one /-- If a 2-vector `p` satisfies `IsCoprime (p 0) (p 1)`, then `p ≠ 0`. -/ theorem IsCoprime.ne_zero [Nontrivial R] {p : Fin 2 → R} (h : IsCoprime (p 0) (p 1)) : p ≠ 0 := by rintro rfl exact not_isCoprime_zero_zero h theorem IsCoprime.ne_zero_or_ne_zero [Nontrivial R] (h : IsCoprime x y) : x ≠ 0 ∨ y ≠ 0 := by apply not_or_of_imp rintro rfl rfl exact not_isCoprime_zero_zero h theorem isCoprime_one_left : IsCoprime 1 x := ⟨1, 0, by rw [one_mul, zero_mul, add_zero]⟩ theorem isCoprime_one_right : IsCoprime x 1 := ⟨0, 1, by rw [one_mul, zero_mul, zero_add]⟩ theorem IsCoprime.dvd_of_dvd_mul_right (H1 : IsCoprime x z) (H2 : x ∣ y * z) : x ∣ y := by let ⟨a, b, H⟩ := H1 rw [← mul_one y, ← H, mul_add, ← mul_assoc, mul_left_comm] exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) theorem IsCoprime.dvd_of_dvd_mul_left (H1 : IsCoprime x y) (H2 : x ∣ y * z) : x ∣ z := by let ⟨a, b, H⟩ := H1 rw [← one_mul z, ← H, add_mul, mul_right_comm, mul_assoc b] exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) theorem IsCoprime.mul_left (H1 : IsCoprime x z) (H2 : IsCoprime y z) : IsCoprime (x * y) z := let ⟨a, b, h1⟩ := H1 let ⟨c, d, h2⟩ := H2 ⟨a * c, a * x * d + b * c * y + b * d * z, calc a * c * (x * y) + (a * x * d + b * c * y + b * d * z) * z _ = (a * x + b * z) * (c * y + d * z) := by ring _ = 1 := by rw [h1, h2, mul_one] ⟩ theorem IsCoprime.mul_right (H1 : IsCoprime x y) (H2 : IsCoprime x z) : IsCoprime x (y * z) := by rw [isCoprime_comm] at H1 H2 ⊢ exact H1.mul_left H2 theorem IsCoprime.mul_dvd (H : IsCoprime x y) (H1 : x ∣ z) (H2 : y ∣ z) : x * y ∣ z := by obtain ⟨a, b, h⟩ := H rw [← mul_one z, ← h, mul_add] apply dvd_add · rw [mul_comm z, mul_assoc] exact (mul_dvd_mul_left _ H2).mul_left _ · rw [mul_comm b, ← mul_assoc] exact (mul_dvd_mul_right H1 _).mul_right _ theorem IsCoprime.of_mul_left_left (H : IsCoprime (x * y) z) : IsCoprime x z := let ⟨a, b, h⟩ := H ⟨a * y, b, by rwa [mul_right_comm, mul_assoc]⟩ theorem IsCoprime.of_mul_left_right (H : IsCoprime (x * y) z) : IsCoprime y z := by rw [mul_comm] at H exact H.of_mul_left_left theorem IsCoprime.of_mul_right_left (H : IsCoprime x (y * z)) : IsCoprime x y := by rw [isCoprime_comm] at H ⊢ exact H.of_mul_left_left theorem IsCoprime.of_mul_right_right (H : IsCoprime x (y * z)) : IsCoprime x z := by rw [mul_comm] at H exact H.of_mul_right_left theorem IsCoprime.mul_left_iff : IsCoprime (x * y) z ↔ IsCoprime x z ∧ IsCoprime y z := ⟨fun H => ⟨H.of_mul_left_left, H.of_mul_left_right⟩, fun ⟨H1, H2⟩ => H1.mul_left H2⟩ theorem IsCoprime.mul_right_iff : IsCoprime x (y * z) ↔ IsCoprime x y ∧ IsCoprime x z := by rw [isCoprime_comm, IsCoprime.mul_left_iff, isCoprime_comm, @isCoprime_comm _ _ z] theorem IsCoprime.of_isCoprime_of_dvd_left (h : IsCoprime y z) (hdvd : x ∣ y) : IsCoprime x z := by obtain ⟨d, rfl⟩ := hdvd exact IsCoprime.of_mul_left_left h theorem IsCoprime.of_isCoprime_of_dvd_right (h : IsCoprime z y) (hdvd : x ∣ y) : IsCoprime z x := (h.symm.of_isCoprime_of_dvd_left hdvd).symm theorem IsCoprime.isUnit_of_dvd (H : IsCoprime x y) (d : x ∣ y) : IsUnit x := let ⟨k, hk⟩ := d isCoprime_self.1 <| IsCoprime.of_mul_right_left <| show IsCoprime x (x * k) from hk ▸ H theorem IsCoprime.isUnit_of_dvd' {a b x : R} (h : IsCoprime a b) (ha : x ∣ a) (hb : x ∣ b) : IsUnit x := (h.of_isCoprime_of_dvd_left ha).isUnit_of_dvd hb theorem IsCoprime.isRelPrime {a b : R} (h : IsCoprime a b) : IsRelPrime a b := fun _ ↦ h.isUnit_of_dvd' theorem IsCoprime.map (H : IsCoprime x y) {S : Type v} [CommSemiring S] (f : R →+* S) : IsCoprime (f x) (f y) := let ⟨a, b, h⟩ := H ⟨f a, f b, by rw [← f.map_mul, ← f.map_mul, ← f.map_add, h, f.map_one]⟩ theorem IsCoprime.of_add_mul_left_left (h : IsCoprime (x + y * z) y) : IsCoprime x y := let ⟨a, b, H⟩ := h ⟨a, a * z + b, by simpa only [add_mul, mul_add, add_assoc, add_comm, add_left_comm, mul_assoc, mul_comm, mul_left_comm] using H⟩ theorem IsCoprime.of_add_mul_right_left (h : IsCoprime (x + z * y) y) : IsCoprime x y := by rw [mul_comm] at h exact h.of_add_mul_left_left theorem IsCoprime.of_add_mul_left_right (h : IsCoprime x (y + x * z)) : IsCoprime x y := by rw [isCoprime_comm] at h ⊢ exact h.of_add_mul_left_left theorem IsCoprime.of_add_mul_right_right (h : IsCoprime x (y + z * x)) : IsCoprime x y := by rw [mul_comm] at h exact h.of_add_mul_left_right theorem IsCoprime.of_mul_add_left_left (h : IsCoprime (y * z + x) y) : IsCoprime x y := by rw [add_comm] at h exact h.of_add_mul_left_left theorem IsCoprime.of_mul_add_right_left (h : IsCoprime (z * y + x) y) : IsCoprime x y := by rw [add_comm] at h exact h.of_add_mul_right_left theorem IsCoprime.of_mul_add_left_right (h : IsCoprime x (x * z + y)) : IsCoprime x y := by rw [add_comm] at h exact h.of_add_mul_left_right theorem IsCoprime.of_mul_add_right_right (h : IsCoprime x (z * x + y)) : IsCoprime x y := by rw [add_comm] at h exact h.of_add_mul_right_right theorem IsRelPrime.of_add_mul_left_left (h : IsRelPrime (x + y * z) y) : IsRelPrime x y := fun _ hx hy ↦ h (dvd_add hx <| dvd_mul_of_dvd_left hy z) hy theorem IsRelPrime.of_add_mul_right_left (h : IsRelPrime (x + z * y) y) : IsRelPrime x y := (mul_comm z y ▸ h).of_add_mul_left_left theorem IsRelPrime.of_add_mul_left_right (h : IsRelPrime x (y + x * z)) : IsRelPrime x y := by rw [isRelPrime_comm] at h ⊢ exact h.of_add_mul_left_left theorem IsRelPrime.of_add_mul_right_right (h : IsRelPrime x (y + z * x)) : IsRelPrime x y := (mul_comm z x ▸ h).of_add_mul_left_right theorem IsRelPrime.of_mul_add_left_left (h : IsRelPrime (y * z + x) y) : IsRelPrime x y := (add_comm _ x ▸ h).of_add_mul_left_left theorem IsRelPrime.of_mul_add_right_left (h : IsRelPrime (z * y + x) y) : IsRelPrime x y := (add_comm _ x ▸ h).of_add_mul_right_left theorem IsRelPrime.of_mul_add_left_right (h : IsRelPrime x (x * z + y)) : IsRelPrime x y := (add_comm _ y ▸ h).of_add_mul_left_right theorem IsRelPrime.of_mul_add_right_right (h : IsRelPrime x (z * x + y)) : IsRelPrime x y := (add_comm _ y ▸ h).of_add_mul_right_right end CommSemiring section ScalarTower variable {R G : Type*} [CommSemiring R] [Group G] [MulAction G R] [SMulCommClass G R R] [IsScalarTower G R R] (x : G) (y z : R) theorem isCoprime_group_smul_left : IsCoprime (x • y) z ↔ IsCoprime y z := ⟨fun ⟨a, b, h⟩ => ⟨x • a, b, by rwa [smul_mul_assoc, ← mul_smul_comm]⟩, fun ⟨a, b, h⟩ => ⟨x⁻¹ • a, b, by rwa [smul_mul_smul_comm, inv_mul_cancel, one_smul]⟩⟩ theorem isCoprime_group_smul_right : IsCoprime y (x • z) ↔ IsCoprime y z := isCoprime_comm.trans <| (isCoprime_group_smul_left x z y).trans isCoprime_comm theorem isCoprime_group_smul : IsCoprime (x • y) (x • z) ↔ IsCoprime y z := (isCoprime_group_smul_left x y (x • z)).trans (isCoprime_group_smul_right x y z) end ScalarTower section CommSemiringUnit variable {R : Type*} [CommSemiring R] {x u v : R} theorem isCoprime_mul_unit_left_left (hu : IsUnit x) (y z : R) : IsCoprime (x * y) z ↔ IsCoprime y z := let ⟨u, hu⟩ := hu hu ▸ isCoprime_group_smul_left u y z theorem isCoprime_mul_unit_left_right (hu : IsUnit x) (y z : R) : IsCoprime y (x * z) ↔ IsCoprime y z := let ⟨u, hu⟩ := hu hu ▸ isCoprime_group_smul_right u y z theorem isCoprime_mul_unit_right_left (hu : IsUnit x) (y z : R) : IsCoprime (y * x) z ↔ IsCoprime y z := mul_comm x y ▸ isCoprime_mul_unit_left_left hu y z theorem isCoprime_mul_unit_right_right (hu : IsUnit x) (y z : R) : IsCoprime y (z * x) ↔ IsCoprime y z := mul_comm x z ▸ isCoprime_mul_unit_left_right hu y z theorem isCoprime_mul_units_left (hu : IsUnit u) (hv : IsUnit v) (y z : R) : IsCoprime (u * y) (v * z) ↔ IsCoprime y z := Iff.trans (isCoprime_mul_unit_left_left hu _ _) (isCoprime_mul_unit_left_right hv _ _) theorem isCoprime_mul_units_right (hu : IsUnit u) (hv : IsUnit v) (y z : R) : IsCoprime (y * u) (z * v) ↔ IsCoprime y z := Iff.trans (isCoprime_mul_unit_right_left hu _ _) (isCoprime_mul_unit_right_right hv _ _) theorem isCoprime_mul_unit_left (hu : IsUnit x) (y z : R) : IsCoprime (x * y) (x * z) ↔ IsCoprime y z := isCoprime_mul_units_left hu hu _ _ theorem isCoprime_mul_unit_right (hu : IsUnit x) (y z : R) : IsCoprime (y * x) (z * x) ↔ IsCoprime y z := isCoprime_mul_units_right hu hu _ _ end CommSemiringUnit namespace IsCoprime section CommRing variable {R : Type u} [CommRing R] theorem add_mul_left_left {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) <| by simpa only [mul_neg, add_neg_cancel_right] using h theorem add_mul_right_left {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime (x + z * y) y := by rw [mul_comm] exact h.add_mul_left_left z theorem add_mul_left_right {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime x (y + x * z) := by rw [isCoprime_comm] exact h.symm.add_mul_left_left z theorem add_mul_right_right {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime x (y + z * x) := by rw [isCoprime_comm] exact h.symm.add_mul_right_left z theorem mul_add_left_left {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime (y * z + x) y := by rw [add_comm] exact h.add_mul_left_left z theorem mul_add_right_left {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime (z * y + x) y := by rw [add_comm] exact h.add_mul_right_left z theorem mul_add_left_right {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime x (x * z + y) := by rw [add_comm] exact h.add_mul_left_right z theorem mul_add_right_right {x y : R} (h : IsCoprime x y) (z : R) : IsCoprime x (z * x + y) := by rw [add_comm] exact h.add_mul_right_right z theorem add_mul_left_left_iff {x y z : R} : IsCoprime (x + y * z) y ↔ IsCoprime x y := ⟨of_add_mul_left_left, fun h => h.add_mul_left_left z⟩ theorem add_mul_right_left_iff {x y z : R} : IsCoprime (x + z * y) y ↔ IsCoprime x y := ⟨of_add_mul_right_left, fun h => h.add_mul_right_left z⟩ theorem add_mul_left_right_iff {x y z : R} : IsCoprime x (y + x * z) ↔ IsCoprime x y := ⟨of_add_mul_left_right, fun h => h.add_mul_left_right z⟩ theorem add_mul_right_right_iff {x y z : R} : IsCoprime x (y + z * x) ↔ IsCoprime x y := ⟨of_add_mul_right_right, fun h => h.add_mul_right_right z⟩ theorem mul_add_left_left_iff {x y z : R} : IsCoprime (y * z + x) y ↔ IsCoprime x y := ⟨of_mul_add_left_left, fun h => h.mul_add_left_left z⟩ theorem mul_add_right_left_iff {x y z : R} : IsCoprime (z * y + x) y ↔ IsCoprime x y := ⟨of_mul_add_right_left, fun h => h.mul_add_right_left z⟩ theorem mul_add_left_right_iff {x y z : R} : IsCoprime x (x * z + y) ↔ IsCoprime x y := ⟨of_mul_add_left_right, fun h => h.mul_add_left_right z⟩ theorem mul_add_right_right_iff {x y z : R} : IsCoprime x (z * x + y) ↔ IsCoprime x y := ⟨of_mul_add_right_right, fun h => h.mul_add_right_right z⟩ theorem neg_left {x y : R} (h : IsCoprime x y) : IsCoprime (-x) y := by obtain ⟨a, b, h⟩ := h use -a, b rwa [neg_mul_neg] theorem neg_left_iff (x y : R) : IsCoprime (-x) y ↔ IsCoprime x y := ⟨fun h => neg_neg x ▸ h.neg_left, neg_left⟩ theorem neg_right {x y : R} (h : IsCoprime x y) : IsCoprime x (-y) := h.symm.neg_left.symm theorem neg_right_iff (x y : R) : IsCoprime x (-y) ↔ IsCoprime x y := ⟨fun h => neg_neg y ▸ h.neg_right, neg_right⟩ theorem neg_neg {x y : R} (h : IsCoprime x y) : IsCoprime (-x) (-y) := h.neg_left.neg_right theorem neg_neg_iff (x y : R) : IsCoprime (-x) (-y) ↔ IsCoprime x y := (neg_left_iff _ _).trans (neg_right_iff _ _) section abs variable [LinearOrder R] [AddLeftMono R] lemma abs_left_iff (x y : R) : IsCoprime |x| y ↔ IsCoprime x y := by cases le_or_gt 0 x with | inl h => rw [abs_of_nonneg h] | inr h => rw [abs_of_neg h, IsCoprime.neg_left_iff] lemma abs_left {x y : R} (h : IsCoprime x y) : IsCoprime |x| y := abs_left_iff _ _ |>.2 h lemma abs_right_iff (x y : R) : IsCoprime x |y| ↔ IsCoprime x y := by rw [isCoprime_comm, IsCoprime.abs_left_iff, isCoprime_comm] lemma abs_right {x y : R} (h : IsCoprime x y) : IsCoprime x |y| := abs_right_iff _ _ |>.2 h theorem abs_abs_iff (x y : R) : IsCoprime |x| |y| ↔ IsCoprime x y := (abs_left_iff _ _).trans (abs_right_iff _ _) theorem abs_abs {x y : R} (h : IsCoprime x y) : IsCoprime |x| |y| := h.abs_left.abs_right end abs end CommRing theorem sq_add_sq_ne_zero {R : Type*} [CommRing R] [LinearOrder R] [IsStrictOrderedRing R] {a b : R} (h : IsCoprime a b) : a ^ 2 + b ^ 2 ≠ 0 := by intro h' obtain ⟨ha, hb⟩ := (add_eq_zero_iff_of_nonneg (sq_nonneg _) (sq_nonneg _)).mp h' obtain rfl := pow_eq_zero ha obtain rfl := pow_eq_zero hb exact not_isCoprime_zero_zero h end IsCoprime /-- `IsCoprime` is not a useful definition for `Nat`; consider using `Nat.Coprime` instead. -/ @[simp] lemma Nat.isCoprime_iff {m n : ℕ} : IsCoprime m n ↔ m = 1 ∨ n = 1 := by refine ⟨fun ⟨a, b, H⟩ => ?_, fun h => ?_⟩ · simp_rw [Nat.add_eq_one_iff, mul_eq_one, mul_eq_zero] at H exact H.symm.imp (·.1.2) (·.2.2) · obtain rfl | rfl := h · exact isCoprime_one_left · exact isCoprime_one_right /-- `IsCoprime` is not a useful definition for `PNat`; consider using `Nat.Coprime` instead. -/ lemma PNat.isCoprime_iff {m n : ℕ+} : IsCoprime (m : ℕ) n ↔ m = 1 ∨ n = 1 := by simp /-- `IsCoprime` is not a useful definition if an inverse is available. -/ @[simp] lemma Semifield.isCoprime_iff {R : Type*} [Semifield R] {m n : R} : IsCoprime m n ↔ m ≠ 0 ∨ n ≠ 0 := by obtain rfl | hn := eq_or_ne n 0 · simp [isCoprime_zero_right] suffices IsCoprime m n by simpa [hn] refine ⟨0, n⁻¹, ?_⟩ simp [inv_mul_cancel₀ hn] namespace IsRelPrime variable {R} [CommRing R] {x y : R} theorem add_mul_left_left (h : IsRelPrime x y) (z : R) : IsRelPrime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) <| by simpa only [mul_neg, add_neg_cancel_right] using h theorem add_mul_right_left (h : IsRelPrime x y) (z : R) : IsRelPrime (x + z * y) y := mul_comm z y ▸ h.add_mul_left_left z theorem add_mul_left_right (h : IsRelPrime x y) (z : R) : IsRelPrime x (y + x * z) := (h.symm.add_mul_left_left z).symm theorem add_mul_right_right (h : IsRelPrime x y) (z : R) : IsRelPrime x (y + z * x) := (h.symm.add_mul_right_left z).symm theorem mul_add_left_left (h : IsRelPrime x y) (z : R) : IsRelPrime (y * z + x) y := add_comm x _ ▸ h.add_mul_left_left z theorem mul_add_right_left (h : IsRelPrime x y) (z : R) : IsRelPrime (z * y + x) y := add_comm x _ ▸ h.add_mul_right_left z theorem mul_add_left_right (h : IsRelPrime x y) (z : R) : IsRelPrime x (x * z + y) := add_comm y _ ▸ h.add_mul_left_right z theorem mul_add_right_right (h : IsRelPrime x y) (z : R) : IsRelPrime x (z * x + y) := add_comm y _ ▸ h.add_mul_right_right z variable {z} theorem add_mul_left_left_iff : IsRelPrime (x + y * z) y ↔ IsRelPrime x y := ⟨of_add_mul_left_left, fun h ↦ h.add_mul_left_left z⟩ theorem add_mul_right_left_iff : IsRelPrime (x + z * y) y ↔ IsRelPrime x y := ⟨of_add_mul_right_left, fun h ↦ h.add_mul_right_left z⟩ theorem add_mul_left_right_iff : IsRelPrime x (y + x * z) ↔ IsRelPrime x y := ⟨of_add_mul_left_right, fun h ↦ h.add_mul_left_right z⟩ theorem add_mul_right_right_iff : IsRelPrime x (y + z * x) ↔ IsRelPrime x y := ⟨of_add_mul_right_right, fun h ↦ h.add_mul_right_right z⟩ theorem mul_add_left_left_iff {x y z : R} : IsRelPrime (y * z + x) y ↔ IsRelPrime x y := ⟨of_mul_add_left_left, fun h ↦ h.mul_add_left_left z⟩ theorem mul_add_right_left_iff {x y z : R} : IsRelPrime (z * y + x) y ↔ IsRelPrime x y := ⟨of_mul_add_right_left, fun h ↦ h.mul_add_right_left z⟩ theorem mul_add_left_right_iff {x y z : R} : IsRelPrime x (x * z + y) ↔ IsRelPrime x y := ⟨of_mul_add_left_right, fun h ↦ h.mul_add_left_right z⟩ theorem mul_add_right_right_iff {x y z : R} : IsRelPrime x (z * x + y) ↔ IsRelPrime x y := ⟨of_mul_add_right_right, fun h ↦ h.mul_add_right_right z⟩ theorem neg_left (h : IsRelPrime x y) : IsRelPrime (-x) y := fun _ ↦ (h <| dvd_neg.mp ·) theorem neg_right (h : IsRelPrime x y) : IsRelPrime x (-y) := h.symm.neg_left.symm protected theorem neg_neg (h : IsRelPrime x y) : IsRelPrime (-x) (-y) := h.neg_left.neg_right theorem neg_left_iff (x y : R) : IsRelPrime (-x) y ↔ IsRelPrime x y := ⟨fun h ↦ neg_neg x ▸ h.neg_left, neg_left⟩ theorem neg_right_iff (x y : R) : IsRelPrime x (-y) ↔ IsRelPrime x y := ⟨fun h ↦ neg_neg y ▸ h.neg_right, neg_right⟩ theorem neg_neg_iff (x y : R) : IsRelPrime (-x) (-y) ↔ IsRelPrime x y := (neg_left_iff _ _).trans (neg_right_iff _ _) end IsRelPrime
NNNorm.lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import Mathlib.Analysis.NormedSpace.OperatorNorm.Basic import Mathlib.Analysis.NormedSpace.Real /-! # Operator norm as an `NNNorm` Operator norm as an `NNNorm`, i.e. taking values in non-negative reals. -/ suppress_compilation open Bornology open Filter hiding map_smul open scoped NNReal Topology Uniformity open Metric ContinuousLinearMap open Set Real variable {𝕜 𝕜₂ 𝕜₃ E F G : Type*} section NontriviallySemiNormed variable [NontriviallyNormedField 𝕜] [NontriviallyNormedField 𝕜₂] [NontriviallyNormedField 𝕜₃] variable [SeminormedAddCommGroup E] [SeminormedAddCommGroup F] [SeminormedAddCommGroup G] variable [NormedSpace 𝕜 E] [NormedSpace 𝕜₂ F] [NormedSpace 𝕜₃ G] variable {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} {σ₁₃ : 𝕜 →+* 𝕜₃} [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] variable [RingHomIsometric σ₁₂] [RingHomIsometric σ₂₃] [RingHomIsometric σ₁₃] namespace ContinuousLinearMap theorem nnnorm_def (f : E →SL[σ₁₂] F) : ‖f‖₊ = sInf { c | ∀ x, ‖f x‖₊ ≤ c * ‖x‖₊ } := by ext rw [NNReal.coe_sInf, coe_nnnorm, norm_def, NNReal.coe_image] simp_rw [← NNReal.coe_le_coe, NNReal.coe_mul, coe_nnnorm, mem_setOf_eq, NNReal.coe_mk, exists_prop] @[simp, nontriviality] theorem opNNNorm_subsingleton [Subsingleton E] (f : E →SL[σ₁₂] F) : ‖f‖₊ = 0 := NNReal.eq <| f.opNorm_subsingleton /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ theorem opNNNorm_le_bound (f : E →SL[σ₁₂] F) (M : ℝ≥0) (hM : ∀ x, ‖f x‖₊ ≤ M * ‖x‖₊) : ‖f‖₊ ≤ M := opNorm_le_bound f (zero_le M) hM /-- If one controls the norm of every `A x`, `‖x‖₊ ≠ 0`, then one controls the norm of `A`. -/ theorem opNNNorm_le_bound' (f : E →SL[σ₁₂] F) (M : ℝ≥0) (hM : ∀ x, ‖x‖₊ ≠ 0 → ‖f x‖₊ ≤ M * ‖x‖₊) : ‖f‖₊ ≤ M := opNorm_le_bound' f (zero_le M) fun x hx => hM x <| by rwa [← NNReal.coe_ne_zero] /-- For a continuous real linear map `f`, if one controls the norm of every `f x`, `‖x‖₊ = 1`, then one controls the norm of `f`. -/ theorem opNNNorm_le_of_unit_nnnorm [NormedAlgebra ℝ 𝕜] {f : E →SL[σ₁₂] F} {C : ℝ≥0} (hf : ∀ x, ‖x‖₊ = 1 → ‖f x‖₊ ≤ C) : ‖f‖₊ ≤ C := opNorm_le_of_unit_norm C.coe_nonneg fun x hx => hf x <| by rwa [← NNReal.coe_eq_one] theorem opNNNorm_le_of_lipschitz {f : E →SL[σ₁₂] F} {K : ℝ≥0} (hf : LipschitzWith K f) : ‖f‖₊ ≤ K := opNorm_le_of_lipschitz hf theorem opNNNorm_eq_of_bounds {φ : E →SL[σ₁₂] F} (M : ℝ≥0) (h_above : ∀ x, ‖φ x‖₊ ≤ M * ‖x‖₊) (h_below : ∀ N, (∀ x, ‖φ x‖₊ ≤ N * ‖x‖₊) → M ≤ N) : ‖φ‖₊ = M := Subtype.ext <| opNorm_eq_of_bounds (zero_le M) h_above <| Subtype.forall'.mpr h_below theorem opNNNorm_le_iff {f : E →SL[σ₁₂] F} {C : ℝ≥0} : ‖f‖₊ ≤ C ↔ ∀ x, ‖f x‖₊ ≤ C * ‖x‖₊ := opNorm_le_iff C.2 theorem isLeast_opNNNorm (f : E →SL[σ₁₂] F) : IsLeast {C : ℝ≥0 | ∀ x, ‖f x‖₊ ≤ C * ‖x‖₊} ‖f‖₊ := by simpa only [← opNNNorm_le_iff] using isLeast_Ici theorem opNNNorm_comp_le (h : F →SL[σ₂₃] G) (f : E →SL[σ₁₂] F) : ‖h.comp f‖₊ ≤ ‖h‖₊ * ‖f‖₊ := opNorm_comp_le h f lemma opENorm_comp_le (h : F →SL[σ₂₃] G) (f : E →SL[σ₁₂] F) : ‖h.comp f‖ₑ ≤ ‖h‖ₑ * ‖f‖ₑ := by simpa [enorm, ← ENNReal.coe_mul] using opNNNorm_comp_le h f theorem le_opNNNorm (f : E →SL[σ₁₂] F) (x : E) : ‖f x‖₊ ≤ ‖f‖₊ * ‖x‖₊ := f.le_opNorm x lemma le_opENorm (f : E →SL[σ₁₂] F) (x : E) : ‖f x‖ₑ ≤ ‖f‖ₑ * ‖x‖ₑ := by dsimp [enorm]; exact mod_cast le_opNNNorm .. theorem nndist_le_opNNNorm (f : E →SL[σ₁₂] F) (x y : E) : nndist (f x) (f y) ≤ ‖f‖₊ * nndist x y := dist_le_opNorm f x y /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz (f : E →SL[σ₁₂] F) : LipschitzWith ‖f‖₊ f := AddMonoidHomClass.lipschitz_of_bound_nnnorm f _ f.le_opNNNorm /-- Evaluation of a continuous linear map `f` at a point is Lipschitz continuous in `f`. -/ theorem lipschitz_apply (x : E) : LipschitzWith ‖x‖₊ fun f : E →SL[σ₁₂] F => f x := lipschitzWith_iff_norm_sub_le.2 fun f g => ((f - g).le_opNorm x).trans_eq (mul_comm _ _) theorem exists_mul_lt_apply_of_lt_opNNNorm (f : E →SL[σ₁₂] F) {r : ℝ≥0} (hr : r < ‖f‖₊) : ∃ x, r * ‖x‖₊ < ‖f x‖₊ := by simpa only [not_forall, not_le, Set.mem_setOf] using notMem_of_lt_csInf (nnnorm_def f ▸ hr : r < sInf { c : ℝ≥0 | ∀ x, ‖f x‖₊ ≤ c * ‖x‖₊ }) (OrderBot.bddBelow _) theorem exists_mul_lt_of_lt_opNorm (f : E →SL[σ₁₂] F) {r : ℝ} (hr₀ : 0 ≤ r) (hr : r < ‖f‖) : ∃ x, r * ‖x‖ < ‖f x‖ := by lift r to ℝ≥0 using hr₀ exact f.exists_mul_lt_apply_of_lt_opNNNorm hr end ContinuousLinearMap namespace ContinuousLinearEquiv variable {σ₂₁ : 𝕜₂ →+* 𝕜} [RingHomInvPair σ₁₂ σ₂₁] [RingHomInvPair σ₂₁ σ₁₂] protected theorem lipschitz (e : E ≃SL[σ₁₂] F) : LipschitzWith ‖(e : E →SL[σ₁₂] F)‖₊ e := (e : E →SL[σ₁₂] F).lipschitz end ContinuousLinearEquiv end NontriviallySemiNormed section DenselyNormedDomain variable [NormedAddCommGroup E] [SeminormedAddCommGroup F] variable [DenselyNormedField 𝕜] [NontriviallyNormedField 𝕜₂] variable [NormedSpace 𝕜 E] [NormedSpace 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} [RingHomIsometric σ₁₂] namespace ContinuousLinearMap theorem exists_lt_apply_of_lt_opNNNorm (f : E →SL[σ₁₂] F) {r : ℝ≥0} (hr : r < ‖f‖₊) : ∃ x : E, ‖x‖₊ < 1 ∧ r < ‖f x‖₊ := by obtain ⟨y, hy⟩ := f.exists_mul_lt_apply_of_lt_opNNNorm hr have hy' : ‖y‖₊ ≠ 0 := nnnorm_ne_zero_iff.2 fun heq => by simp [heq, nnnorm_zero, map_zero] at hy have hfy : ‖f y‖₊ ≠ 0 := (zero_le'.trans_lt hy).ne' rw [← inv_inv ‖f y‖₊, NNReal.lt_inv_iff_mul_lt (inv_ne_zero hfy), mul_assoc, mul_comm ‖y‖₊, ← mul_assoc, ← NNReal.lt_inv_iff_mul_lt hy'] at hy obtain ⟨k, hk₁, hk₂⟩ := NormedField.exists_lt_nnnorm_lt 𝕜 hy refine ⟨k • y, (nnnorm_smul k y).symm ▸ (NNReal.lt_inv_iff_mul_lt hy').1 hk₂, ?_⟩ rwa [map_smulₛₗ f, nnnorm_smul, ← div_lt_iff₀ hfy.bot_lt, div_eq_mul_inv, RingHomIsometric.nnnorm_map] theorem exists_lt_apply_of_lt_opNorm (f : E →SL[σ₁₂] F) {r : ℝ} (hr : r < ‖f‖) : ∃ x : E, ‖x‖ < 1 ∧ r < ‖f x‖ := by by_cases hr₀ : r < 0 · exact ⟨0, by simpa using hr₀⟩ · lift r to ℝ≥0 using not_lt.1 hr₀ exact f.exists_lt_apply_of_lt_opNNNorm hr theorem sSup_unit_ball_eq_nnnorm (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖₊) '' ball 0 1) = ‖f‖₊ := by refine csSup_eq_of_forall_le_of_forall_lt_exists_gt ((nonempty_ball.mpr zero_lt_one).image _) ?_ fun ub hub => ?_ · rintro - ⟨x, hx, rfl⟩ simpa only [mul_one] using f.le_opNorm_of_le (mem_ball_zero_iff.1 hx).le · obtain ⟨x, hx, hxf⟩ := f.exists_lt_apply_of_lt_opNNNorm hub exact ⟨_, ⟨x, mem_ball_zero_iff.2 hx, rfl⟩, hxf⟩ theorem sSup_unit_ball_eq_norm (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖) '' ball 0 1) = ‖f‖ := by simpa only [NNReal.coe_sSup, Set.image_image] using NNReal.coe_inj.2 f.sSup_unit_ball_eq_nnnorm theorem sSup_unitClosedBall_eq_nnnorm (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖₊) '' closedBall 0 1) = ‖f‖₊ := by have hbdd : ∀ y ∈ (fun x => ‖f x‖₊) '' closedBall 0 1, y ≤ ‖f‖₊ := by rintro - ⟨x, hx, rfl⟩ exact f.unit_le_opNorm x (mem_closedBall_zero_iff.1 hx) refine le_antisymm (csSup_le ((nonempty_closedBall.mpr zero_le_one).image _) hbdd) ?_ rw [← sSup_unit_ball_eq_nnnorm] exact csSup_le_csSup ⟨‖f‖₊, hbdd⟩ ((nonempty_ball.2 zero_lt_one).image _) (Set.image_mono ball_subset_closedBall) theorem sSup_unitClosedBall_eq_norm (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖) '' closedBall 0 1) = ‖f‖ := by simpa only [NNReal.coe_sSup, Set.image_image] using NNReal.coe_inj.2 f.sSup_unitClosedBall_eq_nnnorm theorem exists_nnnorm_eq_one_lt_apply_of_lt_opNNNorm [NormedAlgebra ℝ 𝕜] (f : E →SL[σ₁₂] F) {r : ℝ≥0} (hr : r < ‖f‖₊) : ∃ x : E, ‖x‖₊ = 1 ∧ r < ‖f x‖₊ := by obtain ⟨x, hlt, hr⟩ := exists_lt_apply_of_lt_opNNNorm f hr obtain rfl | hx0 := eq_zero_or_nnnorm_pos x · simp at hr use algebraMap ℝ 𝕜 ‖x‖⁻¹ • x suffices r < ‖x‖₊⁻¹ * ‖f x‖₊ by simpa [nnnorm_smul, inv_mul_cancel₀ hx0.ne'] using this calc r < 1⁻¹ * ‖f x‖₊ := by simpa _ < ‖x‖₊⁻¹ * ‖f x‖₊ := by gcongr; exact (zero_le r).trans_lt hr /-- When the domain is a real normed space, `ContinuousLinearMap.sSup_unitClosedBall_eq_nnnorm` can be tightened to take the supremum over only the `Metric.sphere`. -/ theorem sSup_sphere_eq_nnnorm [NormedAlgebra ℝ 𝕜] (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖₊) '' Metric.sphere 0 1) = ‖f‖₊ := by cases subsingleton_or_nontrivial E · simp [sphere_eq_empty_of_subsingleton one_ne_zero] have : NormedSpace ℝ E := NormedSpace.restrictScalars ℝ 𝕜 E refine csSup_eq_of_forall_le_of_forall_lt_exists_gt ((NormedSpace.sphere_nonempty.mpr zero_le_one).image _) ?_ fun ub hub => ?_ · rintro - ⟨x, hx, rfl⟩ simpa only [mul_one] using f.le_opNorm_of_le (mem_sphere_zero_iff_norm.1 hx).le · obtain ⟨x, hx, hxf⟩ := f.exists_nnnorm_eq_one_lt_apply_of_lt_opNNNorm hub exact ⟨_, ⟨x, by simpa using congrArg NNReal.toReal hx, rfl⟩, hxf⟩ /-- When the domain is a real normed space, `ContinuousLinearMap.sSup_unitClosedBall_eq_norm` can be tightened to take the supremum over only the `Metric.sphere`. -/ theorem sSup_sphere_eq_norm [NormedAlgebra ℝ 𝕜] (f : E →SL[σ₁₂] F) : sSup ((fun x => ‖f x‖) '' Metric.sphere 0 1) = ‖f‖ := by simpa only [NNReal.coe_sSup, Set.image_image] using NNReal.coe_inj.2 f.sSup_sphere_eq_nnnorm end ContinuousLinearMap end DenselyNormedDomain
Loop.lean
/- Copyright (c) 2025 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Data.Matroid.Circuit import Mathlib.Tactic.TFAE /-! # Matroid loops and coloops ## Loops A 'loop' of a matroid `M` is an element `e` satisfying one of the following equivalent conditions: * `e ∈ M.closure ∅`; * `{e}` is dependent in `M`; * `{e}` is a circuit of `M`; * no base of `M` contains `e`. In many mathematical contexts, loops can be thought of as 'trivial' or 'zero' elements; For linearly representable matroids, they correspond to the zero vector, and for graphic matroids, they correspond to edges incident with just one vertex (aka 'loops'). As trivial as they are, loops can be created from matroids with no loops by taking minors or duals, so in many contexts it is unreasonable to simply forbid loops from appearing. For `M : Matroid α`, this file defines a set `Matroid.loops M : Set α`, as well as predicates `Matroid.IsLoop M : α → Prop` and `Matroid.IsNonloop M : α → Prop`, and provides API for interacting with them. ## Coloops The dual notion of a loop is a 'coloop'. Geometrically, these can be thought of elements that are skew to the remainder of the matroid. Coloops in graphic matroids are 'bridge' edges of the graph, and coloops in linearly representable matroids are vectors not spanned by the other vectors in the matroid. Coloops also have many equivalent definitions in abstract matroid language; a coloop is an element of `M.E` if any of the following equivalent conditions holds : * `e` is a loop of `M✶`; * `{e}` is a cocircuit of `M`; * `e` is in no circuit of `M`; * `e` is in every base of `M`; * for all `X ⊆ M.E`, `e ∈ X ↔ e ∈ M.closure X`, * `M.E \ {e}` is nonspanning. ## Main Declarations For `M` : Matroid `α`: * `M.loops` is the set `M.closure ∅`. * `M.IsLoop e` means that `e : α` is a loop of `M`, defined as the statement `e ∈ M.loops`. * `M.isLoop_tfae` gives a number of properties that are equivalent to `IsLoop`. * `M.IsNonloop e` means that `e ∈ M.E`, but `e` is not a loop of `M`. * `M.IsColoop e ` means that `e` is a loop of `M✶`. * `M.coloops` is the set of coloops of `M✶`. * `M.isColoop_tfae` gives a number of properties that are equivalent to `IsColoop`. * `M.Loopless` is a typeclass meaning `M` has no loops. * `M.removeLoops` is the matroid obtained from `M` by restricting to its set of nonloop elements. -/ variable {α β : Type*} {M N : Matroid α} {e f : α} {F X C I : Set α} open Set namespace Matroid /-- `Matroid.loops M` is the closure of the empty set. -/ def loops (M : Matroid α) := M.closure ∅ @[aesop unsafe 20% (rule_sets := [Matroid])] lemma loops_subset_ground (M : Matroid α) : M.loops ⊆ M.E := M.closure_subset_ground ∅ /-- A 'loop' is a member of the closure of the empty set -/ def IsLoop (M : Matroid α) (e : α) : Prop := e ∈ M.loops lemma isLoop_iff : M.IsLoop e ↔ e ∈ M.loops := Iff.rfl lemma closure_empty (M : Matroid α) : M.closure ∅ = M.loops := rfl @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsLoop.mem_ground (he : M.IsLoop e) : e ∈ M.E := closure_subset_ground M ∅ he lemma isLoop_tfae (M : Matroid α) (e : α) : List.TFAE [ M.IsLoop e, e ∈ M.closure ∅, M.IsCircuit {e}, M.Dep {e}, ∀ ⦃B⦄, M.IsBase B → e ∈ M.E \ B] := by tfae_have 1 ↔ 2 := Iff.rfl tfae_have 2 ↔ 3 := by simp [M.empty_indep.mem_closure_iff_of_notMem (notMem_empty e), isCircuit_def, minimal_iff_forall_ssubset, ssubset_singleton_iff] tfae_have 2 ↔ 4 := by simp [M.empty_indep.mem_closure_iff_of_notMem (notMem_empty e)] tfae_have 4 ↔ 5 := by simp only [dep_iff, singleton_subset_iff, mem_diff, forall_and] refine ⟨fun h ↦ ⟨fun _ _ ↦ h.2, fun B hB heB ↦ h.1 (hB.indep.subset (by simpa))⟩, fun h ↦ ⟨fun hi ↦ ?_, h.1 _ M.exists_isBase.choose_spec⟩⟩ obtain ⟨B, hB, heB⟩ := hi.exists_isBase_superset exact h.2 _ hB (by simpa using heB) tfae_finish @[simp] lemma singleton_dep : M.Dep {e} ↔ M.IsLoop e := (M.isLoop_tfae e).out 3 0 alias ⟨_, IsLoop.dep⟩ := singleton_dep lemma singleton_not_indep (he : e ∈ M.E := by aesop_mat) : ¬ M.Indep {e} ↔ M.IsLoop e := by rw [← singleton_dep, ← not_indep_iff] @[simp] lemma singleton_isCircuit : M.IsCircuit {e} ↔ M.IsLoop e := (M.isLoop_tfae e).out 2 0 alias ⟨_, IsLoop.isCircuit⟩ := singleton_isCircuit lemma isLoop_iff_forall_mem_compl_isBase : M.IsLoop e ↔ ∀ B, M.IsBase B → e ∈ M.E \ B := (M.isLoop_tfae e).out 0 4 lemma isLoop_iff_forall_notMem_isBase (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ↔ ∀ B, M.IsBase B → e ∉ B := by simp_rw [isLoop_iff_forall_mem_compl_isBase, mem_diff, and_iff_right he] @[deprecated (since := "2025-05-23")] alias isLoop_iff_forall_not_mem_isBase := isLoop_iff_forall_notMem_isBase lemma IsLoop.mem_closure (he : M.IsLoop e) (X : Set α) : e ∈ M.closure X := M.closure_mono (empty_subset _) he lemma IsLoop.mem_of_isFlat (he : M.IsLoop e) {F : Set α} (hF : M.IsFlat F) : e ∈ F := hF.closure ▸ he.mem_closure F lemma IsFlat.loops_subset (hF : M.IsFlat F) : M.loops ⊆ F := fun _ he ↦ IsLoop.mem_of_isFlat he hF lemma IsLoop.dep_of_mem (he : M.IsLoop e) (h : e ∈ X) (hXE : X ⊆ M.E := by aesop_mat) : M.Dep X := he.dep.superset (singleton_subset_iff.mpr h) hXE lemma IsLoop.not_indep_of_mem (he : M.IsLoop e) (h : e ∈ X) : ¬M.Indep X := fun hX ↦ he.dep.not_indep (hX.subset (singleton_subset_iff.mpr h)) lemma IsLoop.notMem_of_indep (he : M.IsLoop e) (hI : M.Indep I) : e ∉ I := fun h ↦ he.not_indep_of_mem h hI @[deprecated (since := "2025-05-23")] alias IsLoop.not_mem_of_indep := IsLoop.notMem_of_indep lemma IsLoop.eq_of_isCircuit_mem (he : M.IsLoop e) (hC : M.IsCircuit C) (h : e ∈ C) : C = {e} := by rw [he.isCircuit.eq_of_subset_isCircuit hC (singleton_subset_iff.mpr h)] lemma Indep.disjoint_loops (hI : M.Indep I) : Disjoint I M.loops := by_contra fun h ↦ let ⟨_, ⟨heI, he⟩⟩ := not_disjoint_iff.mp h IsLoop.notMem_of_indep he hI heI lemma Indep.eq_empty_of_subset_loops (hI : M.Indep I) (h : I ⊆ M.loops) : I = ∅ := eq_empty_iff_forall_notMem.mpr fun _ he ↦ IsLoop.notMem_of_indep (h he) hI he @[simp] lemma isBasis_loops_iff : M.IsBasis I M.loops ↔ I = ∅ := ⟨fun h ↦ h.indep.eq_empty_of_subset_loops h.subset, by simp +contextual [closure_empty]⟩ lemma closure_eq_loops_of_subset (h : X ⊆ M.loops) : M.closure X = M.loops := (closure_subset_closure_of_subset_closure h).antisymm (M.closure_mono (empty_subset _)) lemma isBasis_iff_empty_of_subset_loops (hX : X ⊆ M.loops) : M.IsBasis I X ↔ I = ∅ := by refine ⟨fun h ↦ ?_, by rintro rfl; simpa⟩ have := (closure_eq_loops_of_subset hX) ▸ h.isBasis_closure_right simpa using this lemma IsLoop.closure (he : M.IsLoop e) : M.closure {e} = M.loops := closure_eq_loops_of_subset (singleton_subset_iff.mpr he) lemma isLoop_iff_closure_eq_loops_and_mem_ground : M.IsLoop e ↔ M.closure {e} = M.loops ∧ e ∈ M.E where mp h := ⟨h.closure, h.mem_ground⟩ mpr h := by rw [isLoop_iff, ← closure_empty, ← singleton_subset_iff, ← closure_subset_closure_iff_subset_closure, h.1, loops] lemma isLoop_iff_closure_eq_loops (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ↔ M.closure {e} = M.loops := by rw [isLoop_iff_closure_eq_loops_and_mem_ground, and_iff_left he] @[simp] lemma closure_loops (M : Matroid α) : M.closure M.loops = M.loops := M.closure_closure ∅ @[simp] lemma closure_union_loops_eq (M : Matroid α) (X : Set α) : M.closure (X ∪ M.loops) = M.closure X := by rw [← closure_empty, closure_union_closure_right_eq, union_empty] @[simp] lemma closure_loops_union_eq (M : Matroid α) (X : Set α) : M.closure (M.loops ∪ X) = M.closure X := by simp [union_comm] @[simp] lemma closure_diff_loops_eq (M : Matroid α) (X : Set α) : M.closure (X \ M.loops) = M.closure X := by rw [← M.closure_union_loops_eq (X \ M.loops), diff_union_self, ← closure_empty, closure_union_closure_right_eq, union_empty] /-- A version of `restrict_loops_eq` without the hypothesis that `R ⊆ M.E` -/ lemma restrict_loops_eq' (M : Matroid α) (R : Set α) : (M ↾ R).loops = (M.loops ∩ R) ∪ (R \ M.E) := by rw [← closure_empty, ← closure_empty, restrict_closure_eq', empty_inter] lemma restrict_loops_eq {R : Set α} (hR : R ⊆ M.E) : (M ↾ R).loops = M.loops ∩ R := by rw [restrict_loops_eq', diff_eq_empty.2 hR, union_empty] @[simp] lemma restrict_isLoop_iff {R : Set α} : (M ↾ R).IsLoop e ↔ e ∈ R ∧ (M.IsLoop e ∨ e ∉ M.E) := by simp only [isLoop_iff, restrict_closure_eq', empty_inter, mem_union, mem_inter_iff, mem_diff, ← closure_empty] tauto lemma IsRestriction.isLoop_iff (hNM : N ≤r M) : N.IsLoop e ↔ e ∈ N.E ∧ M.IsLoop e := by obtain ⟨R, hR, rfl⟩ := hNM simp only [restrict_isLoop_iff, restrict_ground_eq, and_congr_right_iff, or_iff_left_iff_imp] exact fun heR heE ↦ (heE (hR heR)).elim lemma IsLoop.of_isRestriction (he : N.IsLoop e) (hNM : N ≤r M) : M.IsLoop e := ((hNM.isLoop_iff).1 he).2 lemma IsLoop.isLoop_isRestriction (he : M.IsLoop e) (hNM : N ≤r M) (heN : e ∈ N.E) : N.IsLoop e := (hNM.isLoop_iff).2 ⟨heN, he⟩ @[simp] lemma map_loops {f : α → β} {hf : InjOn f M.E} : (M.map f hf).loops = f '' M.loops := by simp [loops] @[simp] lemma map_isLoop_iff {f : α → β} {hf : InjOn f M.E} (he : e ∈ M.E := by aesop_mat) : (M.map f hf).IsLoop (f e) ↔ M.IsLoop e := by rw [isLoop_iff, map_loops, hf.mem_image_iff M.loops_subset_ground he, isLoop_iff] @[simp] lemma mapEmbedding_isLoop_iff {f : α ↪ β} : (M.mapEmbedding f).IsLoop (f e) ↔ M.IsLoop e := by simp [mapEmbedding, isLoop_iff, isLoop_iff, map_closure_eq, preimage_empty, ← closure_empty] @[simp] lemma comap_loops {M : Matroid β} {f : α → β} : (M.comap f).loops = f ⁻¹' M.loops := by rw [loops, comap_closure_eq, image_empty, loops] @[simp] lemma comap_isLoop_iff {M : Matroid β} {f : α → β} : (M.comap f).IsLoop e ↔ M.IsLoop (f e) := by simp [isLoop_iff] @[simp] lemma loopyOn_isLoop_iff {E : Set α} : (loopyOn E).IsLoop e ↔ e ∈ E := by simp [isLoop_iff, loops] lemma eq_loopyOn_iff_loops {E : Set α} : M = loopyOn E ↔ M.loops = E ∧ M.E = E where mp h := by rw [h, loops]; simp mpr | ⟨h, h'⟩ => by rw [← h', ← closure_empty_eq_ground_iff, ← loops, h, h'] lemma restrict_subset_loops_eq (hX : X ⊆ M.loops) : M ↾ X = loopyOn X := by rw [eq_loopyOn_iff_loops, restrict_loops_eq', inter_eq_self_of_subset_right hX, union_eq_self_of_subset_right diff_subset, and_iff_left M.restrict_ground_eq] @[simp] lemma freeOn_not_isLoop (E : Set α) (e : α) : ¬ (freeOn E).IsLoop e := by simp [isLoop_iff, loops] @[simp] lemma uniqueBaseOn_isLoop_iff {I E : Set α} : (uniqueBaseOn I E).IsLoop e ↔ e ∈ E \ I := by simp [isLoop_iff, loops] lemma eq_loopyOn_iff_loops_eq {E : Set α} : M = loopyOn E ↔ M.loops = E ∧ M.E = E := ⟨fun h ↦ by simp [h, loops], fun ⟨h, h'⟩ ↦ by rw [← h', ← closure_empty_eq_ground_iff, ← loops, h, h']⟩ section IsNonloop /-- `M.IsNonloop e` means that `e` is an element of `M.E` but not a loop of `M`. -/ @[mk_iff] structure IsNonloop (M : Matroid α) (e : α) : Prop where not_isLoop : ¬ M.IsLoop e mem_ground : e ∈ M.E attribute [aesop unsafe 20% (rule_sets := [Matroid])] IsNonloop.mem_ground lemma IsLoop.not_isNonloop (he : M.IsLoop e) : ¬M.IsNonloop e := fun h ↦ h.not_isLoop he lemma compl_loops_eq (M : Matroid α) : M.E \ M.loops = {e | M.IsNonloop e} := by simp [Set.ext_iff, isNonloop_iff, and_comm, isLoop_iff] lemma isNonloop_of_not_isLoop (he : e ∈ M.E := by aesop_mat) (h : ¬ M.IsLoop e) : M.IsNonloop e := ⟨h,he⟩ lemma isLoop_of_not_isNonloop (he : e ∈ M.E := by aesop_mat) (h : ¬ M.IsNonloop e) : M.IsLoop e := by rwa [isNonloop_iff, and_iff_left he, not_not] at h @[simp] lemma not_isLoop_iff (he : e ∈ M.E := by aesop_mat) : ¬M.IsLoop e ↔ M.IsNonloop e := ⟨fun h ↦ ⟨h, he⟩, IsNonloop.not_isLoop⟩ @[simp] lemma not_isNonloop_iff (he : e ∈ M.E := by aesop_mat) : ¬M.IsNonloop e ↔ M.IsLoop e := by rw [← not_isLoop_iff, not_not] lemma isNonloop_iff_mem_compl_loops : M.IsNonloop e ↔ e ∈ M.E \ M.loops := by rw [isNonloop_iff, IsLoop, and_comm, mem_diff] lemma setOf_isNonloop_eq (M : Matroid α) : {e | M.IsNonloop e} = M.E \ M.loops := Set.ext (fun _ ↦ isNonloop_iff_mem_compl_loops) lemma not_isNonloop_iff_closure : ¬ M.IsNonloop e ↔ M.closure {e} = M.loops := by by_cases he : e ∈ M.E · simp [isLoop_iff_closure_eq_loops_and_mem_ground, he] simp [← closure_inter_ground, singleton_inter_eq_empty.2 he, loops, (show ¬ M.IsNonloop e from fun h ↦ he h.mem_ground)] lemma isLoop_or_isNonloop (M : Matroid α) (e : α) (he : e ∈ M.E := by aesop_mat) : M.IsLoop e ∨ M.IsNonloop e := by rw [isNonloop_iff, and_iff_left he]; apply em @[simp] lemma indep_singleton : M.Indep {e} ↔ M.IsNonloop e := by rw [isNonloop_iff, ← singleton_dep, dep_iff, not_and, not_imp_not, singleton_subset_iff] exact ⟨fun h ↦ ⟨fun _ ↦ h, singleton_subset_iff.mp h.subset_ground⟩, fun h ↦ h.1 h.2⟩ alias ⟨Indep.isNonloop, IsNonloop.indep⟩ := indep_singleton lemma Indep.isNonloop_of_mem (hI : M.Indep I) (h : e ∈ I) : M.IsNonloop e := by rw [← not_isLoop_iff (hI.subset_ground h)]; exact fun he ↦ (he.notMem_of_indep hI) h lemma IsNonloop.exists_mem_isBase (he : M.IsNonloop e) : ∃ B, M.IsBase B ∧ e ∈ B := by simpa using (indep_singleton.2 he).exists_isBase_superset lemma IsCocircuit.isNonloop_of_mem {K : Set α} (hK : M.IsCocircuit K) (he : e ∈ K) : M.IsNonloop e := by rw [← not_isLoop_iff (hK.subset_ground he), ← singleton_isCircuit] intro he' obtain ⟨f, ⟨rfl, -⟩, hfe⟩ := (he'.isCocircuit_inter_nontrivial hK ⟨e, by simp [he]⟩).exists_ne e exact hfe rfl lemma IsCircuit.isNonloop_of_mem (hC : M.IsCircuit C) (hC' : C.Nontrivial) (he : e ∈ C) : M.IsNonloop e := isNonloop_of_not_isLoop (hC.subset_ground he) (fun hL ↦ by simp [hL.eq_of_isCircuit_mem hC he] at hC') lemma IsCircuit.isNonloop_of_mem_of_one_lt_card (hC : M.IsCircuit C) (h : 1 < C.encard) (he : e ∈ C) : M.IsNonloop e := by refine isNonloop_of_not_isLoop (hC.subset_ground he) (fun hlp ↦ ?_) rw [hlp.eq_of_isCircuit_mem hC he, encard_singleton] at h exact h.ne rfl lemma isNonloop_of_notMem_closure (h : e ∉ M.closure X) (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e := isNonloop_of_not_isLoop he (fun hel ↦ h (hel.mem_closure X)) @[deprecated (since := "2025-05-23")] alias isNonloop_of_not_mem_closure := isNonloop_of_notMem_closure lemma isNonloop_iff_notMem_loops (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e ↔ e ∉ M.loops := by rw [isNonloop_iff, isLoop_iff, and_iff_left he] @[deprecated (since := "2025-05-23")] alias isNonloop_iff_not_mem_loops := isNonloop_iff_notMem_loops lemma IsNonloop.mem_closure_singleton (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : f ∈ M.closure {e} := by rw [← union_empty {_}, singleton_union] at * exact (M.closure_exchange (X := ∅) ⟨hef, (isNonloop_iff_notMem_loops he.mem_ground).1 he⟩).1 lemma IsNonloop.mem_closure_comm (he : M.IsNonloop e) (hf : M.IsNonloop f) : f ∈ M.closure {e} ↔ e ∈ M.closure {f} := ⟨hf.mem_closure_singleton, he.mem_closure_singleton⟩ lemma IsNonloop.isNonloop_of_mem_closure (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : M.IsNonloop f := by rw [isNonloop_iff, and_comm] by_contra! h; apply he.not_isLoop rw [isLoop_iff] at *; convert hef using 1 obtain (hf | hf) := em (f ∈ M.E) · rw [← closure_loops, ← insert_eq_of_mem (h hf), closure_insert_congr_right M.closure_loops, insert_empty_eq] rw [eq_comm, ← closure_inter_ground, inter_comm, inter_singleton_eq_empty.mpr hf, loops] lemma IsNonloop.closure_eq_of_mem_closure (he : M.IsNonloop e) (hef : e ∈ M.closure {f}) : M.closure {e} = M.closure {f} := by rw [← closure_closure _ {f}, ← insert_eq_of_mem hef, closure_insert_closure_eq_closure_insert, ← closure_closure _ {e}, ← insert_eq_of_mem (he.mem_closure_singleton hef), closure_insert_closure_eq_closure_insert, pair_comm] /-- Two distinct nonloops with the same closure form a circuit. -/ lemma IsNonloop.closure_eq_closure_iff_isCircuit_of_ne (he : M.IsNonloop e) (hef : e ≠ f) : M.closure {e} = M.closure {f} ↔ M.IsCircuit {e, f} := by refine ⟨fun h ↦ ?_, fun h ↦ ?_⟩ · have hf := he.isNonloop_of_mem_closure (by rw [← h]; exact M.mem_closure_self e) rw [isCircuit_iff_dep_forall_diff_singleton_indep, dep_iff, insert_subset_iff, and_iff_right he.mem_ground, singleton_subset_iff, and_iff_left hf.mem_ground] suffices ¬ M.Indep {e, f} by simpa [pair_diff_left hef, hf, pair_diff_right hef, he] rw [Indep.insert_indep_iff_of_notMem (by simpa) (by simpa)] simp [← h, mem_closure_self _ _ he.mem_ground] have hclosure := (h.closure_diff_singleton_eq e).trans (h.closure_diff_singleton_eq f).symm rwa [pair_diff_left hef, pair_diff_right hef, eq_comm] at hclosure lemma IsNonloop.closure_eq_closure_iff_eq_or_dep (he : M.IsNonloop e) (hf : M.IsNonloop f) : M.closure {e} = M.closure {f} ↔ e = f ∨ ¬M.Indep {e, f} := by obtain (rfl | hne) := eq_or_ne e f · exact iff_of_true rfl (Or.inl rfl) simp_rw [he.closure_eq_closure_iff_isCircuit_of_ne hne, or_iff_right hne, isCircuit_iff_dep_forall_diff_singleton_indep, dep_iff, insert_subset_iff, singleton_subset_iff, and_iff_left hf.mem_ground, and_iff_left he.mem_ground, and_iff_left_iff_imp] rintro hi x (rfl | rfl) · rwa [pair_diff_left hne, indep_singleton] rwa [pair_diff_right hne, indep_singleton] lemma exists_isNonloop (M : Matroid α) [RankPos M] : ∃ e, M.IsNonloop e := let ⟨_, hB⟩ := M.exists_isBase ⟨_, hB.indep.isNonloop_of_mem hB.nonempty.some_mem⟩ lemma IsNonloop.rankPos (h : M.IsNonloop e) : M.RankPos := h.indep.rankPos_of_nonempty (singleton_nonempty e) @[simp] lemma restrict_isNonloop_iff {R : Set α} : (M ↾ R).IsNonloop e ↔ M.IsNonloop e ∧ e ∈ R := by rw [← indep_singleton, restrict_indep_iff, singleton_subset_iff, indep_singleton] lemma IsNonloop.of_restrict {R : Set α} (h : (M ↾ R).IsNonloop e) : M.IsNonloop e := (restrict_isNonloop_iff.1 h).1 lemma IsNonloop.of_isRestriction (h : N.IsNonloop e) (hNM : N ≤r M) : M.IsNonloop e := by obtain ⟨R, -, rfl⟩ := hNM; exact h.of_restrict lemma isNonloop_iff_restrict_of_mem {R : Set α} (he : e ∈ R) : M.IsNonloop e ↔ (M ↾ R).IsNonloop e := ⟨fun h ↦ restrict_isNonloop_iff.2 ⟨h, he⟩, fun h ↦ h.of_restrict⟩ @[simp] lemma comap_isNonloop_iff {M : Matroid β} {f : α → β} : (M.comap f).IsNonloop e ↔ M.IsNonloop (f e) := by rw [← indep_singleton, comap_indep_iff, image_singleton, indep_singleton, and_iff_left (injOn_singleton _ _)] @[simp] lemma freeOn_isNonloop_iff {E : Set α} : (freeOn E).IsNonloop e ↔ e ∈ E := by rw [← indep_singleton, freeOn_indep_iff, singleton_subset_iff] @[simp] lemma uniqueBaseOn_isNonloop_iff {I E : Set α} : (uniqueBaseOn I E).IsNonloop e ↔ e ∈ I ∩ E := by rw [← indep_singleton, uniqueBaseOn_indep_iff', singleton_subset_iff] lemma IsNonloop.exists_mem_isCocircuit (he : M.IsNonloop e) : ∃ K, M.IsCocircuit K ∧ e ∈ K := by obtain ⟨B, hB, heB⟩ := he.exists_mem_isBase exact ⟨_, fundCocircuit_isCocircuit heB hB, mem_fundCocircuit M e B⟩ @[simp] lemma closure_inter_setOf_isNonloop_eq (M : Matroid α) (X : Set α) : M.closure (X ∩ {e | M.IsNonloop e}) = M.closure X := by rw [setOf_isNonloop_eq, ← inter_diff_assoc, closure_diff_loops_eq, closure_inter_ground] end IsNonloop section IsColoop variable {B K : Set α} /-- A coloop is a loop of the dual matroid. See `Matroid.isColoop_tfae` for a number of equivalent definitions. -/ def IsColoop (M : Matroid α) (e : α) : Prop := M✶.IsLoop e /-- `M.coloops` is the set of coloops of `M`. -/ def coloops (M : Matroid α) := M✶.loops @[aesop unsafe 20% (rule_sets := [Matroid])] lemma IsColoop.mem_ground (he : M.IsColoop e) : e ∈ M.E := @IsLoop.mem_ground α (M✶) e he @[aesop unsafe 20% (rule_sets := [Matroid])] lemma coloops_subset_ground (M : Matroid α) : M.coloops ⊆ M.E := fun _ ↦ IsColoop.mem_ground lemma isColoop_iff_mem_coloops : M.IsColoop e ↔ e ∈ M.coloops := Iff.rfl @[deprecated (since := "2025-04-01")] alias isColoop_iff_mem_loops := isColoop_iff_mem_coloops @[simp] lemma dual_loops : M✶.loops = M.coloops := rfl @[simp] lemma dual_coloops : M✶.coloops = M.loops := by rw [coloops, dual_dual] lemma IsColoop.dual_isLoop (he : M.IsColoop e) : M✶.IsLoop e := he lemma IsColoop.isCocircuit (he : M.IsColoop e) : M.IsCocircuit {e} := IsLoop.isCircuit he lemma IsLoop.dual_isColoop (he : M.IsLoop e) : M✶.IsColoop e := by rwa [IsColoop, dual_dual] @[simp] lemma dual_isColoop_iff_isLoop : M✶.IsColoop e ↔ M.IsLoop e := ⟨fun h ↦ by rw [← dual_dual M]; exact h.dual_isLoop, IsLoop.dual_isColoop⟩ @[simp] lemma dual_isLoop_iff_isColoop : M✶.IsLoop e ↔ M.IsColoop e := ⟨fun h ↦ by rw [← dual_dual M]; exact h.dual_isColoop, IsColoop.dual_isLoop⟩ lemma singleton_isCocircuit : M.IsCocircuit {e} ↔ M.IsColoop e := by simp lemma isColoop_tfae (M : Matroid α) (e : α) : List.TFAE [ M.IsColoop e, e ∈ M.coloops, M.IsCocircuit {e}, ∀ ⦃B⦄, M.IsBase B → e ∈ B, (∀ ⦃C⦄, M.IsCircuit C → e ∉ C) ∧ e ∈ M.E, ∀ X, e ∈ M.closure X ↔ e ∈ X, ¬ M.Spanning (M.E \ {e}) ] := by tfae_have 1 <-> 2 := Iff.rfl tfae_have 1 <-> 3 := singleton_isCocircuit.symm tfae_have 1 <-> 4 := by simp_rw [← dual_isLoop_iff_isColoop, isLoop_iff_forall_mem_compl_isBase] refine ⟨fun h B hB ↦ ?_, fun h B hB ↦ h hB.compl_isBase_of_dual⟩ obtain ⟨-, heB : e ∈ B⟩ := by simpa using h (M.E \ B) hB.compl_isBase_dual assumption tfae_have 3 -> 5 := fun h ↦ ⟨fun C hC heC ↦ hC.inter_isCocircuit_ne_singleton h (e := e) (by simpa), h.subset_ground rfl⟩ tfae_have 5 -> 4 := by refine fun ⟨h, heE⟩ B hB ↦ by_contra fun heB ↦ ?_ rw [← hB.closure_eq] at heE obtain ⟨C, -, hC, heC⟩ := (mem_closure_iff_exists_isCircuit heB).1 heE exact h hC heC tfae_have 5 <-> 6 := by refine ⟨fun h X ↦ ⟨fun heX ↦ by_contra fun heX' ↦ ?_, fun heX ↦ M.mem_closure_of_mem' heX h.2⟩, fun h ↦ ⟨fun C hC heC ↦ ?_, M.closure_subset_ground _ <| (h {e}).2 rfl⟩⟩ · obtain ⟨C, -, hC, heC⟩ := (mem_closure_iff_exists_isCircuit heX').1 heX exact h.1 hC heC · simpa [hC.mem_closure_diff_singleton_of_mem heC] using h (C \ {e}) tfae_have 1 <-> 7 := by wlog he : e ∈ M.E · exact iff_of_false (fun h ↦ he h.mem_ground) <| by simp [he, M.ground_spanning] rw [spanning_iff_compl_coindep diff_subset, ← dual_isLoop_iff_isColoop, ← singleton_dep, diff_diff_cancel_left (by simpa), ← not_indep_iff (by simpa)] tfae_finish lemma isColoop_iff_forall_mem_isBase : M.IsColoop e ↔ ∀ ⦃B⦄, M.IsBase B → e ∈ B := (M.isColoop_tfae e).out 0 3 lemma IsBase.mem_of_isColoop (hB : M.IsBase B) (he : M.IsColoop e) : e ∈ B := isColoop_iff_forall_mem_isBase.mp he hB lemma IsColoop.mem_of_isBase (he : M.IsColoop e) (hB : M.IsBase B) : e ∈ B := isColoop_iff_forall_mem_isBase.mp he hB lemma IsBase.coloops_subset (hB : M.IsBase B) : M.coloops ⊆ B := fun _ he ↦ IsColoop.mem_of_isBase he hB lemma IsColoop.isNonloop (h : M.IsColoop e) : M.IsNonloop e := let ⟨_, hB⟩ := M.exists_isBase hB.indep.isNonloop_of_mem ((isColoop_iff_forall_mem_isBase.mp h) hB) lemma IsLoop.not_isColoop (h : M.IsLoop e) : ¬M.IsColoop e := by rw [← dual_isLoop_iff_isColoop]; rw [← dual_dual M, dual_isLoop_iff_isColoop] at h exact h.isNonloop.not_isLoop lemma IsColoop.notMem_isCircuit (he : M.IsColoop e) (hC : M.IsCircuit C) : e ∉ C := fun h ↦ (hC.isCocircuit.isNonloop_of_mem h).not_isLoop he @[deprecated (since := "2025-05-23")] alias IsColoop.not_mem_isCircuit := IsColoop.notMem_isCircuit lemma IsCircuit.disjoint_coloops (hC : M.IsCircuit C) : Disjoint C M.coloops := disjoint_right.2 <| fun _ he ↦ IsColoop.notMem_isCircuit he hC lemma isColoop_iff_forall_notMem_isCircuit (he : e ∈ M.E := by aesop_mat) : M.IsColoop e ↔ ∀ ⦃C⦄, M.IsCircuit C → e ∉ C := by simp_rw [(M.isColoop_tfae e).out 0 4, and_iff_left he] @[deprecated (since := "2025-05-23")] alias isColoop_iff_forall_not_mem_isCircuit := isColoop_iff_forall_notMem_isCircuit lemma isColoop_iff_forall_mem_compl_isCircuit [RankPos M✶] : M.IsColoop e ↔ ∀ C, M.IsCircuit C → e ∈ M.E \ C := by by_cases he : e ∈ M.E · simp [isColoop_iff_forall_notMem_isCircuit, he] obtain ⟨C, hC⟩ := M.exists_isCircuit exact iff_of_false (fun h ↦ he h.mem_ground) fun h ↦ he (h C hC).1 lemma IsCircuit.not_isColoop_of_mem (hC : M.IsCircuit C) (heC : e ∈ C) : ¬ M.IsColoop e := fun h ↦ h.notMem_isCircuit hC heC lemma isColoop_iff_forall_mem_closure_iff_mem : M.IsColoop e ↔ (∀ X, e ∈ M.closure X ↔ e ∈ X) := (M.isColoop_tfae e).out 0 5 /-- A version of `Matroid.isColoop_iff_forall_mem_closure_iff_mem` where we only quantify over subsets of the ground set. -/ lemma isColoop_iff_forall_mem_closure_iff_mem' : M.IsColoop e ↔ (∀ X, X ⊆ M.E → (e ∈ M.closure X ↔ e ∈ X)) ∧ e ∈ M.E := by refine ⟨fun h ↦ ⟨fun X _ ↦ isColoop_iff_forall_mem_closure_iff_mem.1 h X, h.mem_ground⟩, fun ⟨h, he⟩ ↦ isColoop_iff_forall_mem_closure_iff_mem.2 fun X ↦ ?_⟩ rw [← closure_inter_ground, h _ inter_subset_right, mem_inter_iff, and_iff_left he] lemma IsColoop.mem_closure_iff_mem (he : M.IsColoop e) : e ∈ M.closure X ↔ e ∈ X := (isColoop_iff_forall_mem_closure_iff_mem.1 he) X lemma IsColoop.mem_of_mem_closure (he : M.IsColoop e) (heX : e ∈ M.closure X) : e ∈ X := he.mem_closure_iff_mem.1 heX lemma isColoop_iff_diff_not_spanning : M.IsColoop e ↔ ¬ M.Spanning (M.E \ {e}) := (M.isColoop_tfae e).out 0 6 alias ⟨IsColoop.diff_not_spanning, _⟩ := isColoop_iff_diff_not_spanning lemma isColoop_iff_diff_closure : M.IsColoop e ↔ M.closure (M.E \ {e}) ≠ M.E := by rw [isColoop_iff_diff_not_spanning, spanning_iff_closure_eq] lemma isColoop_iff_notMem_closure_compl (he : e ∈ M.E := by aesop_mat) : M.IsColoop e ↔ e ∉ M.closure (M.E \ {e}) := by rw [isColoop_iff_diff_closure, not_iff_not] refine ⟨fun h ↦ by rwa [h], fun h ↦ (M.closure_subset_ground _).antisymm fun x hx ↦ ?_⟩ obtain (rfl | hne) := eq_or_ne x e · assumption exact M.subset_closure (M.E \ {e}) diff_subset (show x ∈ M.E \ {e} from ⟨hx, hne⟩) @[deprecated (since := "2025-05-23")] alias isColoop_iff_not_mem_closure_compl := isColoop_iff_notMem_closure_compl lemma IsBase.isColoop_iff_forall_notMem_fundCircuit (hB : M.IsBase B) (he : e ∈ B) : M.IsColoop e ↔ ∀ x ∈ M.E \ B, e ∉ M.fundCircuit x B := by refine ⟨fun h x hx heC ↦ (h.notMem_isCircuit <| hB.fundCircuit_isCircuit hx.1 hx.2) heC, fun h ↦ ?_⟩ have h' : M.E \ {e} ⊆ M.closure (B \ {e}) := by rintro x ⟨hxE, hne : x ≠ e⟩ obtain (hx | hx) := em (x ∈ B) · exact M.subset_closure (B \ {e}) (diff_subset.trans hB.subset_ground) ⟨hx, hne⟩ have h_cct := (hB.fundCircuit_isCircuit hxE hx).mem_closure_diff_singleton_of_mem (M.mem_fundCircuit x B) refine (M.closure_subset_closure (subset_diff_singleton ?_ ?_)) h_cct · simpa using fundCircuit_subset_insert .. simp [hne.symm, h x ⟨hxE, hx⟩] rw [isColoop_iff_notMem_closure_compl (hB.subset_ground he)] exact notMem_subset (M.closure_subset_closure_of_subset_closure h') <| hB.indep.notMem_closure_diff_of_mem he @[deprecated (since := "2025-05-23")] alias IsBase.isColoop_iff_forall_not_mem_fundCircuit := IsBase.isColoop_iff_forall_notMem_fundCircuit lemma IsBasis'.inter_coloops_subset (hIX : M.IsBasis' I X) : X ∩ M.coloops ⊆ I := by intro e ⟨heX, (heI : M.IsColoop e)⟩ rwa [← heI.mem_closure_iff_mem, hIX.isBasis_closure_right.closure_eq_right, heI.mem_closure_iff_mem] lemma IsBasis.inter_coloops_subset (hIX : M.IsBasis I X) : X ∩ M.coloops ⊆ I := hIX.isBasis'.inter_coloops_subset lemma exists_mem_isCircuit_of_not_isColoop (heE : e ∈ M.E) (he : ¬ M.IsColoop e) : ∃ C, M.IsCircuit C ∧ e ∈ C := by simp only [isColoop_iff_forall_mem_isBase, not_forall, exists_prop] at he obtain ⟨B, hB, heB⟩ := he exact ⟨M.fundCircuit e B, hB.fundCircuit_isCircuit heE heB, .inl rfl⟩ @[simp] lemma closure_inter_coloops_eq (M : Matroid α) (X : Set α) : M.closure X ∩ M.coloops = X ∩ M.coloops := by simp_rw [Set.ext_iff, mem_inter_iff, ← isColoop_iff_mem_coloops, and_congr_left_iff] intro e he rw [he.mem_closure_iff_mem] lemma closure_inter_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure X ∩ K = X ∩ K := by nth_rw 1 [← inter_eq_self_of_subset_right hK] rw [← inter_assoc, closure_inter_coloops_eq, inter_assoc, inter_eq_self_of_subset_right hK] lemma closure_union_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure (X ∪ K) = M.closure X ∪ K := by rw [← closure_union_closure_left_eq, subset_antisymm_iff, and_iff_left (M.subset_closure _), ← diff_eq_empty, eq_empty_iff_forall_notMem] refine fun e ⟨hecl, he⟩ ↦ he (.inl ?_) obtain ⟨C, hCss, hC, heC⟩ := (mem_closure_iff_exists_isCircuit he).1 hecl rw [← singleton_union, ← union_assoc, union_comm, ← diff_subset_iff, (hC.disjoint_coloops.mono_right hK).sdiff_eq_left, singleton_union] at hCss exact M.closure_subset_closure_of_subset_closure (by simpa) <| hC.mem_closure_diff_singleton_of_mem heC lemma closure_insert_isColoop_eq (X : Set α) (he : M.IsColoop e) : M.closure (insert e X) = insert e (M.closure X) := by rw [← union_singleton, closure_union_eq_of_subset_coloops _ (by simpa), union_singleton] lemma closure_eq_of_subset_coloops (hK : K ⊆ M.coloops) : M.closure K = K ∪ M.loops := by rw [← empty_union K, closure_union_eq_of_subset_coloops _ hK, empty_union, union_comm, closure_empty] lemma closure_diff_eq_of_subset_coloops (X : Set α) (hK : K ⊆ M.coloops) : M.closure (X \ K) = M.closure X \ K := by nth_rw 2 [← inter_union_diff X K] rw [union_comm, closure_union_eq_of_subset_coloops _ (inter_subset_right.trans hK), union_diff_distrib, diff_eq_empty.mpr inter_subset_right, union_empty, eq_comm, sdiff_eq_self_iff_disjoint, disjoint_iff_forall_ne] rintro e heK _ heX rfl rw [IsColoop.mem_closure_iff_mem (hK heK)] at heX exact heX.2 heK lemma closure_disjoint_of_disjoint_of_subset_coloops (hXK : Disjoint X K) (hK : K ⊆ M.coloops) : Disjoint (M.closure X) K := by rwa [disjoint_iff_inter_eq_empty, closure_inter_eq_of_subset_coloops X hK, ← disjoint_iff_inter_eq_empty] lemma closure_disjoint_coloops_of_disjoint_coloops (hX : Disjoint X (M.coloops)) : Disjoint (M.closure X) M.coloops := closure_disjoint_of_disjoint_of_subset_coloops hX Subset.rfl lemma closure_union_coloops_eq (M : Matroid α) (X : Set α) : M.closure (X ∪ M.coloops) = M.closure X ∪ M.coloops := closure_union_eq_of_subset_coloops _ Subset.rfl lemma IsColoop.notMem_closure_of_notMem (he : M.IsColoop e) (hX : e ∉ X) : e ∉ M.closure X := mt he.mem_closure_iff_mem.mp hX @[deprecated (since := "2025-05-23")] alias IsColoop.not_mem_closure_of_not_mem := IsColoop.notMem_closure_of_notMem lemma IsColoop.insert_indep_of_indep (he : M.IsColoop e) (hI : M.Indep I) : M.Indep (insert e I) := by refine (em (e ∈ I)).elim (fun h ↦ by rwa [insert_eq_of_mem h]) fun h ↦ ?_ rw [← hI.notMem_closure_iff_of_notMem h] exact he.notMem_closure_of_notMem h lemma union_indep_iff_indep_of_subset_coloops (hK : K ⊆ M.coloops) : M.Indep (I ∪ K) ↔ M.Indep I := by refine ⟨fun h ↦ h.subset subset_union_left, fun h ↦ ?_⟩ obtain ⟨B, hB, hIB⟩ := h.exists_isBase_superset exact hB.indep.subset (union_subset hIB (hK.trans fun e he ↦ IsColoop.mem_of_isBase he hB)) lemma diff_indep_iff_indep_of_subset_coloops (hK : K ⊆ M.coloops) : M.Indep (I \ K) ↔ M.Indep I := by rw [← union_indep_iff_indep_of_subset_coloops hK, diff_union_self, union_indep_iff_indep_of_subset_coloops hK] @[simp] lemma union_coloops_indep_iff : M.Indep (I ∪ M.coloops) ↔ M.Indep I := union_indep_iff_indep_of_subset_coloops Subset.rfl @[simp] lemma diff_coloops_indep_iff : M.Indep (I \ M.coloops) ↔ M.Indep I := diff_indep_iff_indep_of_subset_coloops Subset.rfl lemma coloops_indep (M : Matroid α) : M.Indep M.coloops := by rw [← empty_union M.coloops, union_coloops_indep_iff] exact M.empty_indep lemma restrict_isColoop_iff {R : Set α} (hRE : R ⊆ M.E) : (M ↾ R).IsColoop e ↔ e ∉ M.closure (R \ {e}) ∧ e ∈ R := by wlog heR : e ∈ R · exact iff_of_false (fun h ↦ heR h.mem_ground) fun h ↦ heR h.2 rw [isColoop_iff_forall_notMem_isCircuit heR, mem_closure_iff_exists_isCircuit (by simp)] simp only [restrict_isCircuit_iff hRE, insert_diff_singleton] aesop /-- If two matroids agree on loops and coloops, and have the same independent sets after loops/coloops are removed, they are equal. -/ lemma ext_indep_disjoint_loops_coloops {M₁ M₂ : Matroid α} (hE : M₁.E = M₂.E) (hl : M₁.loops = M₂.loops) (hc : M₁.coloops = M₂.coloops) (h : ∀ I, I ⊆ M₁.E → Disjoint I (M₁.loops ∪ M₁.coloops) → (M₁.Indep I ↔ M₂.Indep I)) : M₁ = M₂ := by refine ext_indep hE fun I hI ↦ ?_ rw [← diff_coloops_indep_iff, ← @diff_coloops_indep_iff _ M₂, ← hc] obtain hdj | hndj := em (Disjoint I (M₁.loops)) · rw [h _ (diff_subset.trans hI)] rw [disjoint_union_right] exact ⟨disjoint_of_subset_left diff_subset hdj, disjoint_sdiff_left⟩ obtain ⟨e, heI, hel : M₁.IsLoop e⟩ := not_disjoint_iff_nonempty_inter.mp hndj refine iff_of_false (hel.not_indep_of_mem ⟨heI, hel.not_isColoop⟩) ?_ rw [isLoop_iff, hl, ← isLoop_iff] at hel rw [hc] exact hel.not_indep_of_mem ⟨heI, hel.not_isColoop⟩ end IsColoop section Loopless /-- A Matroid is `Loopless` if it has no loop -/ @[mk_iff] class Loopless (M : Matroid α) : Prop where loops_eq_empty : M.loops = ∅ @[simp] lemma loops_eq_empty (M : Matroid α) [Loopless M] : M.loops = ∅ := ‹Loopless M›.loops_eq_empty lemma isNonloop_of_loopless [Loopless M] (he : e ∈ M.E := by aesop_mat) : M.IsNonloop e := by rw [← not_isLoop_iff, isLoop_iff, loops_eq_empty] exact notMem_empty _ lemma subsingleton_indep [M.Loopless] (hI : I.Subsingleton) (hIE : I ⊆ M.E := by aesop_mat) : M.Indep I := by obtain rfl | ⟨x, rfl⟩ := hI.eq_empty_or_singleton · simp simpa using M.isNonloop_of_loopless lemma not_isLoop (M : Matroid α) [Loopless M] (e : α) : ¬ M.IsLoop e := fun h ↦ (isNonloop_of_loopless (e := e)).not_isLoop h lemma loopless_iff_forall_isNonloop : M.Loopless ↔ ∀ e ∈ M.E, M.IsNonloop e := ⟨fun _ _ he ↦ isNonloop_of_loopless he, fun h ↦ ⟨subset_empty_iff.1 (fun e (he : M.IsLoop e) ↦ (h e he.mem_ground).not_isLoop he)⟩⟩ lemma loopless_iff_forall_not_isLoop : M.Loopless ↔ ∀ e ∈ M.E, ¬ M.IsLoop e := ⟨fun _ e _ ↦ M.not_isLoop e, fun h ↦ loopless_iff_forall_isNonloop.2 fun e he ↦ (not_isLoop_iff he).1 (h e he)⟩ lemma loopless_iff_forall_isCircuit : M.Loopless ↔ ∀ C, M.IsCircuit C → C.Nontrivial := by suffices (∃ x ∈ M.E, M.IsLoop x) ↔ ∃ x, M.IsCircuit x ∧ x.Subsingleton by simpa [loopless_iff_forall_not_isLoop, ← not_iff_not (a := ∀ _, _)] refine ⟨fun ⟨e, _, he⟩ ↦ ⟨{e}, he.isCircuit, by simp⟩, fun ⟨C, hC, hCs⟩ ↦ ?_⟩ obtain (rfl | ⟨e, rfl⟩) := hCs.eq_empty_or_singleton · simpa using hC.nonempty exact ⟨e, (singleton_isCircuit.1 hC).mem_ground, singleton_isCircuit.1 hC⟩ lemma Loopless.ground_eq (M : Matroid α) [Loopless M] : M.E = {e | M.IsNonloop e} := Set.ext fun _ ↦ ⟨fun he ↦ isNonloop_of_loopless he, IsNonloop.mem_ground⟩ lemma IsRestriction.loopless [M.Loopless] (hR : N ≤r M) : N.Loopless := by obtain ⟨R, hR, rfl⟩ := hR rw [loopless_iff, restrict_loops_eq hR, M.loops_eq_empty, empty_inter] instance {M : Matroid α} [M.Nonempty] [Loopless M] : RankPos M := M.ground_nonempty.elim fun _ he ↦ (isNonloop_of_loopless he).rankPos @[simp] lemma loopyOn_isLoopless_iff {E : Set α} : Loopless (loopyOn E) ↔ E = ∅ := by simp [loopless_iff_forall_not_isLoop, eq_empty_iff_forall_notMem] /-- The loopless matroid obtained from `M` by deleting all its loops. -/ def removeLoops (M : Matroid α) : Matroid α := M ↾ {e | M.IsNonloop e} lemma removeLoops_eq_restrict (M : Matroid α) : M.removeLoops = M ↾ {e | M.IsNonloop e} := rfl lemma removeLoops_ground_eq (M : Matroid α) : M.removeLoops.E = {e | M.IsNonloop e} := rfl instance removeLoops_loopless (M : Matroid α) : Loopless M.removeLoops := by simp [loopless_iff_forall_isNonloop, removeLoops] @[simp] lemma removeLoops_eq_self (M : Matroid α) [Loopless M] : M.removeLoops = M := by rw [removeLoops, ← Loopless.ground_eq, restrict_ground_eq_self] lemma removeLoops_eq_self_iff : M.removeLoops = M ↔ M.Loopless := by refine ⟨fun h ↦ ?_, fun h ↦ M.removeLoops_eq_self⟩ rw [← h] infer_instance lemma removeLoops_isRestriction (M : Matroid α) : M.removeLoops ≤r M := restrict_isRestriction _ _ (fun _ h ↦ IsNonloop.mem_ground h) lemma eq_restrict_removeLoops (M : Matroid α) : M.removeLoops ↾ M.E = M := by rw [removeLoops, ext_iff_indep] simp only [restrict_ground_eq, restrict_indep_iff, true_and] exact fun I hIE ↦ ⟨ fun hI ↦ hI.1.1, fun hI ↦ ⟨⟨hI,fun e heI ↦ hI.isNonloop_of_mem heI⟩, hIE⟩⟩ @[simp] lemma removeLoops_indep_eq : M.removeLoops.Indep = M.Indep := by ext I rw [removeLoops_eq_restrict, restrict_indep_iff, and_iff_left_iff_imp] exact fun h e ↦ h.isNonloop_of_mem @[simp] lemma removeLoops_isBasis'_eq : M.removeLoops.IsBasis' = M.IsBasis' := by ext simp [IsBasis'] @[simp] lemma removeLoops_isBase_eq : M.removeLoops.IsBase = M.IsBase := by ext B rw [isBase_iff_maximal_indep, removeLoops_indep_eq, isBase_iff_maximal_indep] @[simp] lemma removeLoops_isNonloop_eq : M.removeLoops.IsNonloop = M.IsNonloop := by ext e rw [removeLoops_eq_restrict, restrict_isNonloop_iff, mem_setOf, and_self] lemma IsNonloop.removeLoops_isNonloop (he : M.IsNonloop e) : M.removeLoops.IsNonloop e := by simpa lemma removeLoops_idem (M : Matroid α) : M.removeLoops.removeLoops = M.removeLoops := by simp lemma removeLoops_restrict_eq_restrict (hX : X ⊆ {e | M.IsNonloop e}) : M.removeLoops ↾ X = M ↾ X := by rwa [removeLoops_eq_restrict, restrict_restrict_eq] @[simp] lemma restrict_univ_removeLoops_eq : (M ↾ univ).removeLoops = M.removeLoops := by rw [removeLoops_eq_restrict, restrict_restrict_eq _ (subset_univ _), removeLoops_eq_restrict] simp lemma IsRestriction.isRestriction_removeLoops (hNM : N ≤r M) [N.Loopless] : N ≤r M.removeLoops := by obtain ⟨R, hR, rfl⟩ := hNM.exists_eq_restrict exact IsRestriction.of_subset M fun e heR ↦ ((M ↾ R).isNonloop_of_loopless heR).of_restrict lemma removeLoops_mono_isRestriction (hNM : N ≤r M) : N.removeLoops ≤r M.removeLoops := ((removeLoops_isRestriction _).trans hNM).isRestriction_removeLoops end Loopless end Matroid
NAry.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.Order.Filter.Prod /-! # N-ary maps of filter This file defines the binary and ternary maps of filters. This is mostly useful to define pointwise operations on filters. ## Main declarations * `Filter.map₂`: Binary map of filters. ## Notes This file is very similar to `Data.Set.NAry`, `Data.Finset.NAry` and `Data.Option.NAry`. Please keep them in sync. -/ open Function Set open Filter namespace Filter variable {α α' β β' γ γ' δ δ' ε ε' : Type*} {m : α → β → γ} {f f₁ f₂ : Filter α} {g g₁ g₂ : Filter β} {h : Filter γ} {s : Set α} {t : Set β} {u : Set γ} {a : α} {b : β} /-- The image of a binary function `m : α → β → γ` as a function `Filter α → Filter β → Filter γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`. -/ def map₂ (m : α → β → γ) (f : Filter α) (g : Filter β) : Filter γ := ((f ×ˢ g).map (uncurry m)).copy { s | ∃ u ∈ f, ∃ v ∈ g, image2 m u v ⊆ s } fun _ ↦ by simp only [mem_map, mem_prod_iff, image2_subset_iff, prod_subset_iff]; rfl @[simp 900] theorem mem_map₂_iff : u ∈ map₂ m f g ↔ ∃ s ∈ f, ∃ t ∈ g, image2 m s t ⊆ u := Iff.rfl theorem image2_mem_map₂ (hs : s ∈ f) (ht : t ∈ g) : image2 m s t ∈ map₂ m f g := ⟨_, hs, _, ht, Subset.rfl⟩ theorem map_prod_eq_map₂ (m : α → β → γ) (f : Filter α) (g : Filter β) : Filter.map (fun p : α × β => m p.1 p.2) (f ×ˢ g) = map₂ m f g := by rw [map₂, copy_eq, uncurry_def] theorem map_prod_eq_map₂' (m : α × β → γ) (f : Filter α) (g : Filter β) : Filter.map m (f ×ˢ g) = map₂ (fun a b => m (a, b)) f g := map_prod_eq_map₂ m.curry f g @[simp] theorem map₂_mk_eq_prod (f : Filter α) (g : Filter β) : map₂ Prod.mk f g = f ×ˢ g := by simp only [← map_prod_eq_map₂, map_id'] -- lemma image2_mem_map₂_iff (hm : injective2 m) : image2 m s t ∈ map₂ m f g ↔ s ∈ f ∧ t ∈ g := -- ⟨by { rintro ⟨u, v, hu, hv, h⟩, rw image2_subset_image2_iff hm at h, -- exact ⟨mem_of_superset hu h.1, mem_of_superset hv h.2⟩ }, fun h ↦ image2_mem_map₂ h.1 h.2⟩ @[gcongr] theorem map₂_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : map₂ m f₁ g₁ ≤ map₂ m f₂ g₂ := fun _ ⟨s, hs, t, ht, hst⟩ => ⟨s, hf hs, t, hg ht, hst⟩ theorem map₂_mono_left (h : g₁ ≤ g₂) : map₂ m f g₁ ≤ map₂ m f g₂ := map₂_mono Subset.rfl h theorem map₂_mono_right (h : f₁ ≤ f₂) : map₂ m f₁ g ≤ map₂ m f₂ g := map₂_mono h Subset.rfl @[simp] theorem le_map₂_iff {h : Filter γ} : h ≤ map₂ m f g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → image2 m s t ∈ h := ⟨fun H _ hs _ ht => H <| image2_mem_map₂ hs ht, fun H _ ⟨_, hs, _, ht, hu⟩ => mem_of_superset (H hs ht) hu⟩ @[simp] theorem map₂_eq_bot_iff : map₂ m f g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := by simp [← map_prod_eq_map₂] @[simp] theorem map₂_bot_left : map₂ m ⊥ g = ⊥ := map₂_eq_bot_iff.2 <| .inl rfl @[simp] theorem map₂_bot_right : map₂ m f ⊥ = ⊥ := map₂_eq_bot_iff.2 <| .inr rfl @[simp] theorem map₂_neBot_iff : (map₂ m f g).NeBot ↔ f.NeBot ∧ g.NeBot := by simp [neBot_iff, not_or] protected theorem NeBot.map₂ (hf : f.NeBot) (hg : g.NeBot) : (map₂ m f g).NeBot := map₂_neBot_iff.2 ⟨hf, hg⟩ instance map₂.neBot [NeBot f] [NeBot g] : NeBot (map₂ m f g) := .map₂ ‹_› ‹_› theorem NeBot.of_map₂_left (h : (map₂ m f g).NeBot) : f.NeBot := (map₂_neBot_iff.1 h).1 theorem NeBot.of_map₂_right (h : (map₂ m f g).NeBot) : g.NeBot := (map₂_neBot_iff.1 h).2 theorem map₂_sup_left : map₂ m (f₁ ⊔ f₂) g = map₂ m f₁ g ⊔ map₂ m f₂ g := by simp_rw [← map_prod_eq_map₂, sup_prod, map_sup] theorem map₂_sup_right : map₂ m f (g₁ ⊔ g₂) = map₂ m f g₁ ⊔ map₂ m f g₂ := by simp_rw [← map_prod_eq_map₂, prod_sup, map_sup] theorem map₂_inf_subset_left : map₂ m (f₁ ⊓ f₂) g ≤ map₂ m f₁ g ⊓ map₂ m f₂ g := Monotone.map_inf_le (fun _ _ ↦ map₂_mono_right) f₁ f₂ theorem map₂_inf_subset_right : map₂ m f (g₁ ⊓ g₂) ≤ map₂ m f g₁ ⊓ map₂ m f g₂ := Monotone.map_inf_le (fun _ _ ↦ map₂_mono_left) g₁ g₂ @[simp] theorem map₂_pure_left : map₂ m (pure a) g = g.map (m a) := by rw [← map_prod_eq_map₂, pure_prod, map_map]; rfl @[simp] theorem map₂_pure_right : map₂ m f (pure b) = f.map (m · b) := by rw [← map_prod_eq_map₂, prod_pure, map_map]; rfl theorem map₂_pure : map₂ m (pure a) (pure b) = pure (m a b) := by rw [map₂_pure_right, map_pure] theorem map₂_swap (m : α → β → γ) (f : Filter α) (g : Filter β) : map₂ m f g = map₂ (fun a b => m b a) g f := by rw [← map_prod_eq_map₂, prod_comm, map_map, ← map_prod_eq_map₂, Function.comp_def] @[simp] theorem map₂_left [NeBot g] : map₂ (fun x _ => x) f g = f := by rw [← map_prod_eq_map₂, map_fst_prod] @[simp] theorem map₂_right [NeBot f] : map₂ (fun _ y => y) f g = g := by rw [map₂_swap, map₂_left] theorem map_map₂ (m : α → β → γ) (n : γ → δ) : (map₂ m f g).map n = map₂ (fun a b => n (m a b)) f g := by rw [← map_prod_eq_map₂, ← map_prod_eq_map₂, map_map]; rfl theorem map₂_map_left (m : γ → β → δ) (n : α → γ) : map₂ m (f.map n) g = map₂ (fun a b => m (n a) b) f g := by rw [← map_prod_eq_map₂, ← map_prod_eq_map₂, ← @map_id _ g, prod_map_map_eq, map_map, map_id]; rfl theorem map₂_map_right (m : α → γ → δ) (n : β → γ) : map₂ m f (g.map n) = map₂ (fun a b => m a (n b)) f g := by rw [map₂_swap, map₂_map_left, map₂_swap] @[simp] theorem map₂_curry (m : α × β → γ) (f : Filter α) (g : Filter β) : map₂ m.curry f g = (f ×ˢ g).map m := (map_prod_eq_map₂' _ _ _).symm @[simp] theorem map_uncurry_prod (m : α → β → γ) (f : Filter α) (g : Filter β) : (f ×ˢ g).map (uncurry m) = map₂ m f g := (map₂_curry (uncurry m) f g).symm /-! ### Algebraic replacement rules A collection of lemmas to transfer associativity, commutativity, distributivity, ... of operations to the associativity, commutativity, distributivity, ... of `Filter.map₂` of those operations. The proof pattern is `map₂_lemma operation_lemma`. For example, `map₂_comm mul_comm` proves that `map₂ (*) f g = map₂ (*) g f` in a `CommSemigroup`. -/ theorem map₂_assoc {m : δ → γ → ε} {n : α → β → δ} {m' : α → ε' → ε} {n' : β → γ → ε'} {h : Filter γ} (h_assoc : ∀ a b c, m (n a b) c = m' a (n' b c)) : map₂ m (map₂ n f g) h = map₂ m' f (map₂ n' g h) := by rw [← map_prod_eq_map₂ n, ← map_prod_eq_map₂ n', map₂_map_left, map₂_map_right, ← map_prod_eq_map₂, ← map_prod_eq_map₂, ← prod_assoc, map_map] simp only [h_assoc, Function.comp_def, Equiv.prodAssoc_apply] theorem map₂_comm {n : β → α → γ} (h_comm : ∀ a b, m a b = n b a) : map₂ m f g = map₂ n g f := (map₂_swap _ _ _).trans <| by simp_rw [h_comm] theorem map₂_left_comm {m : α → δ → ε} {n : β → γ → δ} {m' : α → γ → δ'} {n' : β → δ' → ε} (h_left_comm : ∀ a b c, m a (n b c) = n' b (m' a c)) : map₂ m f (map₂ n g h) = map₂ n' g (map₂ m' f h) := by rw [map₂_swap m', map₂_swap m] exact map₂_assoc fun _ _ _ => h_left_comm _ _ _ theorem map₂_right_comm {m : δ → γ → ε} {n : α → β → δ} {m' : α → γ → δ'} {n' : δ' → β → ε} (h_right_comm : ∀ a b c, m (n a b) c = n' (m' a c) b) : map₂ m (map₂ n f g) h = map₂ n' (map₂ m' f h) g := by rw [map₂_swap n, map₂_swap n'] exact map₂_assoc fun _ _ _ => h_right_comm _ _ _ theorem map_map₂_distrib {n : γ → δ} {m' : α' → β' → δ} {n₁ : α → α'} {n₂ : β → β'} (h_distrib : ∀ a b, n (m a b) = m' (n₁ a) (n₂ b)) : (map₂ m f g).map n = map₂ m' (f.map n₁) (g.map n₂) := by simp_rw [map_map₂, map₂_map_left, map₂_map_right, h_distrib] /-- Symmetric statement to `Filter.map₂_map_left_comm`. -/ theorem map_map₂_distrib_left {n : γ → δ} {m' : α' → β → δ} {n' : α → α'} (h_distrib : ∀ a b, n (m a b) = m' (n' a) b) : (map₂ m f g).map n = map₂ m' (f.map n') g := map_map₂_distrib h_distrib /-- Symmetric statement to `Filter.map_map₂_right_comm`. -/ theorem map_map₂_distrib_right {n : γ → δ} {m' : α → β' → δ} {n' : β → β'} (h_distrib : ∀ a b, n (m a b) = m' a (n' b)) : (map₂ m f g).map n = map₂ m' f (g.map n') := map_map₂_distrib h_distrib /-- Symmetric statement to `Filter.map_map₂_distrib_left`. -/ theorem map₂_map_left_comm {m : α' → β → γ} {n : α → α'} {m' : α → β → δ} {n' : δ → γ} (h_left_comm : ∀ a b, m (n a) b = n' (m' a b)) : map₂ m (f.map n) g = (map₂ m' f g).map n' := (map_map₂_distrib_left fun a b => (h_left_comm a b).symm).symm /-- Symmetric statement to `Filter.map_map₂_distrib_right`. -/ theorem map_map₂_right_comm {m : α → β' → γ} {n : β → β'} {m' : α → β → δ} {n' : δ → γ} (h_right_comm : ∀ a b, m a (n b) = n' (m' a b)) : map₂ m f (g.map n) = (map₂ m' f g).map n' := (map_map₂_distrib_right fun a b => (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `f-f` cross terms on the RHS. -/ theorem map₂_distrib_le_left {m : α → δ → ε} {n : β → γ → δ} {m₁ : α → β → β'} {m₂ : α → γ → γ'} {n' : β' → γ' → ε} (h_distrib : ∀ a b c, m a (n b c) = n' (m₁ a b) (m₂ a c)) : map₂ m f (map₂ n g h) ≤ map₂ n' (map₂ m₁ f g) (map₂ m₂ f h) := by rintro s ⟨t₁, ⟨u₁, hu₁, v, hv, ht₁⟩, t₂, ⟨u₂, hu₂, w, hw, ht₂⟩, hs⟩ refine ⟨u₁ ∩ u₂, inter_mem hu₁ hu₂, _, image2_mem_map₂ hv hw, ?_⟩ refine (image2_distrib_subset_left h_distrib).trans ((image2_subset ?_ ?_).trans hs) · exact (image2_subset_right inter_subset_left).trans ht₁ · exact (image2_subset_right inter_subset_right).trans ht₂ /-- The other direction does not hold because of the `h`-`h` cross terms on the RHS. -/ theorem map₂_distrib_le_right {m : δ → γ → ε} {n : α → β → δ} {m₁ : α → γ → α'} {m₂ : β → γ → β'} {n' : α' → β' → ε} (h_distrib : ∀ a b c, m (n a b) c = n' (m₁ a c) (m₂ b c)) : map₂ m (map₂ n f g) h ≤ map₂ n' (map₂ m₁ f h) (map₂ m₂ g h) := by rintro s ⟨t₁, ⟨u, hu, w₁, hw₁, ht₁⟩, t₂, ⟨v, hv, w₂, hw₂, ht₂⟩, hs⟩ refine ⟨_, image2_mem_map₂ hu hv, w₁ ∩ w₂, inter_mem hw₁ hw₂, ?_⟩ refine (image2_distrib_subset_right h_distrib).trans ((image2_subset ?_ ?_).trans hs) · exact (image2_subset_left inter_subset_left).trans ht₁ · exact (image2_subset_left inter_subset_right).trans ht₂ theorem map_map₂_antidistrib {n : γ → δ} {m' : β' → α' → δ} {n₁ : β → β'} {n₂ : α → α'} (h_antidistrib : ∀ a b, n (m a b) = m' (n₁ b) (n₂ a)) : (map₂ m f g).map n = map₂ m' (g.map n₁) (f.map n₂) := by rw [map₂_swap m] exact map_map₂_distrib fun _ _ => h_antidistrib _ _ /-- Symmetric statement to `Filter.map₂_map_left_anticomm`. -/ theorem map_map₂_antidistrib_left {n : γ → δ} {m' : β' → α → δ} {n' : β → β'} (h_antidistrib : ∀ a b, n (m a b) = m' (n' b) a) : (map₂ m f g).map n = map₂ m' (g.map n') f := map_map₂_antidistrib h_antidistrib /-- Symmetric statement to `Filter.map_map₂_right_anticomm`. -/ theorem map_map₂_antidistrib_right {n : γ → δ} {m' : β → α' → δ} {n' : α → α'} (h_antidistrib : ∀ a b, n (m a b) = m' b (n' a)) : (map₂ m f g).map n = map₂ m' g (f.map n') := map_map₂_antidistrib h_antidistrib /-- Symmetric statement to `Filter.map_map₂_antidistrib_left`. -/ theorem map₂_map_left_anticomm {m : α' → β → γ} {n : α → α'} {m' : β → α → δ} {n' : δ → γ} (h_left_anticomm : ∀ a b, m (n a) b = n' (m' b a)) : map₂ m (f.map n) g = (map₂ m' g f).map n' := (map_map₂_antidistrib_left fun a b => (h_left_anticomm b a).symm).symm /-- Symmetric statement to `Filter.map_map₂_antidistrib_right`. -/ theorem map_map₂_right_anticomm {m : α → β' → γ} {n : β → β'} {m' : β → α → δ} {n' : δ → γ} (h_right_anticomm : ∀ a b, m a (n b) = n' (m' b a)) : map₂ m f (g.map n) = (map₂ m' g f).map n' := (map_map₂_antidistrib_right fun a b => (h_right_anticomm b a).symm).symm /-- If `a` is a left identity for `f : α → β → β`, then `pure a` is a left identity for `Filter.map₂ f`. -/ theorem map₂_left_identity {f : α → β → β} {a : α} (h : ∀ b, f a b = b) (l : Filter β) : map₂ f (pure a) l = l := by rw [map₂_pure_left, show f a = id from funext h, map_id] /-- If `b` is a right identity for `f : α → β → α`, then `pure b` is a right identity for `Filter.map₂ f`. -/ theorem map₂_right_identity {f : α → β → α} {b : β} (h : ∀ a, f a b = a) (l : Filter α) : map₂ f l (pure b) = l := by rw [map₂_pure_right, funext h, map_id'] end Filter
Bifunctor.lean
/- Copyright (c) 2023 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.GradedObject /-! # The action of bifunctors on graded objects Given a bifunctor `F : C₁ ⥤ C₂ ⥤ C₃` and types `I` and `J`, we construct an obvious functor `mapBifunctor F I J : GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject (I × J) C₃`. When we have a map `p : I × J → K` and that suitable coproducts exists, we also get a functor `mapBifunctorMap F p : GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject K C₃`. In case `p : I × I → I` is the addition on a monoid and `F` is the tensor product on a monoidal category `C`, these definitions shall be used in order to construct a monoidal structure on `GradedObject I C` (TODO @joelriou). -/ namespace CategoryTheory open Category variable {C₁ C₂ C₃ : Type*} [Category C₁] [Category C₂] [Category C₃] (F : C₁ ⥤ C₂ ⥤ C₃) namespace GradedObject /-- Given a bifunctor `F : C₁ ⥤ C₂ ⥤ C₃` and types `I` and `J`, this is the obvious functor `GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject (I × J) C₃`. -/ @[simps] def mapBifunctor (I J : Type*) : GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject (I × J) C₃ where obj X := { obj := fun Y ij => (F.obj (X ij.1)).obj (Y ij.2) map := fun φ ij => (F.obj (X ij.1)).map (φ ij.2) } map φ := { app := fun Y ij => (F.map (φ ij.1)).app (Y ij.2) } section variable {I J K : Type*} (p : I × J → K) /-- Given a bifunctor `F : C₁ ⥤ C₂ ⥤ C₃`, graded objects `X : GradedObject I C₁` and `Y : GradedObject J C₂` and a map `p : I × J → K`, this is the `K`-graded object sending `k` to the coproduct of `(F.obj (X i)).obj (Y j)` for `p ⟨i, j⟩ = k`. -/ noncomputable def mapBifunctorMapObj (X : GradedObject I C₁) (Y : GradedObject J C₂) [HasMap (((mapBifunctor F I J).obj X).obj Y) p] : GradedObject K C₃ := (((mapBifunctor F I J).obj X).obj Y).mapObj p /-- The inclusion of `(F.obj (X i)).obj (Y j)` in `mapBifunctorMapObj F p X Y k` when `i + j = k`. -/ noncomputable def ιMapBifunctorMapObj (X : GradedObject I C₁) (Y : GradedObject J C₂) [HasMap (((mapBifunctor F I J).obj X).obj Y) p] (i : I) (j : J) (k : K) (h : p ⟨i, j⟩ = k) : (F.obj (X i)).obj (Y j) ⟶ mapBifunctorMapObj F p X Y k := (((mapBifunctor F I J).obj X).obj Y).ιMapObj p ⟨i, j⟩ k h /-- The maps `mapBifunctorMapObj F p X₁ Y₁ ⟶ mapBifunctorMapObj F p X₂ Y₂` which express the functoriality of `mapBifunctorMapObj`, see `mapBifunctorMap`. -/ noncomputable def mapBifunctorMapMap {X₁ X₂ : GradedObject I C₁} (f : X₁ ⟶ X₂) {Y₁ Y₂ : GradedObject J C₂} (g : Y₁ ⟶ Y₂) [HasMap (((mapBifunctor F I J).obj X₁).obj Y₁) p] [HasMap (((mapBifunctor F I J).obj X₂).obj Y₂) p] : mapBifunctorMapObj F p X₁ Y₁ ⟶ mapBifunctorMapObj F p X₂ Y₂ := GradedObject.mapMap (((mapBifunctor F I J).map f).app Y₁ ≫ ((mapBifunctor F I J).obj X₂).map g) p @[reassoc (attr := simp)] lemma ι_mapBifunctorMapMap {X₁ X₂ : GradedObject I C₁} (f : X₁ ⟶ X₂) {Y₁ Y₂ : GradedObject J C₂} (g : Y₁ ⟶ Y₂) [HasMap (((mapBifunctor F I J).obj X₁).obj Y₁) p] [HasMap (((mapBifunctor F I J).obj X₂).obj Y₂) p] (i : I) (j : J) (k : K) (h : p ⟨i, j⟩ = k) : ιMapBifunctorMapObj F p X₁ Y₁ i j k h ≫ mapBifunctorMapMap F p f g k = (F.map (f i)).app (Y₁ j) ≫ (F.obj (X₂ i)).map (g j) ≫ ιMapBifunctorMapObj F p X₂ Y₂ i j k h := by simp [ιMapBifunctorMapObj, mapBifunctorMapMap] @[ext] lemma mapBifunctorMapObj_ext {X : GradedObject I C₁} {Y : GradedObject J C₂} {A : C₃} {k : K} [HasMap (((mapBifunctor F I J).obj X).obj Y) p] {f g : mapBifunctorMapObj F p X Y k ⟶ A} (h : ∀ (i : I) (j : J) (hij : p ⟨i, j⟩ = k), ιMapBifunctorMapObj F p X Y i j k hij ≫ f = ιMapBifunctorMapObj F p X Y i j k hij ≫ g) : f = g := by apply mapObj_ext rintro ⟨i, j⟩ hij exact h i j hij variable {F p} in /-- Constructor for morphisms from `mapBifunctorMapObj F p X Y k`. -/ noncomputable def mapBifunctorMapObjDesc {X : GradedObject I C₁} {Y : GradedObject J C₂} {A : C₃} {k : K} [HasMap (((mapBifunctor F I J).obj X).obj Y) p] (f : ∀ (i : I) (j : J) (_ : p ⟨i, j⟩ = k), (F.obj (X i)).obj (Y j) ⟶ A) : mapBifunctorMapObj F p X Y k ⟶ A := descMapObj _ _ (fun ⟨i, j⟩ hij => f i j hij) @[reassoc (attr := simp)] lemma ι_mapBifunctorMapObjDesc {X : GradedObject I C₁} {Y : GradedObject J C₂} {A : C₃} {k : K} [HasMap (((mapBifunctor F I J).obj X).obj Y) p] (f : ∀ (i : I) (j : J) (_ : p ⟨i, j⟩ = k), (F.obj (X i)).obj (Y j) ⟶ A) (i : I) (j : J) (hij : p ⟨i, j⟩ = k) : ιMapBifunctorMapObj F p X Y i j k hij ≫ mapBifunctorMapObjDesc f = f i j hij := by apply ι_descMapObj section variable {X₁ X₂ : GradedObject I C₁} {Y₁ Y₂ : GradedObject J C₂} [HasMap (((mapBifunctor F I J).obj X₁).obj Y₁) p] [HasMap (((mapBifunctor F I J).obj X₂).obj Y₂) p] /-- The isomorphism `mapBifunctorMapObj F p X₁ Y₁ ≅ mapBifunctorMapObj F p X₂ Y₂` induced by isomorphisms `X₁ ≅ X₂` and `Y₁ ≅ Y₂`. -/ @[simps] noncomputable def mapBifunctorMapMapIso (e : X₁ ≅ X₂) (e' : Y₁ ≅ Y₂) : mapBifunctorMapObj F p X₁ Y₁ ≅ mapBifunctorMapObj F p X₂ Y₂ where hom := mapBifunctorMapMap F p e.hom e'.hom inv := mapBifunctorMapMap F p e.inv e'.inv hom_inv_id := by ext; simp inv_hom_id := by ext; simp instance (f : X₁ ⟶ X₂) (g : Y₁ ⟶ Y₂) [IsIso f] [IsIso g] : IsIso (mapBifunctorMapMap F p f g) := (inferInstance : IsIso (mapBifunctorMapMapIso F p (asIso f) (asIso g)).hom) end attribute [local simp] mapBifunctorMapMap /-- Given a bifunctor `F : C₁ ⥤ C₂ ⥤ C₃` and a map `p : I × J → K`, this is the functor `GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject K C₃` sending `X : GradedObject I C₁` and `Y : GradedObject J C₂` to the `K`-graded object sending `k` to the coproduct of `(F.obj (X i)).obj (Y j)` for `p ⟨i, j⟩ = k`. -/ @[simps] noncomputable def mapBifunctorMap [∀ X Y, HasMap (((mapBifunctor F I J).obj X).obj Y) p] : GradedObject I C₁ ⥤ GradedObject J C₂ ⥤ GradedObject K C₃ where obj X := { obj := fun Y => mapBifunctorMapObj F p X Y map := fun ψ => mapBifunctorMapMap F p (𝟙 X) ψ } map {X₁ X₂} φ := { app := fun Y => mapBifunctorMapMap F p φ (𝟙 Y) naturality := fun {Y₁ Y₂} ψ => by dsimp simp only [Functor.map_id, NatTrans.id_app, id_comp, comp_id, ← mapMap_comp, NatTrans.naturality] } end end GradedObject end CategoryTheory
tuple.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat. From mathcomp Require Import seq choice fintype path. Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. (******************************************************************************) (* This file defines tuples, i.e., sequences with a fixed (known) length, *) (* and sequences with bounded length. *) (* For tuples we define: *) (* n.-tuple T == the type of n-tuples of elements of type T *) (* [tuple of s] == the tuple whose underlying sequence (value) is s *) (* The size of s must be known: specifically, Coq must *) (* be able to infer a Canonical tuple projecting on s. *) (* in_tuple s == the (size s).-tuple with value s *) (* [tuple] == the empty tuple *) (* [tuple x1; ..; xn] == the explicit n.-tuple <x1; ..; xn> *) (* [tuple E | i < n] == the n.-tuple with general term E (i : 'I_n is bound *) (* in E) *) (* tcast Emn t == the m.-tuple t cast as an n.-tuple using Emn : m = n *) (* As n.-tuple T coerces to seq t, all seq operations (size, nth, ...) can be *) (* applied to t : n.-tuple T; we provide a few specialized instances when *) (* avoids the need for a default value. *) (* tsize t == the size of t (the n in n.-tuple T) *) (* tnth t i == the i'th component of t, where i : 'I_n *) (* [tnth t i] == the i'th component of t, where i : nat and i < n *) (* is convertible to true *) (* thead t == the first element of t, when n is m.+1 for some m *) (* For bounded sequences we define: *) (* n.-bseq T == the type of bounded sequences of elements of type T, *) (* the length of a bounded sequence is smaller or *) (* or equal to n *) (* [bseq of s] == the bounded sequence whose underlying value is s *) (* The size of s must be known. *) (* in_bseq s == the (size s).-bseq with value s *) (* [bseq] == the empty bseq *) (* insub_bseq n s == the n.-bseq of value s if size s <= n, else [bseq] *) (* [bseq x1; ..; xn] == the explicit n.-bseq <x1; ..; xn> *) (* cast_bseq Emn t == the m.-bseq t cast as an n.-tuple using Emn : m = n *) (* widen_bseq Lmn t == the m.-bseq t cast as an n.-tuple using Lmn : m <= n *) (* Most seq constructors (cons, behead, cat, rcons, belast, take, drop, rot, *) (* rotr, map, ...) can be used to build tuples and bounded sequences via *) (* the [tuple of s] and [bseq of s] constructs respectively. *) (* Tuples and bounded sequences are actually instances of subType of seq, *) (* and inherit all combinatorial structures, including the finType structure. *) (* Some useful lemmas and definitions: *) (* tuple0 : [tuple] is the only 0.-tuple *) (* bseq0 : [bseq] is the only 0.-bseq *) (* tupleP : elimination view for n.+1.-tuple *) (* ord_tuple n : the n.-tuple of all i : 'I_n *) (******************************************************************************) Section TupleDef. Variables (n : nat) (T : Type). Structure tuple_of : Type := Tuple {tval :> seq T; _ : size tval == n}. HB.instance Definition _ := [isSub for tval]. Implicit Type t : tuple_of. Definition tsize of tuple_of := n. Lemma size_tuple t : size t = n. Proof. exact: (eqP (valP t)). Qed. Lemma tnth_default t : 'I_n -> T. Proof. by rewrite -(size_tuple t); case: (tval t) => [|//] []. Qed. Definition tnth t i := nth (tnth_default t i) t i. Lemma tnth_nth x t i : tnth t i = nth x t i. Proof. by apply: set_nth_default; rewrite size_tuple. Qed. Lemma tnth_onth x t i : tnth t i = x <-> onth t i = Some x. Proof. rewrite (tnth_nth x) onthE (nth_map x) ?size_tuple//. by split; [move->|case]. Qed. Lemma map_tnth_enum t : map (tnth t) (enum 'I_n) = t. Proof. case def_t: {-}(val t) => [|x0 t']. by rewrite [enum _]size0nil // -cardE card_ord -(size_tuple t) def_t. apply: (@eq_from_nth _ x0) => [|i]; rewrite size_map. by rewrite -cardE size_tuple card_ord. move=> lt_i_e; have lt_i_n: i < n by rewrite -cardE card_ord in lt_i_e. by rewrite (nth_map (Ordinal lt_i_n)) // (tnth_nth x0) nth_enum_ord. Qed. Lemma eq_from_tnth t1 t2 : tnth t1 =1 tnth t2 -> t1 = t2. Proof. by move/eq_map=> eq_t; apply: val_inj; rewrite /= -!map_tnth_enum eq_t. Qed. Definition tuple t mkT : tuple_of := mkT (let: Tuple _ tP := t return size t == n in tP). Lemma tupleE t : tuple (fun sP => @Tuple t sP) = t. Proof. by case: t. Qed. End TupleDef. Notation "n .-tuple" := (tuple_of n) (format "n .-tuple") : type_scope. Notation "{ 'tuple' n 'of' T }" := (n.-tuple T : predArgType) (only parsing) : type_scope. Notation "[ 'tuple' 'of' s ]" := (tuple (fun sP => @Tuple _ _ s sP)) (format "[ 'tuple' 'of' s ]") : form_scope. Notation "[ 'tnth' t i ]" := (tnth t (@Ordinal (tsize t) i (erefl true))) (t, i at level 8, format "[ 'tnth' t i ]") : form_scope. Canonical nil_tuple T := Tuple (isT : @size T [::] == 0). Canonical cons_tuple n T x (t : n.-tuple T) := Tuple (valP t : size (x :: t) == n.+1). Notation "[ 'tuple' x1 ; .. ; xn ]" := [tuple of x1 :: .. [:: xn] ..] (format "[ 'tuple' '[' x1 ; '/' .. ; '/' xn ']' ]") : form_scope. Notation "[ 'tuple' ]" := [tuple of [::]] (format "[ 'tuple' ]") : form_scope. Section CastTuple. Variable T : Type. Definition in_tuple (s : seq T) := Tuple (eqxx (size s)). Definition tcast m n (eq_mn : m = n) t := let: erefl in _ = n := eq_mn return n.-tuple T in t. Lemma tcastE m n (eq_mn : m = n) t i : tnth (tcast eq_mn t) i = tnth t (cast_ord (esym eq_mn) i). Proof. by case: n / eq_mn in i *; rewrite cast_ord_id. Qed. Lemma tcast_id n (eq_nn : n = n) t : tcast eq_nn t = t. Proof. by rewrite (eq_axiomK eq_nn). Qed. Lemma tcastK m n (eq_mn : m = n) : cancel (tcast eq_mn) (tcast (esym eq_mn)). Proof. by case: n / eq_mn. Qed. Lemma tcastKV m n (eq_mn : m = n) : cancel (tcast (esym eq_mn)) (tcast eq_mn). Proof. by case: n / eq_mn. Qed. Lemma tcast_trans m n p (eq_mn : m = n) (eq_np : n = p) t: tcast (etrans eq_mn eq_np) t = tcast eq_np (tcast eq_mn t). Proof. by case: n / eq_mn eq_np; case: p /. Qed. Lemma tvalK n (t : n.-tuple T) : in_tuple t = tcast (esym (size_tuple t)) t. Proof. by apply: val_inj => /=; case: _ / (esym _). Qed. Lemma val_tcast m n (eq_mn : m = n) (t : m.-tuple T) : tcast eq_mn t = t :> seq T. Proof. by case: n / eq_mn. Qed. Lemma in_tupleE s : in_tuple s = s :> seq T. Proof. by []. Qed. End CastTuple. Section SeqTuple. Variables (n m : nat) (T U rT : Type). Implicit Type t : n.-tuple T. Lemma rcons_tupleP t x : size (rcons t x) == n.+1. Proof. by rewrite size_rcons size_tuple. Qed. Canonical rcons_tuple t x := Tuple (rcons_tupleP t x). Lemma nseq_tupleP x : @size T (nseq n x) == n. Proof. by rewrite size_nseq. Qed. Canonical nseq_tuple x := Tuple (nseq_tupleP x). Lemma iota_tupleP : size (iota m n) == n. Proof. by rewrite size_iota. Qed. Canonical iota_tuple := Tuple iota_tupleP. Lemma behead_tupleP t : size (behead t) == n.-1. Proof. by rewrite size_behead size_tuple. Qed. Canonical behead_tuple t := Tuple (behead_tupleP t). Lemma belast_tupleP x t : size (belast x t) == n. Proof. by rewrite size_belast size_tuple. Qed. Canonical belast_tuple x t := Tuple (belast_tupleP x t). Lemma cat_tupleP t (u : m.-tuple T) : size (t ++ u) == n + m. Proof. by rewrite size_cat !size_tuple. Qed. Canonical cat_tuple t u := Tuple (cat_tupleP t u). Lemma take_tupleP t : size (take m t) == minn m n. Proof. by rewrite size_take size_tuple eqxx. Qed. Canonical take_tuple t := Tuple (take_tupleP t). Lemma drop_tupleP t : size (drop m t) == n - m. Proof. by rewrite size_drop size_tuple. Qed. Canonical drop_tuple t := Tuple (drop_tupleP t). Lemma rev_tupleP t : size (rev t) == n. Proof. by rewrite size_rev size_tuple. Qed. Canonical rev_tuple t := Tuple (rev_tupleP t). Lemma rot_tupleP t : size (rot m t) == n. Proof. by rewrite size_rot size_tuple. Qed. Canonical rot_tuple t := Tuple (rot_tupleP t). Lemma rotr_tupleP t : size (rotr m t) == n. Proof. by rewrite size_rotr size_tuple. Qed. Canonical rotr_tuple t := Tuple (rotr_tupleP t). Lemma map_tupleP f t : @size rT (map f t) == n. Proof. by rewrite size_map size_tuple. Qed. Canonical map_tuple f t := Tuple (map_tupleP f t). Lemma scanl_tupleP f x t : @size rT (scanl f x t) == n. Proof. by rewrite size_scanl size_tuple. Qed. Canonical scanl_tuple f x t := Tuple (scanl_tupleP f x t). Lemma pairmap_tupleP f x t : @size rT (pairmap f x t) == n. Proof. by rewrite size_pairmap size_tuple. Qed. Canonical pairmap_tuple f x t := Tuple (pairmap_tupleP f x t). Lemma zip_tupleP t (u : n.-tuple U) : size (zip t u) == n. Proof. by rewrite size1_zip !size_tuple. Qed. Canonical zip_tuple t u := Tuple (zip_tupleP t u). Lemma allpairs_tupleP f t (u : m.-tuple U) : @size rT (allpairs f t u) == n * m. Proof. by rewrite size_allpairs !size_tuple. Qed. Canonical allpairs_tuple f t u := Tuple (allpairs_tupleP f t u). Lemma sort_tupleP r t : size (sort r t) == n. Proof. by rewrite size_sort size_tuple. Qed. Canonical sort_tuple r t := Tuple (sort_tupleP r t). Definition thead (u : n.+1.-tuple T) := tnth u ord0. Lemma tnth0 x t : tnth [tuple of x :: t] ord0 = x. Proof. by []. Qed. Lemma tnthS x t i : tnth [tuple of x :: t] (lift ord0 i) = tnth t i. Proof. by rewrite (tnth_nth (tnth_default t i)). Qed. Lemma theadE x t : thead [tuple of x :: t] = x. Proof. by []. Qed. Lemma tuple0 : all_equal_to ([tuple] : 0.-tuple T). Proof. by move=> t; apply: val_inj; case: t => [[]]. Qed. Variant tuple1_spec : n.+1.-tuple T -> Type := Tuple1spec x t : tuple1_spec [tuple of x :: t]. Lemma tupleP u : tuple1_spec u. Proof. case: u => [[|x s] //= sz_s]; pose t := @Tuple n _ s sz_s. by rewrite (_ : Tuple _ = [tuple of x :: t]) //; apply: val_inj. Qed. Lemma tnth_map f t i : tnth [tuple of map f t] i = f (tnth t i) :> rT. Proof. by apply: nth_map; rewrite size_tuple. Qed. Lemma tnth_nseq x i : tnth [tuple of nseq n x] i = x. Proof. by rewrite !(tnth_nth (tnth_default (nseq_tuple x) i)) nth_nseq ltn_ord. Qed. End SeqTuple. Lemma tnth_behead n T (t : n.+1.-tuple T) i : tnth [tuple of behead t] i = tnth t (inord i.+1). Proof. by case/tupleP: t => x t; rewrite !(tnth_nth x) inordK ?ltnS. Qed. Lemma tuple_eta n T (t : n.+1.-tuple T) : t = [tuple of thead t :: behead t]. Proof. by case/tupleP: t => x t; apply: val_inj. Qed. Section tnth_shift. Context {T : Type} {n1 n2} (t1 : n1.-tuple T) (t2 : n2.-tuple T). Lemma tnth_lshift i : tnth [tuple of t1 ++ t2] (lshift n2 i) = tnth t1 i. Proof. have x0 := tnth_default t1 i; rewrite !(tnth_nth x0). by rewrite nth_cat size_tuple /= ltn_ord. Qed. Lemma tnth_rshift j : tnth [tuple of t1 ++ t2] (rshift n1 j) = tnth t2 j. Proof. have x0 := tnth_default t2 j; rewrite !(tnth_nth x0). by rewrite nth_cat size_tuple ltnNge leq_addr /= addKn. Qed. End tnth_shift. Section TupleQuantifiers. Variables (n : nat) (T : Type). Implicit Types (a : pred T) (t : n.-tuple T). Lemma forallb_tnth a t : [forall i, a (tnth t i)] = all a t. Proof. apply: negb_inj; rewrite -has_predC -has_map negb_forall. apply/existsP/(has_nthP true) => [[i a_t_i] | [i lt_i_n a_t_i]]. by exists i; rewrite ?size_tuple // -tnth_nth tnth_map. rewrite size_tuple in lt_i_n; exists (Ordinal lt_i_n). by rewrite -tnth_map (tnth_nth true). Qed. Lemma existsb_tnth a t : [exists i, a (tnth t i)] = has a t. Proof. by apply: negb_inj; rewrite negb_exists -all_predC -forallb_tnth. Qed. Lemma all_tnthP a t : reflect (forall i, a (tnth t i)) (all a t). Proof. by rewrite -forallb_tnth; apply: forallP. Qed. Lemma has_tnthP a t : reflect (exists i, a (tnth t i)) (has a t). Proof. by rewrite -existsb_tnth; apply: existsP. Qed. End TupleQuantifiers. Arguments all_tnthP {n T a t}. Arguments has_tnthP {n T a t}. Section EqTuple. Variables (n : nat) (T : eqType). HB.instance Definition _ : hasDecEq (n.-tuple T) := [Equality of n.-tuple T by <:]. Canonical tuple_predType := PredType (pred_of_seq : n.-tuple T -> pred T). Lemma eqEtuple (t1 t2 : n.-tuple T) : (t1 == t2) = [forall i, tnth t1 i == tnth t2 i]. Proof. by apply/eqP/'forall_eqP => [->|/eq_from_tnth]. Qed. Lemma memtE (t : n.-tuple T) : mem t = mem (tval t). Proof. by []. Qed. Lemma mem_tnth i (t : n.-tuple T) : tnth t i \in t. Proof. by rewrite mem_nth ?size_tuple. Qed. Lemma memt_nth x0 (t : n.-tuple T) i : i < n -> nth x0 t i \in t. Proof. by move=> i_lt_n; rewrite mem_nth ?size_tuple. Qed. Lemma tnthP (t : n.-tuple T) x : reflect (exists i, x = tnth t i) (x \in t). Proof. apply: (iffP idP) => [/(nthP x)[i ltin <-] | [i ->]]; last exact: mem_tnth. by rewrite size_tuple in ltin; exists (Ordinal ltin); rewrite (tnth_nth x). Qed. Lemma seq_tnthP (s : seq T) x : x \in s -> {i | x = tnth (in_tuple s) i}. Proof. move=> s_x; pose i := index x s; have lt_i: i < size s by rewrite index_mem. by exists (Ordinal lt_i); rewrite (tnth_nth x) nth_index. Qed. Lemma tuple_uniqP (t : n.-tuple T) : reflect (injective (tnth t)) (uniq t). Proof. case: {+}n => [|m] in t *; first by rewrite tuple0; constructor => -[]. pose x0 := tnth t ord0; apply/(equivP (uniqP x0)); split=> tinj i j. by rewrite !(tnth_nth x0) => /tinj/val_inj; apply; rewrite size_tuple inE. rewrite !size_tuple !inE => im jm; have := tinj (Ordinal im) (Ordinal jm). by rewrite !(tnth_nth x0) => /[apply]-[]. Qed. End EqTuple. HB.instance Definition _ n (T : choiceType) := [Choice of n.-tuple T by <:]. HB.instance Definition _ n (T : countType) := [Countable of n.-tuple T by <:]. Module Type FinTupleSig. Section FinTupleSig. Variables (n : nat) (T : finType). Parameter enum : seq (n.-tuple T). Axiom enumP : Finite.axiom enum. Axiom size_enum : size enum = #|T| ^ n. End FinTupleSig. End FinTupleSig. Module FinTuple : FinTupleSig. Section FinTuple. Variables (n : nat) (T : finType). Definition enum : seq (n.-tuple T) := let extend e := flatten (codom (fun x => map (cons x) e)) in pmap insub (iter n extend [::[::]]). Lemma enumP : Finite.axiom enum. Proof. case=> /= t t_n; rewrite -(count_map _ (pred1 t)) (pmap_filter (insubK _)). rewrite count_filter -(@eq_count _ (pred1 t)) => [|s /=]; last first. by rewrite isSome_insub; case: eqP=> // ->. elim: n t t_n => [|m IHm] [|x t] //= {}/IHm; move: (iter m _ _) => em IHm. transitivity (x \in T : nat); rewrite // -mem_enum codomE. elim: (fintype.enum T) (enum_uniq T) => //= y e IHe /andP[/negPf ney]. rewrite count_cat count_map inE /preim /= [in LHS]/eq_op /= eq_sym => /IHe->. by case: eqP => [->|_]; rewrite ?(ney, count_pred0, IHm). Qed. Lemma size_enum : size enum = #|T| ^ n. Proof. rewrite /= cardE size_pmap_sub; elim: n => //= m IHm. rewrite expnS /codom /image_mem; elim: {2 3}(fintype.enum T) => //= x e IHe. by rewrite count_cat {}IHe count_map IHm. Qed. End FinTuple. End FinTuple. Section UseFinTuple. Variables (n : nat) (T : finType). (* tuple_finMixin could, in principle, be made Canonical to allow for folding *) (* Finite.enum of a finite tuple type (see comments around eqE in eqtype.v), *) (* but in practice it will not work because the mixin_enum projector *) (* has been buried under an opaque alias, to avoid some performance issues *) (* during type inference. *) HB.instance Definition _ := isFinite.Build (n.-tuple T) (@FinTuple.enumP n T). Lemma card_tuple : #|{:n.-tuple T}| = #|T| ^ n. Proof. by rewrite [#|_|]cardT enumT unlock FinTuple.size_enum. Qed. Lemma enum_tupleP (A : {pred T}) : size (enum A) == #|A|. Proof. by rewrite -cardE. Qed. Canonical enum_tuple A := Tuple (enum_tupleP A). Definition ord_tuple : n.-tuple 'I_n := Tuple (introT eqP (size_enum_ord n)). Lemma val_ord_tuple : val ord_tuple = enum 'I_n. Proof. by []. Qed. Lemma tuple_map_ord U (t : n.-tuple U) : t = [tuple of map (tnth t) ord_tuple]. Proof. by apply: val_inj => /=; rewrite map_tnth_enum. Qed. Lemma tnth_ord_tuple i : tnth ord_tuple i = i. Proof. apply: val_inj; rewrite (tnth_nth i) -(nth_map _ 0) ?size_tuple //. by rewrite /= enumT unlock val_ord_enum nth_iota. Qed. Section ImageTuple. Variables (T' : Type) (f : T -> T') (A : {pred T}). Canonical image_tuple : #|A|.-tuple T' := [tuple of image f A]. Canonical codom_tuple : #|T|.-tuple T' := [tuple of codom f]. End ImageTuple. Section MkTuple. Variables (T' : Type) (f : 'I_n -> T'). Definition mktuple := map_tuple f ord_tuple. Lemma tnth_mktuple i : tnth mktuple i = f i. Proof. by rewrite tnth_map tnth_ord_tuple. Qed. Lemma nth_mktuple x0 (i : 'I_n) : nth x0 mktuple i = f i. Proof. by rewrite -tnth_nth tnth_mktuple. Qed. End MkTuple. Lemma eq_mktuple T' (f1 f2 : 'I_n -> T') : f1 =1 f2 -> mktuple f1 = mktuple f2. Proof. by move=> eq_f; apply eq_from_tnth=> i; rewrite !tnth_map eq_f. Qed. End UseFinTuple. Notation "[ 'tuple' F | i < n ]" := (mktuple (fun i : 'I_n => F)) (i at level 0, format "[ '[hv' 'tuple' F '/' | i < n ] ']'") : form_scope. Arguments eq_mktuple {n T'} [f1] f2 eq_f12. Section BseqDef. Variables (n : nat) (T : Type). Structure bseq_of : Type := Bseq {bseqval :> seq T; _ : size bseqval <= n}. HB.instance Definition _ := [isSub for bseqval]. Implicit Type bs : bseq_of. Lemma size_bseq bs : size bs <= n. Proof. by case: bs. Qed. Definition bseq bs mkB : bseq_of := mkB (let: Bseq _ bsP := bs return size bs <= n in bsP). Lemma bseqE bs : bseq (fun sP => @Bseq bs sP) = bs. Proof. by case: bs. Qed. End BseqDef. Canonical nil_bseq n T := Bseq (isT : @size T [::] <= n). Canonical cons_bseq n T x (t : bseq_of n T) := Bseq (valP t : size (x :: t) <= n.+1). Notation "n .-bseq" := (bseq_of n) (format "n .-bseq") : type_scope. Notation "{ 'bseq' n 'of' T }" := (n.-bseq T : predArgType) (only parsing) : type_scope. Notation "[ 'bseq' 'of' s ]" := (bseq (fun sP => @Bseq _ _ s sP)) (format "[ 'bseq' 'of' s ]") : form_scope. Notation "[ 'bseq' x1 ; .. ; xn ]" := [bseq of x1 :: .. [:: xn] ..] (format "[ 'bseq' '[' x1 ; '/' .. ; '/' xn ']' ]") : form_scope. Notation "[ 'bseq' ]" := [bseq of [::]] (format "[ 'bseq' ]") : form_scope. Coercion bseq_of_tuple n T (t : n.-tuple T) : n.-bseq T := Bseq (eq_leq (size_tuple t)). Definition insub_bseq n T (s : seq T) : n.-bseq T := insubd [bseq] s. Lemma size_insub_bseq n T (s : seq T) : size (insub_bseq n s) <= size s. Proof. by rewrite /insub_bseq /insubd; case: insubP => // ? ? ->. Qed. Section CastBseq. Variable T : Type. Definition in_bseq (s : seq T) : (size s).-bseq T := Bseq (leqnn (size s)). Definition cast_bseq m n (eq_mn : m = n) bs := let: erefl in _ = n := eq_mn return n.-bseq T in bs. Definition widen_bseq m n (lemn : m <= n) (bs : m.-bseq T) : n.-bseq T := @Bseq n T bs (leq_trans (size_bseq bs) lemn). Lemma cast_bseq_id n (eq_nn : n = n) bs : cast_bseq eq_nn bs = bs. Proof. by rewrite (eq_axiomK eq_nn). Qed. Lemma cast_bseqK m n (eq_mn : m = n) : cancel (cast_bseq eq_mn) (cast_bseq (esym eq_mn)). Proof. by case: n / eq_mn. Qed. Lemma cast_bseqKV m n (eq_mn : m = n) : cancel (cast_bseq (esym eq_mn)) (cast_bseq eq_mn). Proof. by case: n / eq_mn. Qed. Lemma cast_bseq_trans m n p (eq_mn : m = n) (eq_np : n = p) bs : cast_bseq (etrans eq_mn eq_np) bs = cast_bseq eq_np (cast_bseq eq_mn bs). Proof. by case: n / eq_mn eq_np; case: p /. Qed. Lemma size_cast_bseq m n (eq_mn : m = n) (bs : m.-bseq T) : size (cast_bseq eq_mn bs) = size bs. Proof. by case: n / eq_mn. Qed. Lemma widen_bseq_id n (lenn : n <= n) (bs : n.-bseq T) : widen_bseq lenn bs = bs. Proof. exact: val_inj. Qed. Lemma cast_bseqEwiden m n (eq_mn : m = n) (bs : m.-bseq T) : cast_bseq eq_mn bs = widen_bseq (eq_leq eq_mn) bs. Proof. by case: n / eq_mn; rewrite widen_bseq_id. Qed. Lemma widen_bseqK m n (lemn : m <= n) (lenm : n <= m) : cancel (@widen_bseq m n lemn) (widen_bseq lenm). Proof. by move=> t; apply: val_inj. Qed. Lemma widen_bseq_trans m n p (lemn : m <= n) (lenp : n <= p) (bs : m.-bseq T) : widen_bseq (leq_trans lemn lenp) bs = widen_bseq lenp (widen_bseq lemn bs). Proof. exact/val_inj. Qed. Lemma size_widen_bseq m n (lemn : m <= n) (bs : m.-bseq T) : size (widen_bseq lemn bs) = size bs. Proof. by []. Qed. Lemma in_bseqE s : in_bseq s = s :> seq T. Proof. by []. Qed. Lemma widen_bseq_in_bseq n (bs : n.-bseq T) : widen_bseq (size_bseq bs) (in_bseq bs) = bs. Proof. exact: val_inj. Qed. End CastBseq. Section SeqBseq. Variables (n m : nat) (T U rT : Type). Implicit Type s : n.-bseq T. Lemma rcons_bseqP s x : size (rcons s x) <= n.+1. Proof. by rewrite size_rcons ltnS size_bseq. Qed. Canonical rcons_bseq s x := Bseq (rcons_bseqP s x). Lemma behead_bseqP s : size (behead s) <= n.-1. Proof. rewrite size_behead -!subn1; apply/leq_sub2r/size_bseq. Qed. Canonical behead_bseq s := Bseq (behead_bseqP s). Lemma belast_bseqP x s : size (belast x s) <= n. Proof. by rewrite size_belast; apply/size_bseq. Qed. Canonical belast_bseq x s := Bseq (belast_bseqP x s). Lemma cat_bseqP s (s' : m.-bseq T) : size (s ++ s') <= n + m. Proof. by rewrite size_cat; apply/leq_add/size_bseq/size_bseq. Qed. Canonical cat_bseq s (s' : m.-bseq T) := Bseq (cat_bseqP s s'). Lemma take_bseqP s : size (take m s) <= n. Proof. by rewrite size_take_min (leq_trans _ (size_bseq s)) // geq_minr. Qed. Canonical take_bseq s := Bseq (take_bseqP s). Lemma drop_bseqP s : size (drop m s) <= n - m. Proof. by rewrite size_drop; apply/leq_sub2r/size_bseq. Qed. Canonical drop_bseq s := Bseq (drop_bseqP s). Lemma rev_bseqP s : size (rev s) <= n. Proof. by rewrite size_rev size_bseq. Qed. Canonical rev_bseq s := Bseq (rev_bseqP s). Lemma rot_bseqP s : size (rot m s) <= n. Proof. by rewrite size_rot size_bseq. Qed. Canonical rot_bseq s := Bseq (rot_bseqP s). Lemma rotr_bseqP s : size (rotr m s) <= n. Proof. by rewrite size_rotr size_bseq. Qed. Canonical rotr_bseq s := Bseq (rotr_bseqP s). Lemma map_bseqP f s : @size rT (map f s) <= n. Proof. by rewrite size_map size_bseq. Qed. Canonical map_bseq f s := Bseq (map_bseqP f s). Lemma scanl_bseqP f x s : @size rT (scanl f x s) <= n. Proof. by rewrite size_scanl size_bseq. Qed. Canonical scanl_bseq f x s := Bseq (scanl_bseqP f x s). Lemma pairmap_bseqP f x s : @size rT (pairmap f x s) <= n. Proof. by rewrite size_pairmap size_bseq. Qed. Canonical pairmap_bseq f x s := Bseq (pairmap_bseqP f x s). Lemma allpairs_bseqP f s (s' : m.-bseq U) : @size rT (allpairs f s s') <= n * m. Proof. by rewrite size_allpairs; apply/leq_mul/size_bseq/size_bseq. Qed. Canonical allpairs_bseq f s (s' : m.-bseq U) := Bseq (allpairs_bseqP f s s'). Lemma sort_bseqP r s : size (sort r s) <= n. Proof. by rewrite size_sort size_bseq. Qed. Canonical sort_bseq r s := Bseq (sort_bseqP r s). Lemma bseq0 : all_equal_to ([bseq] : 0.-bseq T). Proof. by move=> s; apply: val_inj; case: s => [[]]. Qed. End SeqBseq. HB.instance Definition bseq_hasDecEq n (T : eqType) := [Equality of n.-bseq T by <:]. Canonical bseq_predType n (T : eqType) := Eval hnf in PredType (fun t : n.-bseq T => mem_seq t). Lemma membsE n (T : eqType) (bs : n.-bseq T) : mem bs = mem (bseqval bs). Proof. by []. Qed. HB.instance Definition bseq_hasChoice n (T : choiceType) := [Choice of n.-bseq T by <:]. HB.instance Definition bseq_isCountable n (T : countType) := [Countable of n.-bseq T by <:]. Definition bseq_tagged_tuple n T (s : n.-bseq T) : {k : 'I_n.+1 & k.-tuple T} := Tagged _ (in_tuple s : (Ordinal (size_bseq s : size s < n.+1)).-tuple _). Arguments bseq_tagged_tuple {n T}. Definition tagged_tuple_bseq n T (t : {k : 'I_n.+1 & k.-tuple T}) : n.-bseq T := widen_bseq (leq_ord (tag t)) (tagged t). Arguments tagged_tuple_bseq {n T}. Lemma bseq_tagged_tupleK {n T} : cancel (@bseq_tagged_tuple n T) tagged_tuple_bseq. Proof. by move=> bs; apply/val_inj. Qed. Lemma tagged_tuple_bseqK {n T} : cancel (@tagged_tuple_bseq n T) bseq_tagged_tuple. Proof. move=> [[k lt_kn] t]; apply: eq_existT_curried => [|k_eq]; apply/val_inj. by rewrite /= size_tuple. by refine (let: erefl := k_eq in _). Qed. Lemma bseq_tagged_tuple_bij {n T} : bijective (@bseq_tagged_tuple n T). Proof. exact/Bijective/tagged_tuple_bseqK/bseq_tagged_tupleK. Qed. Lemma tagged_tuple_bseq_bij {n T} : bijective (@tagged_tuple_bseq n T). Proof. exact/Bijective/bseq_tagged_tupleK/tagged_tuple_bseqK. Qed. #[global] Hint Resolve bseq_tagged_tuple_bij tagged_tuple_bseq_bij : core. #[non_forgetful_inheritance] HB.instance Definition _ n (T : finType) := isFinite.Build (n.-bseq T) (pcan_enumP (can_pcan (@bseq_tagged_tupleK n T))).
PathConnected.lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Yury Kudryashov -/ import Mathlib.Analysis.Convex.Basic import Mathlib.LinearAlgebra.Projection import Mathlib.Topology.Connected.PathConnected /-! # Segment between 2 points as a bundled path In this file we define `Path.segment a b : Path a b` to be the path going from `a` to `b` along the straight segment with constant velocity `b - a`. We also prove basic properties of this construction, then use it to show that a nonempty convex set is path connected. In particular, a topological vector space over `ℝ` is path connected. -/ open Set open scoped Convex variable {E : Type*} [AddCommGroup E] [Module ℝ E] [TopologicalSpace E] [ContinuousAdd E] [ContinuousSMul ℝ E] namespace Path /-- The path from `a` to `b` going along a straight line segment -/ @[simps] protected def segment (a b : E) : Path a b where toFun t := AffineMap.lineMap a b (t : ℝ) source' := by simp target' := by simp @[simp] theorem range_segment (a b : E) : Set.range (Path.segment a b) = [a -[ℝ] b] := by rw [segment_eq_image_lineMap, image_eq_range] simp only [← segment_apply] @[simp] protected theorem segment_same (a : E) : Path.segment a a = .refl a := by ext; simp @[simp] protected theorem segment_symm (a b : E) : (Path.segment a b).symm = .segment b a := by ext; simp [AffineMap.lineMap_apply_one_sub] @[simp] theorem segment_add_segment (a b c d : E) : (Path.segment a b).add (.segment c d) = .segment (a + c) (b + d) := by ext simp [AffineMap.lineMap_apply_module, add_add_add_comm] @[simp] theorem cast_segment {a b c d : E} (hac : c = a) (hbd : d = b) : (Path.segment a b).cast hac hbd = .segment c d := by subst_vars; rfl end Path theorem JoinedIn.of_segment_subset {x y : E} {s : Set E} (h : [x -[ℝ] y] ⊆ s) : JoinedIn s x y := by use .segment x y rwa [← range_subset_iff, Path.range_segment] protected theorem StarConvex.isPathConnected {s : Set E} {a : E} (h : StarConvex ℝ a s) (ha : a ∈ s) : IsPathConnected s := ⟨a, ha, fun _y hy ↦ .of_segment_subset <| h.segment_subset hy⟩ /-- A nonempty convex set is path connected. -/ protected theorem Convex.isPathConnected {s : Set E} (hconv : Convex ℝ s) (hne : s.Nonempty) : IsPathConnected s := let ⟨_a, ha⟩ := hne; (hconv ha).isPathConnected ha /-- A nonempty convex set is connected. -/ protected theorem Convex.isConnected {s : Set E} (h : Convex ℝ s) (hne : s.Nonempty) : IsConnected s := (h.isPathConnected hne).isConnected /-- A convex set is preconnected. -/ protected theorem Convex.isPreconnected {s : Set E} (h : Convex ℝ s) : IsPreconnected s := s.eq_empty_or_nonempty.elim (fun h => h.symm ▸ isPreconnected_empty) fun hne => (h.isConnected hne).isPreconnected /-- A subspace in a topological vector space over `ℝ` is path connected. -/ theorem Submodule.isPathConnected (s : Submodule ℝ E) : IsPathConnected (s : Set E) := s.convex.isPathConnected s.nonempty /-- Every topological vector space over ℝ is path connected. Not an instance, because it creates enormous TC subproblems (turn on `pp.all`). -/ protected theorem IsTopologicalAddGroup.pathConnectedSpace : PathConnectedSpace E := pathConnectedSpace_iff_univ.mpr <| convex_univ.isPathConnected ⟨(0 : E), trivial⟩ /-- Given two complementary subspaces `p` and `q` in `E`, if the complement of `{0}` is path connected in `p` then the complement of `q` is path connected in `E`. -/ theorem isPathConnected_compl_of_isPathConnected_compl_zero {p q : Submodule ℝ E} (hpq : IsCompl p q) (hpc : IsPathConnected ({0}ᶜ : Set p)) : IsPathConnected (qᶜ : Set E) := by convert (hpc.image continuous_subtype_val).add q.isPathConnected using 1 trans Submodule.prodEquivOfIsCompl p q hpq '' ({0}ᶜ ×ˢ univ) · rw [prod_univ, LinearEquiv.image_eq_preimage] ext simp · ext simp [mem_add, and_assoc]
Supported.lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import Mathlib.Algebra.MvPolynomial.Variables /-! # Polynomials supported by a set of variables This file contains the definition and lemmas about `MvPolynomial.supported`. ## Main definitions * `MvPolynomial.supported` : Given a set `s : Set σ`, `supported R s` is the subalgebra of `MvPolynomial σ R` consisting of polynomials whose set of variables is contained in `s`. This subalgebra is isomorphic to `MvPolynomial s R`. ## Tags variables, polynomial, vars -/ universe u v w namespace MvPolynomial variable {σ : Type*} {R : Type u} section CommSemiring variable [CommSemiring R] {p : MvPolynomial σ R} variable (R) in /-- The set of polynomials whose variables are contained in `s` as a `Subalgebra` over `R`. -/ noncomputable def supported (s : Set σ) : Subalgebra R (MvPolynomial σ R) := Algebra.adjoin R (X '' s) open Algebra theorem supported_eq_range_rename (s : Set σ) : supported R s = (rename ((↑) : s → σ)).range := by rw [supported, Set.image_eq_range, adjoin_range_eq_range_aeval, rename] congr /-- The isomorphism between the subalgebra of polynomials supported by `s` and `MvPolynomial s R`. -/ noncomputable def supportedEquivMvPolynomial (s : Set σ) : supported R s ≃ₐ[R] MvPolynomial s R := (Subalgebra.equivOfEq _ _ (supported_eq_range_rename s)).trans (AlgEquiv.ofInjective (rename ((↑) : s → σ)) (rename_injective _ Subtype.val_injective)).symm @[simp] theorem supportedEquivMvPolynomial_symm_C (s : Set σ) (x : R) : (supportedEquivMvPolynomial s).symm (C x) = algebraMap R (supported R s) x := by ext1 simp [supportedEquivMvPolynomial, MvPolynomial.algebraMap_eq] @[simp] theorem supportedEquivMvPolynomial_symm_X (s : Set σ) (i : s) : (↑((supportedEquivMvPolynomial s).symm (X i : MvPolynomial s R)) : MvPolynomial σ R) = X ↑i := by simp [supportedEquivMvPolynomial] variable {s t : Set σ} theorem mem_supported : p ∈ supported R s ↔ ↑p.vars ⊆ s := by classical rw [supported_eq_range_rename, AlgHom.mem_range] constructor · rintro ⟨p, rfl⟩ refine _root_.trans (Finset.coe_subset.2 (vars_rename _ _)) ?_ simp · intro hs exact exists_rename_eq_of_vars_subset_range p ((↑) : s → σ) Subtype.val_injective (by simpa) theorem supported_eq_vars_subset : (supported R s : Set (MvPolynomial σ R)) = { p | ↑p.vars ⊆ s } := Set.ext fun _ ↦ mem_supported @[simp] theorem mem_supported_vars (p : MvPolynomial σ R) : p ∈ supported R (↑p.vars : Set σ) := by rw [mem_supported] variable (s) theorem supported_eq_adjoin_X : supported R s = Algebra.adjoin R (X '' s) := rfl @[simp] theorem supported_univ : supported R (Set.univ : Set σ) = ⊤ := by simp [Algebra.eq_top_iff, mem_supported] @[simp] theorem supported_empty : supported R (∅ : Set σ) = ⊥ := by simp [supported_eq_adjoin_X] variable {s} theorem supported_mono (st : s ⊆ t) : supported R s ≤ supported R t := Algebra.adjoin_mono (Set.image_mono st) @[simp] theorem X_mem_supported [Nontrivial R] {i : σ} : X i ∈ supported R s ↔ i ∈ s := by simp [mem_supported] @[simp] theorem supported_le_supported_iff [Nontrivial R] : supported R s ≤ supported R t ↔ s ⊆ t := by constructor · intro h i simpa using @h (X i) · exact supported_mono theorem supported_strictMono [Nontrivial R] : StrictMono (supported R : Set σ → Subalgebra R (MvPolynomial σ R)) := strictMono_of_le_iff_le fun _ _ ↦ supported_le_supported_iff.symm theorem exists_restrict_to_vars (R : Type*) [CommRing R] {F : MvPolynomial σ ℤ} (hF : ↑F.vars ⊆ s) : ∃ f : (s → R) → R, ∀ x : σ → R, f (x ∘ (↑) : s → R) = aeval x F := by rw [← mem_supported, supported_eq_range_rename, AlgHom.mem_range] at hF obtain ⟨F', hF'⟩ := hF use fun z ↦ aeval z F' intro x simp only [← hF', aeval_rename] end CommSemiring end MvPolynomial
Real.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import Mathlib.Algebra.BigOperators.Intervals import Mathlib.Topology.Algebra.InfiniteSum.Order import Mathlib.Topology.Instances.ENNReal.Lemmas /-! # Infinite sum in the reals This file provides lemmas about Cauchy sequences in terms of infinite sums and infinite sums valued in the reals. -/ open Filter Finset NNReal Topology variable {α β : Type*} [PseudoMetricSpace α] {f : ℕ → α} {a : α} /-- If the distance between consecutive points of a sequence is estimated by a summable series, then the original sequence is a Cauchy sequence. -/ theorem cauchySeq_of_dist_le_of_summable (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : Summable d) : CauchySeq f := by lift d to ℕ → ℝ≥0 using fun n ↦ dist_nonneg.trans (hf n) apply cauchySeq_of_edist_le_of_summable d (α := α) (f := f) · exact_mod_cast hf · exact_mod_cast hd theorem cauchySeq_of_summable_dist (h : Summable fun n ↦ dist (f n) (f n.succ)) : CauchySeq f := cauchySeq_of_dist_le_of_summable _ (fun _ ↦ le_rfl) h theorem dist_le_tsum_of_dist_le_of_tendsto (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : Summable d) {a : α} (ha : Tendsto f atTop (𝓝 a)) (n : ℕ) : dist (f n) a ≤ ∑' m, d (n + m) := by refine le_of_tendsto (tendsto_const_nhds.dist ha) (eventually_atTop.2 ⟨n, fun m hnm ↦ ?_⟩) refine le_trans (dist_le_Ico_sum_of_dist_le hnm fun _ _ ↦ hf _) ?_ rw [sum_Ico_eq_sum_range] refine Summable.sum_le_tsum (range _) (fun _ _ ↦ le_trans dist_nonneg (hf _)) ?_ exact hd.comp_injective (add_right_injective n) theorem dist_le_tsum_of_dist_le_of_tendsto₀ (d : ℕ → ℝ) (hf : ∀ n, dist (f n) (f n.succ) ≤ d n) (hd : Summable d) (ha : Tendsto f atTop (𝓝 a)) : dist (f 0) a ≤ tsum d := by simpa only [zero_add] using dist_le_tsum_of_dist_le_of_tendsto d hf hd ha 0 theorem dist_le_tsum_dist_of_tendsto (h : Summable fun n ↦ dist (f n) (f n.succ)) (ha : Tendsto f atTop (𝓝 a)) (n) : dist (f n) a ≤ ∑' m, dist (f (n + m)) (f (n + m).succ) := show dist (f n) a ≤ ∑' m, (fun x ↦ dist (f x) (f x.succ)) (n + m) from dist_le_tsum_of_dist_le_of_tendsto (fun n ↦ dist (f n) (f n.succ)) (fun _ ↦ le_rfl) h ha n theorem dist_le_tsum_dist_of_tendsto₀ (h : Summable fun n ↦ dist (f n) (f n.succ)) (ha : Tendsto f atTop (𝓝 a)) : dist (f 0) a ≤ ∑' n, dist (f n) (f n.succ) := by simpa only [zero_add] using dist_le_tsum_dist_of_tendsto h ha 0 section summable theorem not_summable_iff_tendsto_nat_atTop_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬Summable f ↔ Tendsto (fun n : ℕ => ∑ i ∈ Finset.range n, f i) atTop atTop := by lift f to ℕ → ℝ≥0 using hf simpa using mod_cast NNReal.not_summable_iff_tendsto_nat_atTop theorem summable_iff_not_tendsto_nat_atTop_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : Summable f ↔ ¬Tendsto (fun n : ℕ => ∑ i ∈ Finset.range n, f i) atTop atTop := by rw [← not_iff_not, Classical.not_not, not_summable_iff_tendsto_nat_atTop_of_nonneg hf] theorem summable_sigma_of_nonneg {α} {β : α → Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : Summable f ↔ (∀ x, Summable fun y => f ⟨x, y⟩) ∧ Summable fun x => ∑' y, f ⟨x, y⟩ := by lift f to (Σ x, β x) → ℝ≥0 using hf simpa using mod_cast NNReal.summable_sigma lemma summable_partition {α β : Type*} {f : β → ℝ} (hf : 0 ≤ f) {s : α → Set β} (hs : ∀ i, ∃! j, i ∈ s j) : Summable f ↔ (∀ j, Summable fun i : s j ↦ f i) ∧ Summable fun j ↦ ∑' i : s j, f i := by simpa only [← (Set.sigmaEquiv s hs).summable_iff] using summable_sigma_of_nonneg (fun _ ↦ hf _) theorem summable_prod_of_nonneg {α β} {f : (α × β) → ℝ} (hf : 0 ≤ f) : Summable f ↔ (∀ x, Summable fun y ↦ f (x, y)) ∧ Summable fun x ↦ ∑' y, f (x, y) := (Equiv.sigmaEquivProd _ _).summable_iff.symm.trans <| summable_sigma_of_nonneg fun _ ↦ hf _ theorem summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : Finset ι, ∑ x ∈ u, f x ≤ c) : Summable f := ⟨⨆ u : Finset ι, ∑ x ∈ u, f x, tendsto_atTop_ciSup (Finset.sum_mono_set_of_nonneg hf) ⟨c, fun _ ⟨u, hu⟩ => hu ▸ h u⟩⟩ theorem summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i ∈ Finset.range n, f i ≤ c) : Summable f := by refine (summable_iff_not_tendsto_nat_atTop_of_nonneg hf).2 fun H => ?_ rcases exists_lt_of_tendsto_atTop H 0 c with ⟨n, -, hn⟩ exact lt_irrefl _ (hn.trans_le (h n)) theorem Real.tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i ∈ Finset.range n, f i ≤ c) : ∑' n, f n ≤ c := (summable_of_sum_range_le hf h).tsum_le_of_sum_range_le h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ protected theorem Summable.tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ b : ℕ, 0 ≤ f b) (h : ∀ b : ℕ, f b ≤ g b) (hi : f i < g i) (hg : Summable g) : ∑' n, f n < ∑' n, g n := Summable.tsum_lt_tsum h hi (.of_nonneg_of_le h0 h hg) hg @[deprecated (since := "2025-04-12")] alias tsum_lt_tsum_of_nonneg := Summable.tsum_lt_tsum_of_nonneg end summable
Trivialization.lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.Data.Bundle import Mathlib.Data.Set.Image import Mathlib.Topology.CompactOpen import Mathlib.Topology.PartialHomeomorph import Mathlib.Topology.Order.Basic /-! # Trivializations ## Main definitions ### Basic definitions * `Trivialization F p` : structure extending partial homeomorphisms, defining a local trivialization of a topological space `Z` with projection `p` and fiber `F`. * `Pretrivialization F proj` : trivialization as a partial equivalence, mainly used when the topology on the total space has not yet been defined. ### Operations on bundles We provide the following operations on `Trivialization`s. * `Trivialization.compHomeomorph`: given a local trivialization `e` of a fiber bundle `p : Z → B` and a homeomorphism `h : Z' ≃ₜ Z`, returns a local trivialization of the fiber bundle `p ∘ h`. ## Implementation notes Previously, in mathlib, there was a structure `topological_vector_bundle.trivialization` which extended another structure `topological_fiber_bundle.trivialization` by a linearity hypothesis. As of PR https://github.com/leanprover-community/mathlib3/pull/17359, we have changed this to a single structure `Trivialization` (no namespace), together with a mixin class `Trivialization.IsLinear`. This permits all the *data* of a vector bundle to be held at the level of fiber bundles, so that the same trivializations can underlie an object's structure as (say) a vector bundle over `ℂ` and as a vector bundle over `ℝ`, as well as its structure simply as a fiber bundle. This might be a little surprising, given the general trend of the library to ever-increased bundling. But in this case the typical motivation for more bundling does not apply: there is no algebraic or order structure on the whole type of linear (say) trivializations of a bundle. Indeed, since trivializations only have meaning on their base sets (taking junk values outside), the type of linear trivializations is not even particularly well-behaved. -/ open TopologicalSpace Filter Set Bundle Function open scoped Topology variable {B : Type*} (F : Type*) {E : B → Type*} variable {Z : Type*} [TopologicalSpace B] [TopologicalSpace F] {proj : Z → B} /-- This structure contains the information left for a local trivialization (which is implemented below as `Trivialization F proj`) if the total space has not been given a topology, but we have a topology on both the fiber and the base space. Through the construction `topological_fiber_prebundle F proj` it will be possible to promote a `Pretrivialization F proj` to a `Trivialization F proj`. -/ structure Pretrivialization (proj : Z → B) extends PartialEquiv Z (B × F) where open_target : IsOpen target baseSet : Set B open_baseSet : IsOpen baseSet source_eq : source = proj ⁻¹' baseSet target_eq : target = baseSet ×ˢ univ proj_toFun : ∀ p ∈ source, (toFun p).1 = proj p namespace Pretrivialization variable {F} variable (e : Pretrivialization F proj) {x : Z} /-- Coercion of a pretrivialization to a function. We don't use `e.toFun` in the `CoeFun` instance because it is actually `e.toPartialEquiv.toFun`, so `simp` will apply lemmas about `toPartialEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' : Z → (B × F) := e.toFun instance : CoeFun (Pretrivialization F proj) fun _ => Z → B × F := ⟨toFun'⟩ @[ext] lemma ext' (e e' : Pretrivialization F proj) (h₁ : e.toPartialEquiv = e'.toPartialEquiv) (h₂ : e.baseSet = e'.baseSet) : e = e' := by cases e; cases e'; congr -- TODO: move `ext` here? lemma ext {e e' : Pretrivialization F proj} (h₁ : ∀ x, e x = e' x) (h₂ : ∀ x, e.toPartialEquiv.symm x = e'.toPartialEquiv.symm x) (h₃ : e.baseSet = e'.baseSet) : e = e' := by ext1 <;> [ext1; exact h₃] · apply h₁ · apply h₂ · rw [e.source_eq, e'.source_eq, h₃] /-- If the fiber is nonempty, then the projection also is. -/ lemma toPartialEquiv_injective [Nonempty F] : Injective (toPartialEquiv : Pretrivialization F proj → PartialEquiv Z (B × F)) := by refine fun e e' h ↦ ext' _ _ h ?_ simpa only [fst_image_prod, univ_nonempty, target_eq] using congr_arg (Prod.fst '' PartialEquiv.target ·) h @[simp, mfld_simps] theorem coe_coe : ⇑e.toPartialEquiv = e := rfl @[simp, mfld_simps] theorem coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_toFun x ex theorem mem_source : x ∈ e.source ↔ proj x ∈ e.baseSet := by rw [e.source_eq, mem_preimage] theorem coe_fst' (ex : proj x ∈ e.baseSet) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) protected theorem eqOn : EqOn (Prod.fst ∘ e) proj e.source := fun _ hx => e.coe_fst hx theorem mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst ex).symm rfl theorem mk_proj_snd' (ex : proj x ∈ e.baseSet) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst' ex).symm rfl /-- Composition of inverse and coercion from the subtype of the target. -/ def setSymm : e.target → Z := e.target.restrict e.toPartialEquiv.symm theorem mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.baseSet := by rw [e.target_eq, prod_univ, mem_preimage] theorem proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.toPartialEquiv.symm x) = x.1 := by have := (e.coe_fst (e.map_target hx)).symm rwa [← e.coe_coe, e.right_inv hx] at this theorem proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : proj (e.toPartialEquiv.symm (b, x)) = b := e.proj_symm_apply (e.mem_target.2 hx) theorem proj_surjOn_baseSet [Nonempty F] : Set.SurjOn proj e.source e.baseSet := fun b hb => let ⟨y⟩ := ‹Nonempty F› ⟨e.toPartialEquiv.symm (b, y), e.toPartialEquiv.map_target <| e.mem_target.2 hb, e.proj_symm_apply' hb⟩ theorem apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.toPartialEquiv.symm x) = x := e.toPartialEquiv.right_inv hx theorem apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : e (e.toPartialEquiv.symm (b, x)) = (b, x) := e.apply_symm_apply (e.mem_target.2 hx) theorem symm_apply_apply {x : Z} (hx : x ∈ e.source) : e.toPartialEquiv.symm (e x) = x := e.toPartialEquiv.left_inv hx @[simp, mfld_simps] theorem symm_apply_mk_proj {x : Z} (ex : x ∈ e.source) : e.toPartialEquiv.symm (proj x, (e x).2) = x := by rw [← e.coe_fst ex, ← e.coe_coe, e.left_inv ex] @[simp, mfld_simps] theorem preimage_symm_proj_baseSet : e.toPartialEquiv.symm ⁻¹' (proj ⁻¹' e.baseSet) ∩ e.target = e.target := by refine inter_eq_right.mpr fun x hx => ?_ simp only [mem_preimage, e.proj_symm_apply hx] exact e.mem_target.mp hx @[simp, mfld_simps] theorem preimage_symm_proj_inter (s : Set B) : e.toPartialEquiv.symm ⁻¹' (proj ⁻¹' s) ∩ e.baseSet ×ˢ univ = (s ∩ e.baseSet) ×ˢ univ := by ext ⟨x, y⟩ suffices x ∈ e.baseSet → (proj (e.toPartialEquiv.symm (x, y)) ∈ s ↔ x ∈ s) by simpa only [prodMk_mem_set_prod_eq, mem_inter_iff, and_true, mem_univ, and_congr_left_iff] intro h rw [e.proj_symm_apply' h] theorem target_inter_preimage_symm_source_eq (e f : Pretrivialization F proj) : f.target ∩ f.toPartialEquiv.symm ⁻¹' e.source = (e.baseSet ∩ f.baseSet) ×ˢ univ := by rw [inter_comm, f.target_eq, e.source_eq, f.preimage_symm_proj_inter] theorem trans_source (e f : Pretrivialization F proj) : (f.toPartialEquiv.symm.trans e.toPartialEquiv).source = (e.baseSet ∩ f.baseSet) ×ˢ univ := by rw [PartialEquiv.trans_source, PartialEquiv.symm_source, e.target_inter_preimage_symm_source_eq] theorem symm_trans_symm (e e' : Pretrivialization F proj) : (e.toPartialEquiv.symm.trans e'.toPartialEquiv).symm = e'.toPartialEquiv.symm.trans e.toPartialEquiv := by rw [PartialEquiv.trans_symm_eq_symm_trans_symm, PartialEquiv.symm_symm] theorem symm_trans_source_eq (e e' : Pretrivialization F proj) : (e.toPartialEquiv.symm.trans e'.toPartialEquiv).source = (e.baseSet ∩ e'.baseSet) ×ˢ univ := by rw [PartialEquiv.trans_source, e'.source_eq, PartialEquiv.symm_source, e.target_eq, inter_comm, e.preimage_symm_proj_inter, inter_comm] theorem symm_trans_target_eq (e e' : Pretrivialization F proj) : (e.toPartialEquiv.symm.trans e'.toPartialEquiv).target = (e.baseSet ∩ e'.baseSet) ×ˢ univ := by rw [← PartialEquiv.symm_source, symm_trans_symm, symm_trans_source_eq, inter_comm] variable (e' : Pretrivialization F (π F E)) {b : B} {y : E b} @[simp] theorem coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.baseSet := e'.mem_source @[mfld_simps] theorem coe_coe_fst (hb : b ∈ e'.baseSet) : (e' y).1 = b := by simp [hb] theorem mk_mem_target {x : B} {y : F} : (x, y) ∈ e'.target ↔ x ∈ e'.baseSet := e'.mem_target theorem symm_coe_proj {x : B} {y : F} (e' : Pretrivialization F (π F E)) (h : x ∈ e'.baseSet) : (e'.toPartialEquiv.symm (x, y)).1 = x := e'.proj_symm_apply' h section Zero variable [∀ x, Zero (E x)] open Classical in /-- A fiberwise inverse to `e`. This is the function `F → E b` that induces a local inverse `B × F → TotalSpace F E` of `e` on `e.baseSet`. It is defined to be `0` outside `e.baseSet`. -/ protected noncomputable def symm (e : Pretrivialization F (π F E)) (b : B) (y : F) : E b := if hb : b ∈ e.baseSet then cast (congr_arg E (e.proj_symm_apply' hb)) (e.toPartialEquiv.symm (b, y)).2 else 0 theorem symm_apply (e : Pretrivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.toPartialEquiv.symm (b, y)).2 := dif_pos hb theorem symm_apply_of_notMem (e : Pretrivialization F (π F E)) {b : B} (hb : b ∉ e.baseSet) (y : F) : e.symm b y = 0 := dif_neg hb @[deprecated (since := "2025-05-23")] alias symm_apply_of_not_mem := symm_apply_of_notMem theorem coe_symm_of_notMem (e : Pretrivialization F (π F E)) {b : B} (hb : b ∉ e.baseSet) : (e.symm b : F → E b) = 0 := funext fun _ => dif_neg hb @[deprecated (since := "2025-05-23")] alias coe_symm_of_not_mem := coe_symm_of_notMem theorem mk_symm (e : Pretrivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : TotalSpace.mk b (e.symm b y) = e.toPartialEquiv.symm (b, y) := by simp only [e.symm_apply hb, TotalSpace.mk_cast (e.proj_symm_apply' hb), TotalSpace.eta] theorem symm_proj_apply (e : Pretrivialization F (π F E)) (z : TotalSpace F E) (hz : z.proj ∈ e.baseSet) : e.symm z.proj (e z).2 = z.2 := by rw [e.symm_apply hz, cast_eq_iff_heq, e.mk_proj_snd' hz, e.symm_apply_apply (e.mem_source.mpr hz)] theorem symm_apply_apply_mk (e : Pretrivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : E b) : e.symm b (e ⟨b, y⟩).2 = y := e.symm_proj_apply ⟨b, y⟩ hb theorem apply_mk_symm (e : Pretrivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e ⟨b, e.symm b y⟩ = (b, y) := by rw [e.mk_symm hb, e.apply_symm_apply (e.mk_mem_target.mpr hb)] end Zero end Pretrivialization variable [TopologicalSpace Z] [TopologicalSpace (TotalSpace F E)] /-- A structure extending partial homeomorphisms, defining a local trivialization of a projection `proj : Z → B` with fiber `F`, as a partial homeomorphism between `Z` and `B × F` defined between two sets of the form `proj ⁻¹' baseSet` and `baseSet × F`, acting trivially on the first coordinate. -/ structure Trivialization (proj : Z → B) extends PartialHomeomorph Z (B × F) where baseSet : Set B open_baseSet : IsOpen baseSet source_eq : source = proj ⁻¹' baseSet target_eq : target = baseSet ×ˢ univ proj_toFun : ∀ p ∈ source, (toPartialHomeomorph p).1 = proj p namespace Trivialization variable {F} variable (e : Trivialization F proj) {x : Z} @[ext] lemma ext' (e e' : Trivialization F proj) (h₁ : e.toPartialHomeomorph = e'.toPartialHomeomorph) (h₂ : e.baseSet = e'.baseSet) : e = e' := by cases e; cases e'; congr /-- Coercion of a trivialization to a function. We don't use `e.toFun` in the `CoeFun` instance because it is actually `e.toPartialEquiv.toFun`, so `simp` will apply lemmas about `toPartialEquiv`. While we may want to switch to this behavior later, doing it mid-port will break a lot of proofs. -/ @[coe] def toFun' : Z → (B × F) := e.toFun /-- Natural identification as a `Pretrivialization`. -/ def toPretrivialization : Pretrivialization F proj := { e with } instance : CoeFun (Trivialization F proj) fun _ => Z → B × F := ⟨toFun'⟩ instance : Coe (Trivialization F proj) (Pretrivialization F proj) := ⟨toPretrivialization⟩ /-- See Note [custom simps projection] -/ def Simps.apply (proj : Z → B) (e : Trivialization F proj) : Z → B × F := e /-- See Note [custom simps projection] -/ noncomputable def Simps.symm_apply (proj : Z → B) (e : Trivialization F proj) : B × F → Z := e.toPartialHomeomorph.symm initialize_simps_projections Trivialization (toFun → apply, invFun → symm_apply) theorem toPretrivialization_injective : Function.Injective fun e : Trivialization F proj => e.toPretrivialization := fun e e' h => by ext1 exacts [PartialHomeomorph.toPartialEquiv_injective (congr_arg Pretrivialization.toPartialEquiv h), congr_arg Pretrivialization.baseSet h] @[simp, mfld_simps] theorem coe_coe : ⇑e.toPartialHomeomorph = e := rfl @[simp, mfld_simps] theorem coe_fst (ex : x ∈ e.source) : (e x).1 = proj x := e.proj_toFun x ex protected theorem eqOn : EqOn (Prod.fst ∘ e) proj e.source := fun _x hx => e.coe_fst hx theorem mem_source : x ∈ e.source ↔ proj x ∈ e.baseSet := by rw [e.source_eq, mem_preimage] theorem coe_fst' (ex : proj x ∈ e.baseSet) : (e x).1 = proj x := e.coe_fst (e.mem_source.2 ex) theorem mk_proj_snd (ex : x ∈ e.source) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst ex).symm rfl theorem mk_proj_snd' (ex : proj x ∈ e.baseSet) : (proj x, (e x).2) = e x := Prod.ext (e.coe_fst' ex).symm rfl theorem source_inter_preimage_target_inter (s : Set (B × F)) : e.source ∩ e ⁻¹' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.toPartialHomeomorph.source_inter_preimage_target_inter s @[simp, mfld_simps] theorem coe_mk (e : PartialHomeomorph Z (B × F)) (i j k l m) (x : Z) : (Trivialization.mk e i j k l m : Trivialization F proj) x = e x := rfl theorem mem_target {x : B × F} : x ∈ e.target ↔ x.1 ∈ e.baseSet := e.toPretrivialization.mem_target theorem map_target {x : B × F} (hx : x ∈ e.target) : e.toPartialHomeomorph.symm x ∈ e.source := e.toPartialHomeomorph.map_target hx theorem proj_symm_apply {x : B × F} (hx : x ∈ e.target) : proj (e.toPartialHomeomorph.symm x) = x.1 := e.toPretrivialization.proj_symm_apply hx theorem proj_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : proj (e.toPartialHomeomorph.symm (b, x)) = b := e.toPretrivialization.proj_symm_apply' hx theorem proj_surjOn_baseSet [Nonempty F] : Set.SurjOn proj e.source e.baseSet := e.toPretrivialization.proj_surjOn_baseSet theorem apply_symm_apply {x : B × F} (hx : x ∈ e.target) : e (e.toPartialHomeomorph.symm x) = x := e.toPartialHomeomorph.right_inv hx theorem apply_symm_apply' {b : B} {x : F} (hx : b ∈ e.baseSet) : e (e.toPartialHomeomorph.symm (b, x)) = (b, x) := e.toPretrivialization.apply_symm_apply' hx @[simp, mfld_simps] theorem symm_apply_mk_proj (ex : x ∈ e.source) : e.toPartialHomeomorph.symm (proj x, (e x).2) = x := e.toPretrivialization.symm_apply_mk_proj ex theorem symm_trans_source_eq (e e' : Trivialization F proj) : (e.toPartialEquiv.symm.trans e'.toPartialEquiv).source = (e.baseSet ∩ e'.baseSet) ×ˢ univ := Pretrivialization.symm_trans_source_eq e.toPretrivialization e' theorem symm_trans_target_eq (e e' : Trivialization F proj) : (e.toPartialEquiv.symm.trans e'.toPartialEquiv).target = (e.baseSet ∩ e'.baseSet) ×ˢ univ := Pretrivialization.symm_trans_target_eq e.toPretrivialization e' theorem coe_fst_eventuallyEq_proj (ex : x ∈ e.source) : Prod.fst ∘ e =ᶠ[𝓝 x] proj := mem_nhds_iff.2 ⟨e.source, fun _y hy => e.coe_fst hy, e.open_source, ex⟩ theorem coe_fst_eventuallyEq_proj' (ex : proj x ∈ e.baseSet) : Prod.fst ∘ e =ᶠ[𝓝 x] proj := e.coe_fst_eventuallyEq_proj (e.mem_source.2 ex) theorem map_proj_nhds (ex : x ∈ e.source) : map proj (𝓝 x) = 𝓝 (proj x) := by rw [← e.coe_fst ex, ← map_congr (e.coe_fst_eventuallyEq_proj ex), ← map_map, ← e.coe_coe, e.map_nhds_eq ex, map_fst_nhds] theorem preimage_subset_source {s : Set B} (hb : s ⊆ e.baseSet) : proj ⁻¹' s ⊆ e.source := fun _p hp => e.mem_source.mpr (hb hp) theorem image_preimage_eq_prod_univ {s : Set B} (hb : s ⊆ e.baseSet) : e '' (proj ⁻¹' s) = s ×ˢ univ := Subset.antisymm (image_subset_iff.mpr fun p hp => ⟨(e.proj_toFun p (e.preimage_subset_source hb hp)).symm ▸ hp, trivial⟩) fun p hp => let hp' : p ∈ e.target := e.mem_target.mpr (hb hp.1) ⟨e.invFun p, mem_preimage.mpr ((e.proj_symm_apply hp').symm ▸ hp.1), e.apply_symm_apply hp'⟩ theorem tendsto_nhds_iff {α : Type*} {l : Filter α} {f : α → Z} {z : Z} (hz : z ∈ e.source) : Tendsto f l (𝓝 z) ↔ Tendsto (proj ∘ f) l (𝓝 (proj z)) ∧ Tendsto (fun x ↦ (e (f x)).2) l (𝓝 (e z).2) := by rw [e.nhds_eq_comap_inf_principal hz, tendsto_inf, tendsto_comap_iff, Prod.tendsto_iff, coe_coe, tendsto_principal, coe_fst _ hz] by_cases hl : ∀ᶠ x in l, f x ∈ e.source · simp only [hl, and_true] refine (tendsto_congr' ?_).and Iff.rfl exact hl.mono fun x ↦ e.coe_fst · simp only [hl, and_false, false_iff, not_and] rw [e.source_eq] at hl hz exact fun h _ ↦ hl <| h <| e.open_baseSet.mem_nhds hz theorem nhds_eq_inf_comap {z : Z} (hz : z ∈ e.source) : 𝓝 z = comap proj (𝓝 (proj z)) ⊓ comap (Prod.snd ∘ e) (𝓝 (e z).2) := by refine eq_of_forall_le_iff fun l ↦ ?_ rw [le_inf_iff, ← tendsto_iff_comap, ← tendsto_iff_comap] exact e.tendsto_nhds_iff hz /-- The preimage of a subset of the base set is homeomorphic to the product with the fiber. -/ def preimageHomeomorph {s : Set B} (hb : s ⊆ e.baseSet) : proj ⁻¹' s ≃ₜ s × F := (e.toPartialHomeomorph.homeomorphOfImageSubsetSource (e.preimage_subset_source hb) (e.image_preimage_eq_prod_univ hb)).trans ((Homeomorph.Set.prod s univ).trans ((Homeomorph.refl s).prodCongr (Homeomorph.Set.univ F))) @[simp] theorem preimageHomeomorph_apply {s : Set B} (hb : s ⊆ e.baseSet) (p : proj ⁻¹' s) : e.preimageHomeomorph hb p = (⟨proj p, p.2⟩, (e p).2) := Prod.ext (Subtype.ext (e.proj_toFun p (e.mem_source.mpr (hb p.2)))) rfl /-- Auxiliary definition to avoid looping in `dsimp` with `Trivialization.preimageHomeomorph_symm_apply`. -/ protected def preimageHomeomorph_symm_apply.aux {s : Set B} (hb : s ⊆ e.baseSet) := (e.preimageHomeomorph hb).symm @[simp] theorem preimageHomeomorph_symm_apply {s : Set B} (hb : s ⊆ e.baseSet) (p : s × F) : (e.preimageHomeomorph hb).symm p = ⟨e.symm (p.1, p.2), ((preimageHomeomorph_symm_apply.aux e hb) p).2⟩ := rfl /-- The source is homeomorphic to the product of the base set with the fiber. -/ def sourceHomeomorphBaseSetProd : e.source ≃ₜ e.baseSet × F := (Homeomorph.setCongr e.source_eq).trans (e.preimageHomeomorph subset_rfl) @[simp] theorem sourceHomeomorphBaseSetProd_apply (p : e.source) : e.sourceHomeomorphBaseSetProd p = (⟨proj p, e.mem_source.mp p.2⟩, (e p).2) := e.preimageHomeomorph_apply subset_rfl ⟨p, e.mem_source.mp p.2⟩ /-- Auxiliary definition to avoid looping in `dsimp` with `Trivialization.sourceHomeomorphBaseSetProd_symm_apply`. -/ protected def sourceHomeomorphBaseSetProd_symm_apply.aux := e.sourceHomeomorphBaseSetProd.symm @[simp] theorem sourceHomeomorphBaseSetProd_symm_apply (p : e.baseSet × F) : e.sourceHomeomorphBaseSetProd.symm p = ⟨e.symm (p.1, p.2), (sourceHomeomorphBaseSetProd_symm_apply.aux e p).2⟩ := rfl /-- Each fiber of a trivialization is homeomorphic to the specified fiber. -/ def preimageSingletonHomeomorph {b : B} (hb : b ∈ e.baseSet) : proj ⁻¹' {b} ≃ₜ F := .trans (e.preimageHomeomorph (Set.singleton_subset_iff.mpr hb)) <| .trans (.prodCongr (Homeomorph.homeomorphOfUnique ({b} : Set B) PUnit.{1}) (Homeomorph.refl F)) (Homeomorph.punitProd F) @[simp] theorem preimageSingletonHomeomorph_apply {b : B} (hb : b ∈ e.baseSet) (p : proj ⁻¹' {b}) : e.preimageSingletonHomeomorph hb p = (e p).2 := rfl @[simp] theorem preimageSingletonHomeomorph_symm_apply {b : B} (hb : b ∈ e.baseSet) (p : F) : (e.preimageSingletonHomeomorph hb).symm p = ⟨e.symm (b, p), by rw [mem_preimage, e.proj_symm_apply' hb, mem_singleton_iff]⟩ := rfl /-- In the domain of a bundle trivialization, the projection is continuous -/ theorem continuousAt_proj (ex : x ∈ e.source) : ContinuousAt proj x := (e.map_proj_nhds ex).le theorem continuousOn_proj : ContinuousOn proj e.source := continuousOn_of_forall_continuousAt fun _ ↦ e.continuousAt_proj /-- Composition of a `Trivialization` and a `Homeomorph`. -/ protected def compHomeomorph {Z' : Type*} [TopologicalSpace Z'] (h : Z' ≃ₜ Z) : Trivialization F (proj ∘ h) where toPartialHomeomorph := h.toPartialHomeomorph.trans e.toPartialHomeomorph baseSet := e.baseSet open_baseSet := e.open_baseSet source_eq := by simp [source_eq, preimage_preimage, Function.comp_def] target_eq := by simp [target_eq] proj_toFun p hp := by have hp : h p ∈ e.source := by simpa using hp simp [hp] /-- Read off the continuity of a function `f : Z → X` at `z : Z` by transferring via a trivialization of `Z` containing `z`. -/ theorem continuousAt_of_comp_right {X : Type*} [TopologicalSpace X] {f : Z → X} {z : Z} (e : Trivialization F proj) (he : proj z ∈ e.baseSet) (hf : ContinuousAt (f ∘ e.toPartialEquiv.symm) (e z)) : ContinuousAt f z := by have hez : z ∈ e.toPartialEquiv.symm.target := by rw [PartialEquiv.symm_target, e.mem_source] exact he rwa [e.toPartialHomeomorph.symm.continuousAt_iff_continuousAt_comp_right hez, PartialHomeomorph.symm_symm] /-- Read off the continuity of a function `f : X → Z` at `x : X` by transferring via a trivialization of `Z` containing `f x`. -/ theorem continuousAt_of_comp_left {X : Type*} [TopologicalSpace X] {f : X → Z} {x : X} (e : Trivialization F proj) (hf_proj : ContinuousAt (proj ∘ f) x) (he : proj (f x) ∈ e.baseSet) (hf : ContinuousAt (e ∘ f) x) : ContinuousAt f x := by rw [e.continuousAt_iff_continuousAt_comp_left] · exact hf rw [e.source_eq, ← preimage_comp] exact hf_proj.preimage_mem_nhds (e.open_baseSet.mem_nhds he) variable (e' : Trivialization F (π F E)) {b : B} {y : E b} protected theorem continuousOn : ContinuousOn e' e'.source := e'.continuousOn_toFun theorem coe_mem_source : ↑y ∈ e'.source ↔ b ∈ e'.baseSet := e'.mem_source @[simp, mfld_simps] theorem coe_coe_fst (hb : b ∈ e'.baseSet) : (e' y).1 = b := e'.coe_fst (e'.mem_source.2 hb) theorem mk_mem_target {y : F} : (b, y) ∈ e'.target ↔ b ∈ e'.baseSet := e'.toPretrivialization.mem_target theorem symm_apply_apply {x : TotalSpace F E} (hx : x ∈ e'.source) : e'.toPartialHomeomorph.symm (e' x) = x := e'.toPartialEquiv.left_inv hx @[simp, mfld_simps] theorem symm_coe_proj {x : B} {y : F} (e : Trivialization F (π F E)) (h : x ∈ e.baseSet) : (e.toPartialHomeomorph.symm (x, y)).1 = x := e.proj_symm_apply' h section Zero variable [∀ x, Zero (E x)] /-- A fiberwise inverse to `e'`. The function `F → E x` that induces a local inverse `B × F → TotalSpace F E` of `e'` on `e'.baseSet`. It is defined to be `0` outside `e'.baseSet`. -/ protected noncomputable def symm (e : Trivialization F (π F E)) (b : B) (y : F) : E b := e.toPretrivialization.symm b y theorem symm_apply (e : Trivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e.symm b y = cast (congr_arg E (e.symm_coe_proj hb)) (e.toPartialHomeomorph.symm (b, y)).2 := dif_pos hb theorem symm_apply_of_notMem (e : Trivialization F (π F E)) {b : B} (hb : b ∉ e.baseSet) (y : F) : e.symm b y = 0 := dif_neg hb @[deprecated (since := "2025-05-23")] alias symm_apply_of_not_mem := symm_apply_of_notMem theorem mk_symm (e : Trivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : TotalSpace.mk b (e.symm b y) = e.toPartialHomeomorph.symm (b, y) := e.toPretrivialization.mk_symm hb y theorem symm_proj_apply (e : Trivialization F (π F E)) (z : TotalSpace F E) (hz : z.proj ∈ e.baseSet) : e.symm z.proj (e z).2 = z.2 := e.toPretrivialization.symm_proj_apply z hz theorem symm_apply_apply_mk (e : Trivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : E b) : e.symm b (e ⟨b, y⟩).2 = y := e.symm_proj_apply ⟨b, y⟩ hb theorem apply_mk_symm (e : Trivialization F (π F E)) {b : B} (hb : b ∈ e.baseSet) (y : F) : e ⟨b, e.symm b y⟩ = (b, y) := e.toPretrivialization.apply_mk_symm hb y theorem continuousOn_symm (e : Trivialization F (π F E)) : ContinuousOn (fun z : B × F => TotalSpace.mk' F z.1 (e.symm z.1 z.2)) (e.baseSet ×ˢ univ) := by have : ∀ z ∈ e.baseSet ×ˢ (univ : Set F), TotalSpace.mk z.1 (e.symm z.1 z.2) = e.toPartialHomeomorph.symm z := by rintro x ⟨hx : x.1 ∈ e.baseSet, _⟩ rw [e.mk_symm hx] refine ContinuousOn.congr ?_ this rw [← e.target_eq] exact e.toPartialHomeomorph.continuousOn_symm end Zero /-- If `e` is a `Trivialization` of `proj : Z → B` with fiber `F` and `h` is a homeomorphism `F ≃ₜ F'`, then `e.trans_fiber_homeomorph h` is the trivialization of `proj` with the fiber `F'` that sends `p : Z` to `((e p).1, h (e p).2)`. -/ def transFiberHomeomorph {F' : Type*} [TopologicalSpace F'] (e : Trivialization F proj) (h : F ≃ₜ F') : Trivialization F' proj where toPartialHomeomorph := e.toPartialHomeomorph.transHomeomorph <| (Homeomorph.refl _).prodCongr h baseSet := e.baseSet open_baseSet := e.open_baseSet source_eq := e.source_eq target_eq := by simp [target_eq, prod_univ, preimage_preimage] proj_toFun := e.proj_toFun @[simp] theorem transFiberHomeomorph_apply {F' : Type*} [TopologicalSpace F'] (e : Trivialization F proj) (h : F ≃ₜ F') (x : Z) : e.transFiberHomeomorph h x = ((e x).1, h (e x).2) := rfl /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations. See also `Trivialization.coordChangeHomeomorph` for a version bundled as `F ≃ₜ F`. -/ def coordChange (e₁ e₂ : Trivialization F proj) (b : B) (x : F) : F := (e₂ <| e₁.toPartialHomeomorph.symm (b, x)).2 theorem mk_coordChange (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) (x : F) : (b, e₁.coordChange e₂ b x) = e₂ (e₁.toPartialHomeomorph.symm (b, x)) := by refine Prod.ext ?_ rfl rw [e₂.coe_fst', ← e₁.coe_fst', e₁.apply_symm_apply' h₁] · rwa [e₁.proj_symm_apply' h₁] · rwa [e₁.proj_symm_apply' h₁] theorem coordChange_apply_snd (e₁ e₂ : Trivialization F proj) {p : Z} (h : proj p ∈ e₁.baseSet) : e₁.coordChange e₂ (proj p) (e₁ p).snd = (e₂ p).snd := by rw [coordChange, e₁.symm_apply_mk_proj (e₁.mem_source.2 h)] theorem coordChange_same_apply (e : Trivialization F proj) {b : B} (h : b ∈ e.baseSet) (x : F) : e.coordChange e b x = x := by rw [coordChange, e.apply_symm_apply' h] theorem coordChange_same (e : Trivialization F proj) {b : B} (h : b ∈ e.baseSet) : e.coordChange e b = id := funext <| e.coordChange_same_apply h theorem coordChange_coordChange (e₁ e₂ e₃ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) (x : F) : e₂.coordChange e₃ b (e₁.coordChange e₂ b x) = e₁.coordChange e₃ b x := by rw [coordChange, e₁.mk_coordChange _ h₁ h₂, ← e₂.coe_coe, e₂.left_inv, coordChange] rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] theorem continuous_coordChange (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : Continuous (e₁.coordChange e₂ b) := by refine continuous_snd.comp (e₂.toPartialHomeomorph.continuousOn.comp_continuous (e₁.toPartialHomeomorph.continuousOn_symm.comp_continuous ?_ ?_) ?_) · fun_prop · exact fun x => e₁.mem_target.2 h₁ · intro x rwa [e₂.mem_source, e₁.proj_symm_apply' h₁] /-- Coordinate transformation in the fiber induced by a pair of bundle trivializations, as a homeomorphism. -/ protected def coordChangeHomeomorph (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : F ≃ₜ F where toFun := e₁.coordChange e₂ b invFun := e₂.coordChange e₁ b left_inv x := by simp only [*, coordChange_coordChange, coordChange_same_apply] right_inv x := by simp only [*, coordChange_coordChange, coordChange_same_apply] continuous_toFun := e₁.continuous_coordChange e₂ h₁ h₂ continuous_invFun := e₂.continuous_coordChange e₁ h₂ h₁ @[simp] theorem coordChangeHomeomorph_coe (e₁ e₂ : Trivialization F proj) {b : B} (h₁ : b ∈ e₁.baseSet) (h₂ : b ∈ e₂.baseSet) : ⇑(e₁.coordChangeHomeomorph e₂ h₁ h₂) = e₁.coordChange e₂ b := rfl theorem isImage_preimage_prod (e : Trivialization F proj) (s : Set B) : e.toPartialHomeomorph.IsImage (proj ⁻¹' s) (s ×ˢ univ) := fun x hx => by simp [hx] /-- Restrict a `Trivialization` to an open set in the base. -/ protected def restrOpen (e : Trivialization F proj) (s : Set B) (hs : IsOpen s) : Trivialization F proj where toPartialHomeomorph := ((e.isImage_preimage_prod s).symm.restr (IsOpen.inter e.open_target (hs.prod isOpen_univ))).symm baseSet := e.baseSet ∩ s open_baseSet := IsOpen.inter e.open_baseSet hs source_eq := by simp [source_eq] target_eq := by simp [target_eq, prod_univ] proj_toFun p hp := e.proj_toFun p hp.1 section Piecewise theorem frontier_preimage (e : Trivialization F proj) (s : Set B) : e.source ∩ frontier (proj ⁻¹' s) = proj ⁻¹' (e.baseSet ∩ frontier s) := by rw [← (e.isImage_preimage_prod s).frontier.preimage_eq, frontier_prod_univ_eq, (e.isImage_preimage_prod _).preimage_eq, e.source_eq, preimage_inter] open Classical in /-- Given two bundle trivializations `e`, `e'` of `proj : Z → B` and a set `s : Set B` such that the base sets of `e` and `e'` intersect `frontier s` on the same set and `e p = e' p` whenever `proj p ∈ e.baseSet ∩ frontier s`, `e.piecewise e' s Hs Heq` is the bundle trivialization over `Set.ite s e.baseSet e'.baseSet` that is equal to `e` on `proj ⁻¹ s` and is equal to `e'` otherwise. -/ noncomputable def piecewise (e e' : Trivialization F proj) (s : Set B) (Hs : e.baseSet ∩ frontier s = e'.baseSet ∩ frontier s) (Heq : EqOn e e' <| proj ⁻¹' (e.baseSet ∩ frontier s)) : Trivialization F proj where toPartialHomeomorph := e.toPartialHomeomorph.piecewise e'.toPartialHomeomorph (proj ⁻¹' s) (s ×ˢ univ) (e.isImage_preimage_prod s) (e'.isImage_preimage_prod s) (by rw [e.frontier_preimage, e'.frontier_preimage, Hs]) (by rwa [e.frontier_preimage]) baseSet := s.ite e.baseSet e'.baseSet open_baseSet := e.open_baseSet.ite e'.open_baseSet Hs source_eq := by simp [source_eq] target_eq := by simp [target_eq, prod_univ] proj_toFun p := by rintro (⟨he, hs⟩ | ⟨he, hs⟩) <;> simp [*] /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.baseSet ∩ e'.baseSet` such that `e` equals `e'` on `proj ⁻¹' {a}`, `e.piecewise_le_of_eq e' a He He' Heq` is the bundle trivialization over `Set.ite (Iic a) e.baseSet e'.baseSet` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `e'` otherwise. -/ noncomputable def piecewiseLeOfEq [LinearOrder B] [OrderTopology B] (e e' : Trivialization F proj) (a : B) (He : a ∈ e.baseSet) (He' : a ∈ e'.baseSet) (Heq : ∀ p, proj p = a → e p = e' p) : Trivialization F proj := e.piecewise e' (Iic a) (Set.ext fun x => and_congr_left_iff.2 fun hx => by obtain rfl : x = a := mem_singleton_iff.1 (frontier_Iic_subset _ hx) simp [He, He']) fun p hp => Heq p <| frontier_Iic_subset _ hp.2 /-- Given two bundle trivializations `e`, `e'` of a topological fiber bundle `proj : Z → B` over a linearly ordered base `B` and a point `a ∈ e.baseSet ∩ e'.baseSet`, `e.piecewise_le e' a He He'` is the bundle trivialization over `Set.ite (Iic a) e.baseSet e'.baseSet` that is equal to `e` on points `p` such that `proj p ≤ a` and is equal to `((e' p).1, h (e' p).2)` otherwise, where `h = e'.coord_change_homeomorph e _ _` is the homeomorphism of the fiber such that `h (e' p).2 = (e p).2` whenever `e p = a`. -/ noncomputable def piecewiseLe [LinearOrder B] [OrderTopology B] (e e' : Trivialization F proj) (a : B) (He : a ∈ e.baseSet) (He' : a ∈ e'.baseSet) : Trivialization F proj := e.piecewiseLeOfEq (e'.transFiberHomeomorph (e'.coordChangeHomeomorph e He' He)) a He He' <| by rintro p rfl ext1 · simp [e.coe_fst', e'.coe_fst', *] · simp [coordChange_apply_snd, *] open Classical in /-- Given two bundle trivializations `e`, `e'` over disjoint sets, `e.disjoint_union e' H` is the bundle trivialization over the union of the base sets that agrees with `e` and `e'` over their base sets. -/ noncomputable def disjointUnion (e e' : Trivialization F proj) (H : Disjoint e.baseSet e'.baseSet) : Trivialization F proj where toPartialHomeomorph := e.toPartialHomeomorph.disjointUnion e'.toPartialHomeomorph (by rw [e.source_eq, e'.source_eq] exact H.preimage _) (by rw [e.target_eq, e'.target_eq, disjoint_iff_inf_le] intro x hx exact H.le_bot ⟨hx.1.1, hx.2.1⟩) baseSet := e.baseSet ∪ e'.baseSet open_baseSet := IsOpen.union e.open_baseSet e'.open_baseSet source_eq := congr_arg₂ (· ∪ ·) e.source_eq e'.source_eq target_eq := (congr_arg₂ (· ∪ ·) e.target_eq e'.target_eq).trans union_prod.symm proj_toFun := by rintro p (hp | hp') · change (e.source.piecewise e e' p).1 = proj p rw [piecewise_eq_of_mem, e.coe_fst] <;> exact hp · change (e.source.piecewise e e' p).1 = proj p rw [piecewise_eq_of_notMem, e'.coe_fst hp'] simp only [source_eq] at hp' ⊢ exact fun h => H.le_bot ⟨h, hp'⟩ end Piecewise section Lift /-- The local lifting through a Trivialization `T` from the base to the leaf containing `z`. -/ def lift (T : Trivialization F proj) (z : Z) (b : B) : Z := T.invFun (b, (T z).2) variable {T : Trivialization F proj} {z : Z} {b : B} @[simp] theorem lift_self (he : proj z ∈ T.baseSet) : T.lift z (proj z) = z := symm_apply_mk_proj _ <| T.mem_source.2 he theorem proj_lift (hx : b ∈ T.baseSet) : proj (T.lift z b) = b := T.proj_symm_apply <| T.mem_target.2 hx /-- The restriction of `lift` to the source and base set of `T`, as a bundled continuous map. -/ def liftCM (T : Trivialization F proj) : C(T.source × T.baseSet, T.source) where toFun ex := ⟨T.lift ex.1 ex.2, T.map_target (by simp [mem_target])⟩ continuous_toFun := by apply Continuous.subtype_mk refine T.continuousOn_invFun.comp_continuous ?_ (by simp [mem_target]) refine .prodMk (by fun_prop) (.snd ?_) exact T.continuousOn_toFun.comp_continuous (by fun_prop) (by simp) variable {ι : Type*} [TopologicalSpace ι] [LocallyCompactPair ι T.baseSet] {γ : C(ι, T.baseSet)} {i : ι} {e : T.source} /-- Extension of `liftCM` to continuous maps taking values in `T.baseSet` (local version of homotopy lifting) -/ def clift (T : Trivialization F proj) [LocallyCompactPair ι T.baseSet] : C(T.source × C(ι, T.baseSet), C(ι, T.source)) := by let Ψ : C((T.source × C(ι, T.baseSet)) × ι, C(ι, T.baseSet) × ι) := ⟨fun eγt => (eγt.1.2, eγt.2), by fun_prop⟩ refine ContinuousMap.curry <| T.liftCM.comp <| ⟨fun eγt => ⟨eγt.1.1, eγt.1.2 eγt.2⟩, ?_⟩ simpa using ⟨by fun_prop, ContinuousEval.continuous_eval.comp Ψ.continuous⟩ @[simp] theorem clift_self (h : proj e.1 = γ i) : T.clift (e, γ) i = e := by have : proj e ∈ T.baseSet := by simp [h] simp [clift, liftCM, ← h, lift_self, this] theorem proj_clift : proj (T.clift (e, γ) i) = γ i := by simp [clift, liftCM, proj_lift] end Lift end Trivialization
Basic.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.Algebra.BigOperators.Group.List.Lemmas import Mathlib.Algebra.BigOperators.Group.Multiset.Defs import Mathlib.Algebra.Group.Prod import Mathlib.Algebra.Order.Group.Multiset import Mathlib.Algebra.Order.Sub.Unbundled.Basic /-! # Sums and products over multisets In this file we define products and sums indexed by multisets. This is later used to define products and sums indexed by finite sets. ## Main declarations * `Multiset.prod`: `s.prod f` is the product of `f i` over all `i ∈ s`. Not to be mistaken with the cartesian product `Multiset.product`. * `Multiset.sum`: `s.sum f` is the sum of `f i` over all `i ∈ s`. -/ assert_not_exists MonoidWithZero variable {F ι κ G M N O : Type*} namespace Multiset section CommMonoid variable [CommMonoid M] [CommMonoid N] {s t : Multiset M} {a : M} {m : Multiset ι} {f g : ι → M} @[to_additive (attr := simp)] theorem prod_erase [DecidableEq M] (h : a ∈ s) : a * (s.erase a).prod = s.prod := by rw [← s.coe_toList, coe_erase, prod_coe, prod_coe, List.prod_erase (mem_toList.2 h)] @[to_additive (attr := simp)] theorem prod_map_erase [DecidableEq ι] {a : ι} (h : a ∈ m) : f a * ((m.erase a).map f).prod = (m.map f).prod := by rw [← m.coe_toList, coe_erase, map_coe, map_coe, prod_coe, prod_coe, List.prod_map_erase f (mem_toList.2 h)] @[to_additive (attr := simp, grind =)] theorem prod_add (s t : Multiset M) : prod (s + t) = prod s * prod t := Quotient.inductionOn₂ s t fun l₁ l₂ => by simp @[to_additive] theorem prod_nsmul (m : Multiset M) : ∀ n : ℕ, (n • m).prod = m.prod ^ n | 0 => by rw [zero_nsmul, pow_zero] rfl | n + 1 => by rw [add_nsmul, one_nsmul, pow_add, pow_one, prod_add, prod_nsmul m n] @[to_additive] theorem prod_filter_mul_prod_filter_not (p) [DecidablePred p] : (s.filter p).prod * (s.filter (fun a ↦ ¬ p a)).prod = s.prod := by rw [← prod_add, filter_add_not] @[to_additive] theorem prod_map_eq_pow_single [DecidableEq ι] (i : ι) (hf : ∀ i' ≠ i, i' ∈ m → f i' = 1) : (m.map f).prod = f i ^ m.count i := by induction m using Quotient.inductionOn simp [List.prod_map_eq_pow_single i f hf] @[to_additive] theorem prod_eq_pow_single [DecidableEq M] (a : M) (h : ∀ a' ≠ a, a' ∈ s → a' = 1) : s.prod = a ^ s.count a := by induction s using Quotient.inductionOn; simp [List.prod_eq_pow_single a h] @[to_additive] lemma prod_eq_one (h : ∀ x ∈ s, x = (1 : M)) : s.prod = 1 := by induction s using Quotient.inductionOn; simp [List.prod_eq_one h] @[to_additive] theorem prod_hom_ne_zero {s : Multiset M} (hs : s ≠ 0) {F : Type*} [FunLike F M N] [MulHomClass F M N] (f : F) : (s.map f).prod = f s.prod := by induction s using Quot.inductionOn; aesop (add simp List.prod_hom_nonempty) @[to_additive] theorem prod_hom (s : Multiset M) {F : Type*} [FunLike F M N] [MonoidHomClass F M N] (f : F) : (s.map f).prod = f s.prod := Quotient.inductionOn s fun l => by simp only [l.prod_hom f, quot_mk_to_coe, map_coe, prod_coe] @[to_additive] theorem prod_hom' (s : Multiset ι) {F : Type*} [FunLike F M N] [MonoidHomClass F M N] (f : F) (g : ι → M) : (s.map fun i => f <| g i).prod = f (s.map g).prod := by convert (s.map g).prod_hom f exact (map_map _ _ _).symm @[to_additive] theorem prod_hom₂_ne_zero [CommMonoid O] {s : Multiset ι} (hs : s ≠ 0) (f : M → N → O) (hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (f₁ : ι → M) (f₂ : ι → N) : (s.map fun i => f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod := by induction s using Quotient.inductionOn; aesop (add simp List.prod_hom₂_nonempty) @[to_additive] theorem prod_hom₂ [CommMonoid O] (s : Multiset ι) (f : M → N → O) (hf : ∀ a b c d, f (a * b) (c * d) = f a c * f b d) (hf' : f 1 1 = 1) (f₁ : ι → M) (f₂ : ι → N) : (s.map fun i => f (f₁ i) (f₂ i)).prod = f (s.map f₁).prod (s.map f₂).prod := Quotient.inductionOn s fun l => by simp only [l.prod_hom₂ f hf hf', quot_mk_to_coe, map_coe, prod_coe] @[to_additive (attr := simp)] theorem prod_map_mul : (m.map fun i => f i * g i).prod = (m.map f).prod * (m.map g).prod := m.prod_hom₂ (· * ·) mul_mul_mul_comm (mul_one _) _ _ @[to_additive] theorem prod_map_pow {n : ℕ} : (m.map fun i => f i ^ n).prod = (m.map f).prod ^ n := m.prod_hom' (powMonoidHom n : M →* M) f @[to_additive] theorem prod_map_prod_map (m : Multiset ι) (n : Multiset κ) {f : ι → κ → M} : prod (m.map fun a => prod <| n.map fun b => f a b) = prod (n.map fun b => prod <| m.map fun a => f a b) := Multiset.induction_on m (by simp) fun a m ih => by simp [ih] theorem prod_dvd_prod_of_le (h : s ≤ t) : s.prod ∣ t.prod := by obtain ⟨z, rfl⟩ := exists_add_of_le h simp only [prod_add, dvd_mul_right] @[to_additive] lemma _root_.map_multiset_prod [FunLike F M N] [MonoidHomClass F M N] (f : F) (s : Multiset M) : f s.prod = (s.map f).prod := (s.prod_hom f).symm @[to_additive] lemma _root_.map_multiset_ne_zero_prod [FunLike F M N] [MulHomClass F M N] (f : F) {s : Multiset M} (hs : s ≠ 0) : f s.prod = (s.map f).prod := (s.prod_hom_ne_zero hs f).symm @[to_additive] protected lemma _root_.MonoidHom.map_multiset_prod (f : M →* N) (s : Multiset M) : f s.prod = (s.map f).prod := (s.prod_hom f).symm @[to_additive] protected lemma _root_.MulHom.map_multiset_ne_zero_prod (f : M →ₙ* N) (s : Multiset M) (hs : s ≠ 0) : f s.prod = (s.map f).prod := (s.prod_hom_ne_zero hs f).symm lemma dvd_prod : a ∈ s → a ∣ s.prod := Quotient.inductionOn s (fun l a h ↦ by simpa using List.dvd_prod h) a @[to_additive] lemma fst_prod (s : Multiset (M × N)) : s.prod.1 = (s.map Prod.fst).prod := map_multiset_prod (MonoidHom.fst _ _) _ @[to_additive] lemma snd_prod (s : Multiset (M × N)) : s.prod.2 = (s.map Prod.snd).prod := map_multiset_prod (MonoidHom.snd _ _) _ end CommMonoid theorem prod_dvd_prod_of_dvd [CommMonoid N] {S : Multiset M} (g1 g2 : M → N) (h : ∀ a ∈ S, g1 a ∣ g2 a) : (Multiset.map g1 S).prod ∣ (Multiset.map g2 S).prod := by apply Multiset.induction_on' S · simp intro a T haS _ IH simp [mul_dvd_mul (h a haS) IH] section AddCommMonoid variable [AddCommMonoid M] /-- `Multiset.sum`, the sum of the elements of a multiset, promoted to a morphism of `AddCommMonoid`s. -/ def sumAddMonoidHom : Multiset M →+ M where toFun := sum map_zero' := sum_zero map_add' := sum_add @[simp] theorem coe_sumAddMonoidHom : (sumAddMonoidHom : Multiset M → M) = sum := rfl end AddCommMonoid section DivisionCommMonoid variable [DivisionCommMonoid G] {m : Multiset ι} {f g : ι → G} @[to_additive] theorem prod_map_inv' (m : Multiset G) : (m.map Inv.inv).prod = m.prod⁻¹ := m.prod_hom (invMonoidHom : G →* G) @[to_additive (attr := simp)] theorem prod_map_inv : (m.map fun i => (f i)⁻¹).prod = (m.map f).prod⁻¹ := by rw [← (m.map f).prod_map_inv', map_map, Function.comp_def] @[to_additive (attr := simp)] theorem prod_map_div : (m.map fun i => f i / g i).prod = (m.map f).prod / (m.map g).prod := m.prod_hom₂ (· / ·) mul_div_mul_comm (div_one _) _ _ @[to_additive] theorem prod_map_zpow {n : ℤ} : (m.map fun i => f i ^ n).prod = (m.map f).prod ^ n := by convert (m.map f).prod_hom (zpowGroupHom n : G →* G) simp only [map_map, Function.comp_apply, zpowGroupHom_apply] end DivisionCommMonoid @[simp] theorem sum_map_singleton (s : Multiset M) : (s.map fun a => ({a} : Multiset M)).sum = s := Multiset.induction_on s (by simp) (by simp) theorem sum_nat_mod (s : Multiset ℕ) (n : ℕ) : s.sum % n = (s.map (· % n)).sum % n := by induction s using Multiset.induction <;> simp [Nat.add_mod, *] theorem prod_nat_mod (s : Multiset ℕ) (n : ℕ) : s.prod % n = (s.map (· % n)).prod % n := by induction s using Multiset.induction <;> simp [Nat.mul_mod, *] theorem sum_int_mod (s : Multiset ℤ) (n : ℤ) : s.sum % n = (s.map (· % n)).sum % n := by induction s using Multiset.induction <;> simp [Int.add_emod, *] theorem prod_int_mod (s : Multiset ℤ) (n : ℤ) : s.prod % n = (s.map (· % n)).prod % n := by induction s using Multiset.induction <;> simp [Int.mul_emod, *] section OrderedSub theorem sum_map_tsub [AddCommMonoid M] [PartialOrder M] [ExistsAddOfLE M] [AddLeftMono M] [AddLeftReflectLE M] [Sub M] [OrderedSub M] (l : Multiset ι) {f g : ι → M} (hfg : ∀ x ∈ l, g x ≤ f x) : (l.map fun x ↦ f x - g x).sum = (l.map f).sum - (l.map g).sum := eq_tsub_of_add_eq <| by rw [← sum_map_add] congr 1 exact map_congr rfl fun x hx => tsub_add_cancel_of_le <| hfg _ hx end OrderedSub end Multiset
NielsenSchreier.lean
/- Copyright (c) 2021 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import Mathlib.CategoryTheory.Action import Mathlib.Combinatorics.Quiver.Arborescence import Mathlib.Combinatorics.Quiver.ConnectedComponent import Mathlib.GroupTheory.FreeGroup.IsFreeGroup /-! # The Nielsen-Schreier theorem This file proves that a subgroup of a free group is itself free. ## Main result - `subgroupIsFreeOfIsFree H`: an instance saying that a subgroup of a free group is free. ## Proof overview The proof is analogous to the proof using covering spaces and fundamental groups of graphs, but we work directly with groupoids instead of topological spaces. Under this analogy, - `IsFreeGroupoid G` corresponds to saying that a space is a graph. - `endMulEquivSubgroup H` plays the role of replacing 'subgroup of fundamental group' with 'fundamental group of covering space'. - `actionGroupoidIsFree G A` corresponds to the fact that a covering of a (single-vertex) graph is a graph. - `endIsFree T` corresponds to the fact that, given a spanning tree `T` of a graph, its fundamental group is free (generated by loops from the complement of the tree). ## Implementation notes Our definition of `IsFreeGroupoid` is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from the generators, but we only consider _groups_ `X`. This simplifies the argument since functor equality is complicated in general, but simple for functors to single object categories. ## References https://ncatlab.org/nlab/show/Nielsen-Schreier+theorem ## Tags free group, free groupoid, Nielsen-Schreier -/ noncomputable section universe v u /- Porting note: ./././Mathport/Syntax/Translate/Command.lean:229:11:unsupported: unusual advanced open style -/ open CategoryTheory CategoryTheory.ActionCategory CategoryTheory.SingleObj Quiver FreeGroup /-- `IsFreeGroupoid.Generators G` is a type synonym for `G`. We think of this as the vertices of the generating quiver of `G` when `G` is free. We can't use `G` directly, since `G` already has a quiver instance from being a groupoid. -/ @[nolint unusedArguments] def IsFreeGroupoid.Generators (G) [Groupoid G] := G /-- A groupoid `G` is free when we have the following data: - a quiver on `IsFreeGroupoid.Generators G` (a type synonym for `G`) - a function `of` taking a generating arrow to a morphism in `G` - such that a functor from `G` to any group `X` is uniquely determined by assigning labels in `X` to the generating arrows. This definition is nonstandard. Normally one would require that functors `G ⥤ X` to any _groupoid_ `X` are given by graph homomorphisms from `generators`. -/ class IsFreeGroupoid (G) [Groupoid.{v} G] where quiverGenerators : Quiver.{v + 1} (IsFreeGroupoid.Generators G) of : ∀ {a b : IsFreeGroupoid.Generators G}, (a ⟶ b) → ((show G from a) ⟶ b) unique_lift : ∀ {X : Type v} [Group X] (f : Labelling (IsFreeGroupoid.Generators G) X), ∃! F : G ⥤ CategoryTheory.SingleObj X, ∀ (a b) (g : a ⟶ b), F.map (of g) = f g attribute [nolint docBlame] IsFreeGroupoid.of IsFreeGroupoid.unique_lift namespace IsFreeGroupoid attribute [instance] quiverGenerators /-- Two functors from a free groupoid to a group are equal when they agree on the generating quiver. -/ @[ext] theorem ext_functor {G} [Groupoid.{v} G] [IsFreeGroupoid G] {X : Type v} [Group X] (f g : G ⥤ CategoryTheory.SingleObj X) (h : ∀ (a b) (e : a ⟶ b), f.map (of e) = g.map (of e)) : f = g := let ⟨_, _, u⟩ := @unique_lift G _ _ X _ fun (a b : Generators G) (e : a ⟶ b) => g.map (of e) _root_.trans (u _ h) (u _ fun _ _ _ => rfl).symm /-- An action groupoid over a free group is free. More generally, one could show that the groupoid of elements over a free groupoid is free, but this version is easier to prove and suffices for our purposes. Analogous to the fact that a covering space of a graph is a graph. (A free groupoid is like a graph, and a groupoid of elements is like a covering space.) -/ instance actionGroupoidIsFree {G A : Type u} [Group G] [IsFreeGroup G] [MulAction G A] : IsFreeGroupoid (ActionCategory G A) where quiverGenerators := ⟨fun a b => { e : IsFreeGroup.Generators G // IsFreeGroup.of e • a.back = b.back }⟩ of := fun (e : Subtype _) => ⟨IsFreeGroup.of e, e.property⟩ unique_lift := by intro X _ f let f' : IsFreeGroup.Generators G → (A → X) ⋊[mulAutArrow] G := fun e => ⟨fun b => @f ⟨(), _⟩ ⟨(), b⟩ ⟨e, smul_inv_smul _ b⟩, IsFreeGroup.of e⟩ rcases IsFreeGroup.unique_lift f' with ⟨F', hF', uF'⟩ refine ⟨uncurry F' ?_, ?_, ?_⟩ · suffices SemidirectProduct.rightHom.comp F' = MonoidHom.id _ by exact DFunLike.ext_iff.mp this apply IsFreeGroup.ext_hom (fun x ↦ ?_) rw [MonoidHom.comp_apply, hF'] rfl · rintro ⟨⟨⟩, a : A⟩ ⟨⟨⟩, b⟩ ⟨e, h : IsFreeGroup.of e • a = b⟩ change (F' (IsFreeGroup.of _)).left _ = _ rw [hF'] cases inv_smul_eq_iff.mpr h.symm rfl · intro E hE have : curry E = F' := by apply uF' intro e ext · convert hE _ _ _ rfl · rfl apply Functor.hext · intro apply Unit.ext · refine ActionCategory.cases ?_ intros simp only [← this, uncurry_map, curry_apply_left, coe_back, homOfPair.val] rfl namespace SpanningTree /- In this section, we suppose we have a free groupoid with a spanning tree for its generating quiver. The goal is to prove that the vertex group at the root is free. A picture to have in mind is that we are 'pulling' the endpoints of all the edges of the quiver along the spanning tree to the root. -/ variable {G : Type u} [Groupoid.{u} G] [IsFreeGroupoid G] (T : WideSubquiver (Symmetrify <| Generators G)) [Arborescence T] /-- The root of `T`, except its type is `G` instead of the type synonym `T`. -/ private def root' : G := show T from root T -- this has to be marked noncomputable, see issue https://github.com/leanprover-community/mathlib4/pull/451. -- It might be nicer to define this in terms of `composePath` /-- A path in the tree gives a hom, by composition. -/ -- Porting note: removed noncomputable. This is already declared at the beginning of the section. def homOfPath : ∀ {a : G}, Path (root T) a → (root' T ⟶ a) | _, Path.nil => 𝟙 _ | _, Path.cons p f => homOfPath p ≫ Sum.recOn f.val (fun e => of e) fun e => inv (of e) /-- For every vertex `a`, there is a canonical hom from the root, given by the path in the tree. -/ def treeHom (a : G) : root' T ⟶ a := homOfPath T default /-- Any path to `a` gives `treeHom T a`, since paths in the tree are unique. -/ theorem treeHom_eq {a : G} (p : Path (root T) a) : treeHom T a = homOfPath T p := by rw [treeHom, Unique.default_eq] @[simp] theorem treeHom_root : treeHom T (root' T) = 𝟙 _ := -- this should just be `treeHom_eq T Path.nil`, but Lean treats `homOfPath` with suspicion. _root_.trans (treeHom_eq T Path.nil) rfl /-- Any hom in `G` can be made into a loop, by conjugating with `treeHom`s. -/ def loopOfHom {a b : G} (p : a ⟶ b) : End (root' T) := treeHom T a ≫ p ≫ inv (treeHom T b) /-- Turning an edge in the spanning tree into a loop gives the identity loop. -/ theorem loopOfHom_eq_id {a b : Generators G} (e) (H : e ∈ wideSubquiverSymmetrify T a b) : loopOfHom T (of e) = 𝟙 (root' T) := by rw [loopOfHom, ← Category.assoc, IsIso.comp_inv_eq, Category.id_comp] rcases H with H | H · rw [treeHom_eq T (Path.cons default ⟨Sum.inl e, H⟩), homOfPath] rfl · rw [treeHom_eq T (Path.cons default ⟨Sum.inr e, H⟩), homOfPath] simp only [IsIso.inv_hom_id, Category.comp_id, Category.assoc, treeHom] /-- Since a hom gives a loop, any homomorphism from the vertex group at the root extends to a functor on the whole groupoid. -/ @[simps] def functorOfMonoidHom {X} [Monoid X] (f : End (root' T) →* X) : G ⥤ CategoryTheory.SingleObj X where obj _ := () map p := f (loopOfHom T p) map_id := by intro a dsimp only [loopOfHom] rw [Category.id_comp, IsIso.hom_inv_id, ← End.one_def, f.map_one, id_as_one] map_comp := by intros rw [comp_as_mul, ← f.map_mul] simp only [IsIso.inv_hom_id_assoc, loopOfHom, End.mul_def, Category.assoc] open scoped Classical in /-- Given a free groupoid and an arborescence of its generating quiver, the vertex group at the root is freely generated by loops coming from generating arrows in the complement of the tree. -/ lemma endIsFree : IsFreeGroup (End (root' T)) := IsFreeGroup.ofUniqueLift ((wideSubquiverEquivSetTotal <| wideSubquiverSymmetrify T)ᶜ : Set _) (fun e => loopOfHom T (of e.val.hom)) (by intro X _ f let f' : Labelling (Generators G) X := fun a b e => if h : e ∈ wideSubquiverSymmetrify T a b then 1 else f ⟨⟨a, b, e⟩, h⟩ rcases unique_lift f' with ⟨F', hF', uF'⟩ refine ⟨F'.mapEnd _, ?_, ?_⟩ · suffices ∀ {x y} (q : x ⟶ y), F'.map (loopOfHom T q) = (F'.map q : X) by rintro ⟨⟨a, b, e⟩, h⟩ -- Work around the defeq `X = End (F'.obj (IsFreeGroupoid.SpanningTree.root' T))` erw [Functor.mapEnd_apply] rw [this, hF'] exact dif_neg h intros x y q suffices ∀ {a} (p : Path (root T) a), F'.map (homOfPath T p) = 1 by simp only [this, treeHom, comp_as_mul, inv_as_inv, loopOfHom, inv_one, mul_one, one_mul, Functor.map_inv, Functor.map_comp] intro a p induction p with | nil => rw [homOfPath, F'.map_id, id_as_one] | cons p e ih => rw [homOfPath, F'.map_comp, comp_as_mul, ih, mul_one] rcases e with ⟨e | e, eT⟩ · rw [hF'] exact dif_pos (Or.inl eT) · rw [F'.map_inv, inv_as_inv, inv_eq_one, hF'] exact dif_pos (Or.inr eT) · intro E hE ext x suffices (functorOfMonoidHom T E).map x = F'.map x by simpa only [loopOfHom, functorOfMonoidHom, IsIso.inv_id, treeHom_root, Category.id_comp, Category.comp_id] using this congr apply uF' intro a b e change E (loopOfHom T _) = dite _ _ _ split_ifs with h · rw [loopOfHom_eq_id T e h, ← End.one_def, E.map_one] · exact hE ⟨⟨a, b, e⟩, h⟩) end SpanningTree /-- Another name for the identity function `G → G`, to help type checking. -/ private def symgen {G : Type u} [Groupoid.{v} G] [IsFreeGroupoid G] : G → Symmetrify (Generators G) := id /-- If there exists a morphism `a → b` in a free groupoid, then there also exists a zigzag from `a` to `b` in the generating quiver. -/ theorem path_nonempty_of_hom {G} [Groupoid.{u, u} G] [IsFreeGroupoid G] {a b : G} : Nonempty (a ⟶ b) → Nonempty (Path (symgen a) (symgen b)) := by rintro ⟨p⟩ rw [← @WeaklyConnectedComponent.eq (Generators G), eq_comm, ← FreeGroup.of_injective.eq_iff, ← mul_inv_eq_one] let X := FreeGroup (WeaklyConnectedComponent <| Generators G) let f : G → X := fun g => FreeGroup.of (WeaklyConnectedComponent.mk g) let F : G ⥤ CategoryTheory.SingleObj.{u} (X : Type u) := SingleObj.differenceFunctor f change (F.map p) = ((@CategoryTheory.Functor.const G _ _ (SingleObj.category X)).obj ()).map p congr; ext rw [Functor.const_obj_map, id_as_one, differenceFunctor_map, @mul_inv_eq_one _ _ (f _)] apply congr_arg FreeGroup.of apply (WeaklyConnectedComponent.eq _ _).mpr exact ⟨Hom.toPath (Sum.inr (by assumption))⟩ /-- Given a connected free groupoid, its generating quiver is rooted-connected. -/ instance generators_connected (G) [Groupoid.{u, u} G] [IsConnected G] [IsFreeGroupoid G] (r : G) : RootedConnected (symgen r) := ⟨fun b => path_nonempty_of_hom (CategoryTheory.nonempty_hom_of_preconnected_groupoid r b)⟩ /-- A vertex group in a free connected groupoid is free. With some work one could drop the connectedness assumption, by looking at connected components. -/ instance endIsFreeOfConnectedFree {G : Type u} [Groupoid G] [IsConnected G] [IsFreeGroupoid G] (r : G) : IsFreeGroup.{u} (End r) := SpanningTree.endIsFree <| geodesicSubtree (symgen r) end IsFreeGroupoid /-- The Nielsen-Schreier theorem: a subgroup of a free group is free. -/ instance subgroupIsFreeOfIsFree {G : Type u} [Group G] [IsFreeGroup G] (H : Subgroup G) : IsFreeGroup H := IsFreeGroup.ofMulEquiv (endMulEquivSubgroup H)
Lemma.lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kyle Miller -/ import Mathlib.Init import Lean.Parser.Command /-! # Support for `lemma` as a synonym for `theorem`. -/ open Lean -- higher priority to override the one in Batteries /-- `lemma` means the same as `theorem`. It is used to denote "less important" theorems -/ syntax (name := lemma) (priority := default + 1) declModifiers group("lemma " declId ppIndent(declSig) declVal) : command /-- Implementation of the `lemma` command, by macro expansion to `theorem`. -/ @[macro «lemma»] def expandLemma : Macro := fun stx => -- Not using a macro match, to be more resilient against changes to `lemma`. -- This implementation ensures that any future changes to `theorem` are reflected in `lemma` let stx := stx.modifyArg 1 fun stx => let stx := stx.modifyArg 0 (mkAtomFrom · "theorem" (canonical := true)) stx.setKind ``Parser.Command.theorem pure <| stx.setKind ``Parser.Command.declaration
Iterate.lean
/- Copyright (c) 2024 Miyahara Kō. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Miyahara Kō -/ import Mathlib.Algebra.Order.Group.Nat import Mathlib.Data.List.Defs import Mathlib.Data.Set.Function /-! # iterate Proves various lemmas about `List.iterate`. -/ variable {α : Type*} namespace List @[simp] theorem length_iterate (f : α → α) (a : α) (n : ℕ) : length (iterate f a n) = n := by induction n generalizing a <;> simp [*] @[simp] theorem iterate_eq_nil {f : α → α} {a : α} {n : ℕ} : iterate f a n = [] ↔ n = 0 := by rw [← length_eq_zero_iff, length_iterate] theorem getElem?_iterate (f : α → α) (a : α) : ∀ (n i : ℕ), i < n → (iterate f a n)[i]? = f^[i] a | n + 1, 0 , _ => by simp | n + 1, i + 1, h => by simp [getElem?_iterate f (f a) n i (by simpa using h)] @[simp] theorem getElem_iterate (f : α → α) (a : α) (n : ℕ) (i : Nat) (h : i < (iterate f a n).length) : (iterate f a n)[i] = f^[i] a := (getElem_eq_iff _).2 <| getElem?_iterate _ _ _ _ <| by rwa [length_iterate] at h @[simp] theorem mem_iterate {f : α → α} {a : α} {n : ℕ} {b : α} : b ∈ iterate f a n ↔ ∃ m < n, b = f^[m] a := by simp [List.mem_iff_get, Fin.exists_iff, eq_comm (b := b)] @[simp] theorem range_map_iterate (n : ℕ) (f : α → α) (a : α) : (List.range n).map (f^[·] a) = List.iterate f a n := by apply List.ext_getElem <;> simp theorem iterate_add (f : α → α) (a : α) (m n : ℕ) : iterate f a (m + n) = iterate f a m ++ iterate f (f^[m] a) n := by induction m generalizing a with | zero => simp | succ n ih => rw [iterate, add_right_comm, iterate, ih, Nat.iterate, cons_append] theorem take_iterate (f : α → α) (a : α) (m n : ℕ) : take m (iterate f a n) = iterate f a (min m n) := by rw [← range_map_iterate, ← range_map_iterate, ← map_take, take_range] end List
WeakFactorizationSystem.lean
/- Copyright (c) 2025 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.CategoryTheory.MorphismProperty.RetractArgument /-! # Weak factorization systems In this file, we introduce the notion of weak factorization system, which is a property of two classes of morphisms `W₁` and `W₂` in a category `C`. The type class `IsWeakFactorizationSystem W₁ W₂` asserts that `W₁` is exactly `W₂.llp`, `W₂` is exactly `W₁.rlp`, and any morphism in `C` can be factored a `i ≫ p` with `W₁ i` and `W₂ p`. ## References * https://ncatlab.org/nlab/show/weak+factorization+system -/ universe v u namespace CategoryTheory.MorphismProperty variable {C : Type u} [Category.{v} C] (W₁ W₂ : MorphismProperty C) /-- Two classes of morphisms `W₁` and `W₂` in a category `C` form a weak factorization system if `W₁` is exactly `W₂.llp`, `W₂` is exactly `W₁.rlp`, and any morphism can be factored a `i ≫ p` with `W₁ i` and `W₂ p`. -/ class IsWeakFactorizationSystem : Prop where rlp : W₁.rlp = W₂ llp : W₂.llp = W₁ hasFactorization : HasFactorization W₁ W₂ := by infer_instance namespace IsWeakFactorizationSystem attribute [instance] hasFactorization lemma mk' [HasFactorization W₁ W₂] [W₁.IsStableUnderRetracts] [W₂.IsStableUnderRetracts] (h : ∀ {A B X Y : C} (i : A ⟶ B) (p : X ⟶ Y), W₁ i → W₂ p → HasLiftingProperty i p) : IsWeakFactorizationSystem W₁ W₂ where rlp := rlp_eq_of_le_rlp_of_hasFactorization_of_isStableUnderRetracts (fun _ _ _ hp _ _ _ hi ↦ h _ _ hi hp) llp := llp_eq_of_le_llp_of_hasFactorization_of_isStableUnderRetracts (fun _ _ _ hi _ _ _ hp ↦ h _ _ hi hp) end IsWeakFactorizationSystem section variable [IsWeakFactorizationSystem W₁ W₂] lemma rlp_eq_of_wfs : W₁.rlp = W₂ := IsWeakFactorizationSystem.rlp lemma llp_eq_of_wfs : W₂.llp = W₁ := IsWeakFactorizationSystem.llp variable {W₁ W₂} in lemma hasLiftingProperty_of_wfs {A B X Y : C} (i : A ⟶ B) (p : X ⟶ Y) (hi : W₁ i) (hp : W₂ p) : HasLiftingProperty i p := (llp_eq_of_wfs W₁ W₂ ▸ hi) p hp end end CategoryTheory.MorphismProperty
Restrict.lean
/- Copyright (c) 2023 Peter Nelson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Peter Nelson -/ import Mathlib.Data.Matroid.Dual /-! # Matroid Restriction Given `M : Matroid α` and `R : Set α`, the independent sets of `M` that are contained in `R` are the independent sets of another matroid `M ↾ R` with ground set `R`, called the 'restriction' of `M` to `R`. For `I ⊆ R ⊆ M.E`, `I` is a basis of `R` in `M` if and only if `I` is a base of the restriction `M ↾ R`, so this construction relates `Matroid.IsBasis` to `Matroid.IsBase`. If `N M : Matroid α` satisfy `N = M ↾ R` for some `R ⊆ M.E`, then we call `N` a 'restriction of `M`', and write `N ≤r M`. This is a partial order. This file proves that the restriction is a matroid and that the `≤r` order is a partial order, and gives related API. It also proves some `Matroid.IsBasis` analogues of `Matroid.IsBase` lemmas that, while they could be stated in `Data.Matroid.Basic`, are hard to prove without `Matroid.restrict` API. ## Main Definitions * `M.restrict R`, written `M ↾ R`, is the restriction of `M : Matroid α` to `R : Set α`: i.e. the matroid with ground set `R` whose independent sets are the `M`-independent subsets of `R`. * `Matroid.Restriction N M`, written `N ≤r M`, means that `N = M ↾ R` for some `R ⊆ M.E`. * `Matroid.IsStrictRestriction N M`, written `N <r M`, means that `N = M ↾ R` for some `R ⊂ M.E`. * `Matroidᵣ α` is a type synonym for `Matroid α`, equipped with the `PartialOrder` `≤r`. ## Implementation Notes Since `R` and `M.E` are both terms in `Set α`, to define the restriction `M ↾ R`, we need to either insist that `R ⊆ M.E`, or to say what happens when `R` contains the junk outside `M.E`. It turns out that `R ⊆ M.E` is just an unnecessary hypothesis; if we say the restriction `M ↾ R` has ground set `R` and its independent sets are the `M`-independent subsets of `R`, we always get a matroid, in which the elements of `R \ M.E` aren't in any independent sets. We could instead define this matroid to always be 'smaller' than `M` by setting `(M ↾ R).E := R ∩ M.E`, but this is worse definitionally, and more generally less convenient. This makes it possible to actually restrict a matroid 'upwards'; for instance, if `M : Matroid α` satisfies `M.E = ∅`, then `M ↾ Set.univ` is the matroid on `α` whose ground set is all of `α`, where the empty set is the only independent set. (In general, elements of `R \ M.E` are all 'loops' of the matroid `M ↾ R`; see `Matroid.loops` and `Matroid.restrict_loops_eq'` for a precise version of this statement.) This is mathematically strange, but is useful for API building. The cost of allowing a restriction of `M` to be 'bigger' than `M` itself is that the statement `M ↾ R ≤r M` is only true with the hypothesis `R ⊆ M.E` (at least, if we want `≤r` to be a partial order). But this isn't too inconvenient in practice. Indeed `(· ⊆ M.E)` proofs can often be automatically provided by `aesop_mat`. We define the restriction order `≤r` to give a `PartialOrder` instance on the type synonym `Matroidᵣ α` rather than `Matroid α` itself, because the `PartialOrder (Matroid α)` instance is reserved for the more mathematically important 'minor' order; see `Matroid.IsMinor`. -/ assert_not_exists Field open Set namespace Matroid variable {α : Type*} {M : Matroid α} {R I X Y : Set α} section restrict /-- The `IndepMatroid` whose independent sets are the independent subsets of `R`. -/ @[simps] def restrictIndepMatroid (M : Matroid α) (R : Set α) : IndepMatroid α where E := R Indep I := M.Indep I ∧ I ⊆ R indep_empty := ⟨M.empty_indep, empty_subset _⟩ indep_subset := fun _ _ h hIJ ↦ ⟨h.1.subset hIJ, hIJ.trans h.2⟩ indep_aug := by rintro I I' ⟨hI, hIY⟩ (hIn : ¬ M.IsBasis' I R) (hI' : M.IsBasis' I' R) rw [isBasis'_iff_isBasis_inter_ground] at hIn hI' obtain ⟨B', hB', rfl⟩ := hI'.exists_isBase obtain ⟨B, hB, hIB, hBIB'⟩ := hI.exists_isBase_subset_union_isBase hB' rw [hB'.inter_isBasis_iff_compl_inter_isBasis_dual, diff_inter_diff] at hI' have hss : M.E \ (B' ∪ (R ∩ M.E)) ⊆ M.E \ (B ∪ (R ∩ M.E)) := by apply diff_subset_diff_right rw [union_subset_iff, and_iff_left subset_union_right, union_comm] exact hBIB'.trans (union_subset_union_left _ (subset_inter hIY hI.subset_ground)) have hi : M✶.Indep (M.E \ (B ∪ (R ∩ M.E))) := by rw [dual_indep_iff_exists] exact ⟨B, hB, disjoint_of_subset_right subset_union_left disjoint_sdiff_left⟩ have h_eq := hI'.eq_of_subset_indep hi hss (diff_subset_diff_right subset_union_right) rw [h_eq, ← diff_inter_diff, ← hB.inter_isBasis_iff_compl_inter_isBasis_dual] at hI' obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis_of_subset (subset_inter hIB (subset_inter hIY hI.subset_ground)) obtain rfl := hI'.indep.eq_of_isBasis hJ have hIJ' : I ⊂ B ∩ (R ∩ M.E) := hIJ.ssubset_of_ne (fun he ↦ hIn (by rwa [he])) obtain ⟨e, he⟩ := exists_of_ssubset hIJ' exact ⟨e, ⟨⟨(hBIB' he.1.1).elim (fun h ↦ (he.2 h).elim) id,he.1.2⟩, he.2⟩, hI'.indep.subset (insert_subset he.1 hIJ), insert_subset he.1.2.1 hIY⟩ indep_maximal := by rintro A hAR I ⟨hI, _⟩ hIA obtain ⟨J, hJ, hIJ⟩ := hI.subset_isBasis'_of_subset hIA use J simp only [hIJ, and_assoc, maximal_subset_iff, hJ.indep, hJ.subset, and_imp, true_and, hJ.subset.trans hAR] exact fun K hK _ hKA hJK ↦ hJ.eq_of_subset_indep hK hJK hKA subset_ground _ := And.right /-- Change the ground set of a matroid to some `R : Set α`. The independent sets of the restriction are the independent subsets of the new ground set. Most commonly used when `R ⊆ M.E`, but it is convenient not to require this. The elements of `R \ M.E` become 'loops'. -/ def restrict (M : Matroid α) (R : Set α) : Matroid α := (M.restrictIndepMatroid R).matroid /-- `M ↾ R` means `M.restrict R`. -/ scoped infixl:65 " ↾ " => Matroid.restrict @[simp] theorem restrict_indep_iff : (M ↾ R).Indep I ↔ M.Indep I ∧ I ⊆ R := Iff.rfl theorem Indep.indep_restrict_of_subset (h : M.Indep I) (hIR : I ⊆ R) : (M ↾ R).Indep I := restrict_indep_iff.mpr ⟨h,hIR⟩ theorem Indep.of_restrict (hI : (M ↾ R).Indep I) : M.Indep I := (restrict_indep_iff.1 hI).1 @[simp] theorem restrict_ground_eq : (M ↾ R).E = R := rfl theorem restrict_finite {R : Set α} (hR : R.Finite) : (M ↾ R).Finite := ⟨hR⟩ @[simp] theorem restrict_dep_iff : (M ↾ R).Dep X ↔ ¬ M.Indep X ∧ X ⊆ R := by rw [Dep, restrict_indep_iff, restrict_ground_eq]; tauto @[simp] theorem restrict_ground_eq_self (M : Matroid α) : (M ↾ M.E) = M := by refine ext_indep rfl ?_; aesop theorem restrict_restrict_eq {R₁ R₂ : Set α} (M : Matroid α) (hR : R₂ ⊆ R₁) : (M ↾ R₁) ↾ R₂ = M ↾ R₂ := by refine ext_indep rfl ?_ simp only [restrict_ground_eq, restrict_indep_iff, and_congr_left_iff, and_iff_left_iff_imp] exact fun _ h _ _ ↦ h.trans hR @[simp] theorem restrict_idem (M : Matroid α) (R : Set α) : M ↾ R ↾ R = M ↾ R := by rw [M.restrict_restrict_eq Subset.rfl] @[simp] theorem isBase_restrict_iff (hX : X ⊆ M.E := by aesop_mat) : (M ↾ X).IsBase I ↔ M.IsBasis I X := by simp_rw [isBase_iff_maximal_indep, IsBasis, and_iff_left hX, maximal_iff, restrict_indep_iff] theorem isBase_restrict_iff' : (M ↾ X).IsBase I ↔ M.IsBasis' I X := by simp_rw [isBase_iff_maximal_indep, IsBasis', maximal_iff, restrict_indep_iff] theorem IsBasis'.isBase_restrict (hI : M.IsBasis' I X) : (M ↾ X).IsBase I := isBase_restrict_iff'.1 hI theorem IsBasis.restrict_isBase (h : M.IsBasis I X) : (M ↾ X).IsBase I := (isBase_restrict_iff h.subset_ground).2 h instance restrict_rankFinite [M.RankFinite] (R : Set α) : (M ↾ R).RankFinite := let ⟨_, hB⟩ := (M ↾ R).exists_isBase hB.rankFinite_of_finite (hB.indep.of_restrict.finite) instance restrict_finitary [Finitary M] (R : Set α) : Finitary (M ↾ R) := by refine ⟨fun I hI ↦ ?_⟩ simp only [restrict_indep_iff] at * rw [indep_iff_forall_finite_subset_indep] exact ⟨fun J hJ hJfin ↦ (hI J hJ hJfin).1, fun e heI ↦ singleton_subset_iff.1 (hI _ (by simpa) (toFinite _)).2⟩ @[simp] theorem IsBasis.isBase_restrict (h : M.IsBasis I X) : (M ↾ X).IsBase I := (isBase_restrict_iff h.subset_ground).mpr h theorem IsBasis.isBasis_restrict_of_subset (hI : M.IsBasis I X) (hXY : X ⊆ Y) : (M ↾ Y).IsBasis I X := by rwa [← isBase_restrict_iff, M.restrict_restrict_eq hXY, isBase_restrict_iff] theorem isBasis'_restrict_iff : (M ↾ R).IsBasis' I X ↔ M.IsBasis' I (X ∩ R) ∧ I ⊆ R := by simp_rw [IsBasis', maximal_iff, restrict_indep_iff, subset_inter_iff, and_imp] tauto theorem isBasis_restrict_iff' : (M ↾ R).IsBasis I X ↔ M.IsBasis I (X ∩ M.E) ∧ X ⊆ R := by rw [isBasis_iff_isBasis'_subset_ground, isBasis'_restrict_iff, restrict_ground_eq, and_congr_left_iff, ← isBasis'_iff_isBasis_inter_ground] intro hXR rw [inter_eq_self_of_subset_left hXR, and_iff_left_iff_imp] exact fun h ↦ h.subset.trans hXR theorem isBasis_restrict_iff (hR : R ⊆ M.E := by aesop_mat) : (M ↾ R).IsBasis I X ↔ M.IsBasis I X ∧ X ⊆ R := by rw [isBasis_restrict_iff', and_congr_left_iff] intro hXR rw [← isBasis'_iff_isBasis_inter_ground, isBasis'_iff_isBasis] lemma isBasis'_iff_isBasis_restrict_univ : M.IsBasis' I X ↔ (M ↾ univ).IsBasis I X := by rw [isBasis_restrict_iff', isBasis'_iff_isBasis_inter_ground, and_iff_left (subset_univ _)] theorem restrict_eq_restrict_iff (M M' : Matroid α) (X : Set α) : M ↾ X = M' ↾ X ↔ ∀ I, I ⊆ X → (M.Indep I ↔ M'.Indep I) := by refine ⟨fun h I hIX ↦ ?_, fun h ↦ ext_indep rfl fun I (hI : I ⊆ X) ↦ ?_⟩ · rw [← and_iff_left (a := (M.Indep I)) hIX, ← and_iff_left (a := (M'.Indep I)) hIX, ← restrict_indep_iff, h, restrict_indep_iff] rw [restrict_indep_iff, and_iff_left hI, restrict_indep_iff, and_iff_left hI, h _ hI] @[simp] theorem restrict_eq_self_iff : M ↾ R = M ↔ R = M.E := ⟨fun h ↦ by rw [← h]; rfl, fun h ↦ by simp [h]⟩ end restrict section IsRestriction variable {N : Matroid α} /-- `Restriction N M` means that `N = M ↾ R` for some subset `R` of `M.E` -/ def IsRestriction (N M : Matroid α) : Prop := ∃ R ⊆ M.E, N = M ↾ R @[deprecated (since := "2025-02-14")] alias Restriction := IsRestriction /-- `IsStrictRestriction N M` means that `N = M ↾ R` for some strict subset `R` of `M.E` -/ def IsStrictRestriction (N M : Matroid α) : Prop := IsRestriction N M ∧ ¬ IsRestriction M N @[deprecated (since := "2025-02-14")] alias StrictRestriction := IsStrictRestriction /-- `N ≤r M` means that `N` is a `Restriction` of `M`. -/ scoped infix:50 " ≤r " => IsRestriction /-- `N <r M` means that `N` is a `IsStrictRestriction` of `M`. -/ scoped infix:50 " <r " => IsStrictRestriction /-- A type synonym for matroids with the isRestriction order. (The `PartialOrder` on `Matroid α` is reserved for the minor order) -/ @[ext] structure Matroidᵣ (α : Type*) where ofMatroid :: /-- The underlying `Matroid` -/ toMatroid : Matroid α instance {α : Type*} : CoeOut (Matroidᵣ α) (Matroid α) where coe := Matroidᵣ.toMatroid @[simp] theorem Matroidᵣ.coe_inj {M₁ M₂ : Matroidᵣ α} : (M₁ : Matroid α) = (M₂ : Matroid α) ↔ M₁ = M₂ := by cases M₁; cases M₂; simp instance {α : Type*} : PartialOrder (Matroidᵣ α) where le := (· ≤r ·) le_refl M := ⟨(M : Matroid α).E, Subset.rfl, (M : Matroid α).restrict_ground_eq_self.symm⟩ le_trans M₁ M₂ M₃ := by rintro ⟨R, hR, h₁⟩ ⟨R', hR', h₂⟩ rw [h₂] at h₁ hR rw [h₁, restrict_restrict_eq _ (show R ⊆ R' from hR)] exact ⟨R, hR.trans hR', rfl⟩ le_antisymm M₁ M₂ := by rintro ⟨R, hR, h⟩ ⟨R', hR', h'⟩ rw [h', restrict_ground_eq] at hR rw [h, restrict_ground_eq] at hR' rw [← Matroidᵣ.coe_inj, h, h', hR.antisymm hR', restrict_idem] @[simp] protected theorem Matroidᵣ.le_iff {M M' : Matroidᵣ α} : M ≤ M' ↔ (M : Matroid α) ≤r (M' : Matroid α) := Iff.rfl @[simp] protected theorem Matroidᵣ.lt_iff {M M' : Matroidᵣ α} : M < M' ↔ (M : Matroid α) <r (M' : Matroid α) := Iff.rfl theorem ofMatroid_le_iff {M M' : Matroid α} : Matroidᵣ.ofMatroid M ≤ Matroidᵣ.ofMatroid M' ↔ M ≤r M' := by simp theorem ofMatroid_lt_iff {M M' : Matroid α} : Matroidᵣ.ofMatroid M < Matroidᵣ.ofMatroid M' ↔ M <r M' := by simp theorem IsRestriction.refl : M ≤r M := le_refl (Matroidᵣ.ofMatroid M) theorem IsRestriction.antisymm {M' : Matroid α} (h : M ≤r M') (h' : M' ≤r M) : M = M' := by simpa using (ofMatroid_le_iff.2 h).antisymm (ofMatroid_le_iff.2 h') theorem IsRestriction.trans {M₁ M₂ M₃ : Matroid α} (h : M₁ ≤r M₂) (h' : M₂ ≤r M₃) : M₁ ≤r M₃ := le_trans (α := Matroidᵣ α) h h' theorem restrict_isRestriction (M : Matroid α) (R : Set α) (hR : R ⊆ M.E := by aesop_mat) : M ↾ R ≤r M := ⟨R, hR, rfl⟩ theorem IsRestriction.eq_restrict (h : N ≤r M) : M ↾ N.E = N := by obtain ⟨R, -, rfl⟩ := h; rw [restrict_ground_eq] theorem IsRestriction.subset (h : N ≤r M) : N.E ⊆ M.E := by obtain ⟨R, hR, rfl⟩ := h; exact hR theorem IsRestriction.exists_eq_restrict (h : N ≤r M) : ∃ R ⊆ M.E, N = M ↾ R := h theorem IsRestriction.of_subset {R' : Set α} (M : Matroid α) (h : R ⊆ R') : (M ↾ R) ≤r (M ↾ R') := by rw [← restrict_restrict_eq M h]; exact restrict_isRestriction _ _ h theorem isRestriction_iff_exists : (N ≤r M) ↔ ∃ R, R ⊆ M.E ∧ N = M ↾ R := by use IsRestriction.exists_eq_restrict; rintro ⟨R, hR, rfl⟩; exact restrict_isRestriction M R hR theorem IsStrictRestriction.isRestriction (h : N <r M) : N ≤r M := h.1 theorem IsStrictRestriction.ne (h : N <r M) : N ≠ M := by rintro rfl; rw [← ofMatroid_lt_iff] at h; simp at h theorem IsStrictRestriction.irrefl (M : Matroid α) : ¬ (M <r M) := fun h ↦ h.ne rfl theorem IsStrictRestriction.ssubset (h : N <r M) : N.E ⊂ M.E := by obtain ⟨R, -, rfl⟩ := h.1 refine h.isRestriction.subset.ssubset_of_ne (fun h' ↦ h.2 ⟨R, Subset.rfl, ?_⟩) rw [show R = M.E from h', restrict_idem, restrict_ground_eq_self] theorem IsStrictRestriction.eq_restrict (h : N <r M) : M ↾ N.E = N := h.isRestriction.eq_restrict theorem IsStrictRestriction.exists_eq_restrict (h : N <r M) : ∃ R, R ⊂ M.E ∧ N = M ↾ R := ⟨N.E, h.ssubset, by rw [h.eq_restrict]⟩ theorem IsRestriction.isStrictRestriction_of_ne (h : N ≤r M) (hne : N ≠ M) : N <r M := ⟨h, fun h' ↦ hne <| h.antisymm h'⟩ theorem IsRestriction.eq_or_isStrictRestriction (h : N ≤r M) : N = M ∨ N <r M := by simpa using eq_or_lt_of_le (ofMatroid_le_iff.2 h) theorem restrict_isStrictRestriction {M : Matroid α} (hR : R ⊂ M.E) : M ↾ R <r M := by refine (M.restrict_isRestriction R hR.subset).isStrictRestriction_of_ne (fun h ↦ ?_) rw [← h, restrict_ground_eq] at hR exact hR.ne rfl theorem IsRestriction.isStrictRestriction_of_ground_ne (h : N ≤r M) (hne : N.E ≠ M.E) : N <r M := by rw [← h.eq_restrict] exact restrict_isStrictRestriction (h.subset.ssubset_of_ne hne) theorem IsStrictRestriction.of_ssubset {R' : Set α} (M : Matroid α) (h : R ⊂ R') : (M ↾ R) <r (M ↾ R') := (IsRestriction.of_subset M h.subset).isStrictRestriction_of_ground_ne h.ne theorem IsRestriction.finite {M : Matroid α} [M.Finite] (h : N ≤r M) : N.Finite := by obtain ⟨R, hR, rfl⟩ := h exact restrict_finite <| M.ground_finite.subset hR theorem IsRestriction.rankFinite {M : Matroid α} [RankFinite M] (h : N ≤r M) : N.RankFinite := by obtain ⟨R, -, rfl⟩ := h infer_instance theorem IsRestriction.finitary {M : Matroid α} [Finitary M] (h : N ≤r M) : N.Finitary := by obtain ⟨R, -, rfl⟩ := h infer_instance theorem finite_setOf_isRestriction (M : Matroid α) [M.Finite] : {N | N ≤r M}.Finite := (M.ground_finite.finite_subsets.image (fun R ↦ M ↾ R)).subset <| by rintro _ ⟨R, hR, rfl⟩; exact ⟨_, hR, rfl⟩ theorem Indep.of_isRestriction (hI : N.Indep I) (hNM : N ≤r M) : M.Indep I := by obtain ⟨R, -, rfl⟩ := hNM; exact hI.of_restrict theorem Indep.indep_isRestriction (hI : M.Indep I) (hNM : N ≤r M) (hIN : I ⊆ N.E) : N.Indep I := by obtain ⟨R, -, rfl⟩ := hNM; simpa [hI] theorem IsRestriction.indep_iff (hMN : N ≤r M) : N.Indep I ↔ M.Indep I ∧ I ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.indep_isRestriction hMN h.2⟩ theorem IsBasis.isBasis_isRestriction (hI : M.IsBasis I X) (hNM : N ≤r M) (hX : X ⊆ N.E) : N.IsBasis I X := by obtain ⟨R, hR, rfl⟩ := hNM; rwa [isBasis_restrict_iff, and_iff_left (show X ⊆ R from hX)] theorem IsBasis.of_isRestriction (hI : N.IsBasis I X) (hNM : N ≤r M) : M.IsBasis I X := by obtain ⟨R, hR, rfl⟩ := hNM; exact ((isBasis_restrict_iff hR).1 hI).1 theorem IsBase.isBasis_of_isRestriction (hI : N.IsBase I) (hNM : N ≤r M) : M.IsBasis I N.E := by obtain ⟨R, hR, rfl⟩ := hNM; rwa [isBase_restrict_iff] at hI theorem IsRestriction.base_iff (hMN : N ≤r M) {B : Set α} : N.IsBase B ↔ M.IsBasis B N.E := ⟨fun h ↦ IsBase.isBasis_of_isRestriction h hMN, fun h ↦ by simpa [hMN.eq_restrict] using h.restrict_isBase⟩ theorem IsRestriction.isBasis_iff (hMN : N ≤r M) : N.IsBasis I X ↔ M.IsBasis I X ∧ X ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.isBasis_isRestriction hMN h.2⟩ theorem Dep.of_isRestriction (hX : N.Dep X) (hNM : N ≤r M) : M.Dep X := by obtain ⟨R, hR, rfl⟩ := hNM rw [restrict_dep_iff] at hX exact ⟨hX.1, hX.2.trans hR⟩ theorem Dep.dep_isRestriction (hX : M.Dep X) (hNM : N ≤r M) (hXE : X ⊆ N.E := by aesop_mat) : N.Dep X := by obtain ⟨R, -, rfl⟩ := hNM; simpa [hX.not_indep] theorem IsRestriction.dep_iff (hMN : N ≤r M) : N.Dep X ↔ M.Dep X ∧ X ⊆ N.E := ⟨fun h ↦ ⟨h.of_isRestriction hMN, h.subset_ground⟩, fun h ↦ h.1.dep_isRestriction hMN h.2⟩ end IsRestriction /-! ### `IsBasis` and `Base` The lemmas below exploit the fact that `(M ↾ X).Base I ↔ M.IsBasis I X` to transfer facts about `Matroid.Base` to facts about `Matroid.IsBasis`. Their statements thematically belong in `Data.Matroid.Basic`, but they appear here because their proofs depend on the API for `Matroid.restrict`, -/ section IsBasis variable {B J : Set α} {e : α} theorem IsBasis.transfer (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) (hXY : X ⊆ Y) (hJY : M.IsBasis J Y) : M.IsBasis I Y := by rw [← isBase_restrict_iff]; rw [← isBase_restrict_iff] at hJY exact hJY.isBase_of_isBasis_superset hJX.subset (hIX.isBasis_restrict_of_subset hXY) theorem IsBasis.isBasis_of_isBasis_of_subset_of_subset (hI : M.IsBasis I X) (hJ : M.IsBasis J Y) (hJX : J ⊆ X) (hIY : I ⊆ Y) : M.IsBasis I Y := by have hI' := hI.isBasis_subset (subset_inter hI.subset hIY) inter_subset_left have hJ' := hJ.isBasis_subset (subset_inter hJX hJ.subset) inter_subset_right exact hI'.transfer hJ' inter_subset_right hJ theorem Indep.exists_isBasis_subset_union_isBasis (hI : M.Indep I) (hIX : I ⊆ X) (hJ : M.IsBasis J X) : ∃ I', M.IsBasis I' X ∧ I ⊆ I' ∧ I' ⊆ I ∪ J := by obtain ⟨I', hI', hII', hI'IJ⟩ := (hI.indep_restrict_of_subset hIX).exists_isBase_subset_union_isBase (IsBasis.isBase_restrict hJ) rw [isBase_restrict_iff] at hI' exact ⟨I', hI', hII', hI'IJ⟩ theorem Indep.exists_insert_of_not_isBasis (hI : M.Indep I) (hIX : I ⊆ X) (hI' : ¬M.IsBasis I X) (hJ : M.IsBasis J X) : ∃ e ∈ J \ I, M.Indep (insert e I) := by rw [← isBase_restrict_iff] at hI'; rw [← isBase_restrict_iff] at hJ obtain ⟨e, he, hi⟩ := (hI.indep_restrict_of_subset hIX).exists_insert_of_not_isBase hI' hJ exact ⟨e, he, (restrict_indep_iff.mp hi).1⟩ theorem IsBasis.isBase_of_isBase_subset (hIX : M.IsBasis I X) (hB : M.IsBase B) (hBX : B ⊆ X) : M.IsBase I := hB.isBase_of_isBasis_superset hBX hIX theorem IsBasis.exchange (hIX : M.IsBasis I X) (hJX : M.IsBasis J X) (he : e ∈ I \ J) : ∃ f ∈ J \ I, M.IsBasis (insert f (I \ {e})) X := by obtain ⟨y,hy, h⟩ := hIX.restrict_isBase.exchange hJX.restrict_isBase he exact ⟨y, hy, by rwa [isBase_restrict_iff] at h⟩ theorem IsBasis.eq_exchange_of_diff_eq_singleton (hI : M.IsBasis I X) (hJ : M.IsBasis J X) (hIJ : I \ J = {e}) : ∃ f ∈ J \ I, J = insert f I \ {e} := by rw [← isBase_restrict_iff] at hI hJ; exact hI.eq_exchange_of_diff_eq_singleton hJ hIJ theorem IsBasis'.encard_eq_encard (hI : M.IsBasis' I X) (hJ : M.IsBasis' J X) : I.encard = J.encard := by rw [← isBase_restrict_iff'] at hI hJ; exact hI.encard_eq_encard_of_isBase hJ theorem IsBasis.encard_eq_encard (hI : M.IsBasis I X) (hJ : M.IsBasis J X) : I.encard = J.encard := hI.isBasis'.encard_eq_encard hJ.isBasis' /-- Any independent set can be extended into a larger independent set. -/ theorem Indep.augment (hI : M.Indep I) (hJ : M.Indep J) (hIJ : I.encard < J.encard) : ∃ e ∈ J \ I, M.Indep (insert e I) := by by_contra! he have hb : M.IsBasis I (I ∪ J) := by simp_rw [hI.isBasis_iff_forall_insert_dep subset_union_left, union_diff_left, mem_diff, and_imp, dep_iff, insert_subset_iff, and_iff_left hI.subset_ground] exact fun e heJ heI ↦ ⟨he e ⟨heJ, heI⟩, hJ.subset_ground heJ⟩ obtain ⟨J', hJ', hJJ'⟩ := hJ.subset_isBasis_of_subset I.subset_union_right rw [← hJ'.encard_eq_encard hb] at hIJ exact hIJ.not_ge (encard_mono hJJ') lemma Indep.augment_finset {I J : Finset α} (hI : M.Indep I) (hJ : M.Indep J) (hIJ : I.card < J.card) : ∃ e ∈ J, e ∉ I ∧ M.Indep (insert e I) := by obtain ⟨x, hx, hxI⟩ := hI.augment hJ (by simpa [encard_eq_coe_toFinset_card]) simp only [mem_diff, Finset.mem_coe] at hx exact ⟨x, hx.1, hx.2, hxI⟩ end IsBasis end Matroid
Nilpotent.lean
/- Copyright (c) 2023 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Emilie Uthaiwat, Oliver Nash -/ import Mathlib.Algebra.Polynomial.AlgebraMap import Mathlib.Algebra.Polynomial.Div import Mathlib.Algebra.Polynomial.Identities import Mathlib.RingTheory.Ideal.Quotient.Operations import Mathlib.RingTheory.Nilpotent.Basic import Mathlib.RingTheory.Nilpotent.Lemmas /-! # Nilpotency in polynomial rings. This file is a place for results related to nilpotency in (single-variable) polynomial rings. ## Main results: * `Polynomial.isNilpotent_iff` * `Polynomial.isUnit_iff_coeff_isUnit_isNilpotent` -/ namespace Polynomial variable {R : Type*} {r : R} section Semiring variable [Semiring R] {P : R[X]} lemma isNilpotent_C_mul_pow_X_of_isNilpotent (n : ℕ) (hnil : IsNilpotent r) : IsNilpotent ((C r) * X ^ n) := by refine Commute.isNilpotent_mul_right (commute_X_pow _ _).symm ?_ obtain ⟨m, hm⟩ := hnil refine ⟨m, ?_⟩ rw [← C_pow, hm, C_0] lemma isNilpotent_pow_X_mul_C_of_isNilpotent (n : ℕ) (hnil : IsNilpotent r) : IsNilpotent (X ^ n * (C r)) := by rw [commute_X_pow] exact isNilpotent_C_mul_pow_X_of_isNilpotent n hnil @[simp] lemma isNilpotent_monomial_iff {n : ℕ} : IsNilpotent (monomial (R := R) n r) ↔ IsNilpotent r := exists_congr fun k ↦ by simp @[simp] lemma isNilpotent_C_iff : IsNilpotent (C r) ↔ IsNilpotent r := exists_congr fun k ↦ by simpa only [← C_pow] using C_eq_zero @[simp] lemma isNilpotent_X_mul_iff : IsNilpotent (X * P) ↔ IsNilpotent P := by refine ⟨fun h ↦ ?_, ?_⟩ · rwa [Commute.isNilpotent_mul_left_iff (commute_X P) (by simp)] at h · rintro ⟨k, hk⟩ exact ⟨k, by simp [(commute_X P).mul_pow, hk]⟩ @[simp] lemma isNilpotent_mul_X_iff : IsNilpotent (P * X) ↔ IsNilpotent P := by rw [← commute_X P] exact isNilpotent_X_mul_iff end Semiring section CommRing variable [CommRing R] {P : R[X]} protected lemma isNilpotent_iff : IsNilpotent P ↔ ∀ i, IsNilpotent (coeff P i) := by refine ⟨P.recOnHorner (by simp) (fun p r hp₀ _ hp hpr i ↦ ?_) (fun p _ hnp hpX i ↦ ?_), fun h ↦ ?_⟩ · rw [← sum_monomial_eq P] exact isNilpotent_sum (fun i _ ↦ by simpa only [isNilpotent_monomial_iff] using h i) · have hr : IsNilpotent (C r) := by obtain ⟨k, hk⟩ := hpr replace hp : eval 0 p = 0 := by rwa [coeff_zero_eq_aeval_zero] at hp₀ refine isNilpotent_C_iff.mpr ⟨k, ?_⟩ simpa [coeff_zero_eq_aeval_zero, hp] using congr_arg (fun q ↦ coeff q 0) hk rcases i with - | i · simpa [hp₀] using hr simp only [coeff_add, coeff_C_succ, add_zero] apply hp simpa using Commute.isNilpotent_sub (Commute.all _ _) hpr hr · rcases i with - | i · simp simpa using hnp (isNilpotent_mul_X_iff.mp hpX) i @[simp] lemma isNilpotent_reflect_iff {P : R[X]} {N : ℕ} (hN : P.natDegree ≤ N) : IsNilpotent (reflect N P) ↔ IsNilpotent P := by simp only [Polynomial.isNilpotent_iff] refine ⟨fun h i ↦ ?_, fun h i ↦ ?_⟩ <;> rcases le_or_gt i N with hi | hi · simpa [tsub_tsub_cancel_of_le hi] using h (N - i) · simp [coeff_eq_zero_of_natDegree_lt <| lt_of_le_of_lt hN hi] · simpa [hi, revAt_le] using h (N - i) · simpa [revAt_eq_self_of_lt hi] using h i @[simp] lemma isNilpotent_reverse_iff : IsNilpotent P.reverse ↔ IsNilpotent P := isNilpotent_reflect_iff (le_refl _) /-- Let `P` be a polynomial over `R`. If its constant term is a unit and its other coefficients are nilpotent, then `P` is a unit. See also `Polynomial.isUnit_iff_coeff_isUnit_isNilpotent`. -/ theorem isUnit_of_coeff_isUnit_isNilpotent (hunit : IsUnit (P.coeff 0)) (hnil : ∀ i, i ≠ 0 → IsNilpotent (P.coeff i)) : IsUnit P := by induction' h : P.natDegree using Nat.strong_induction_on with k hind generalizing P by_cases hdeg : P.natDegree = 0 { rw [eq_C_of_natDegree_eq_zero hdeg] exact hunit.map C } set P₁ := P.eraseLead with hP₁ suffices IsUnit P₁ by rw [← eraseLead_add_monomial_natDegree_leadingCoeff P, ← C_mul_X_pow_eq_monomial, ← hP₁] refine IsNilpotent.isUnit_add_left_of_commute ?_ this (Commute.all _ _) exact isNilpotent_C_mul_pow_X_of_isNilpotent _ (hnil _ hdeg) have hdeg₂ := lt_of_le_of_lt P.eraseLead_natDegree_le (Nat.sub_lt (Nat.pos_of_ne_zero hdeg) zero_lt_one) refine hind P₁.natDegree ?_ ?_ (fun i hi => ?_) rfl · simp_rw [P₁, ← h, hdeg₂] · simp_rw [P₁, eraseLead_coeff_of_ne _ (Ne.symm hdeg), hunit] · by_cases H : i ≤ P₁.natDegree · simp_rw [P₁, eraseLead_coeff_of_ne _ (ne_of_lt (lt_of_le_of_lt H hdeg₂)), hnil i hi] · simp_rw [coeff_eq_zero_of_natDegree_lt (lt_of_not_ge H), IsNilpotent.zero] /-- Let `P` be a polynomial over `R`. If `P` is a unit, then all its coefficients are nilpotent, except its constant term which is a unit. See also `Polynomial.isUnit_iff_coeff_isUnit_isNilpotent`. -/ theorem coeff_isUnit_isNilpotent_of_isUnit (hunit : IsUnit P) : IsUnit (P.coeff 0) ∧ (∀ i, i ≠ 0 → IsNilpotent (P.coeff i)) := by obtain ⟨Q, hQ⟩ := IsUnit.exists_right_inv hunit constructor · refine isUnit_of_mul_eq_one _ (Q.coeff 0) ?_ have h := (mul_coeff_zero P Q).symm rwa [hQ, coeff_one_zero] at h · intros n hn rw [nilpotent_iff_mem_prime] intros I hI let f := mapRingHom (Ideal.Quotient.mk I) have hPQ : degree (f P) = 0 ∧ degree (f Q) = 0 := by rw [← Nat.WithBot.add_eq_zero_iff, ← degree_mul, ← map_mul, hQ, map_one, degree_one] have hcoeff : (f P).coeff n = 0 := by refine coeff_eq_zero_of_degree_lt ?_ rw [hPQ.1] exact WithBot.coe_pos.2 hn.bot_lt rw [coe_mapRingHom, coeff_map, ← RingHom.mem_ker, Ideal.mk_ker] at hcoeff exact hcoeff /-- Let `P` be a polynomial over `R`. `P` is a unit if and only if all its coefficients are nilpotent, except its constant term which is a unit. See also `Polynomial.isUnit_iff'`. -/ theorem isUnit_iff_coeff_isUnit_isNilpotent : IsUnit P ↔ IsUnit (P.coeff 0) ∧ (∀ i, i ≠ 0 → IsNilpotent (P.coeff i)) := ⟨coeff_isUnit_isNilpotent_of_isUnit, fun H => isUnit_of_coeff_isUnit_isNilpotent H.1 H.2⟩ @[simp] lemma isUnit_C_add_X_mul_iff : IsUnit (C r + X * P) ↔ IsUnit r ∧ IsNilpotent P := by have : ∀ i, coeff (C r + X * P) (i + 1) = coeff P i := by simp simp_rw [isUnit_iff_coeff_isUnit_isNilpotent, Nat.forall_ne_zero_iff, this] simp only [coeff_add, coeff_C_zero, mul_coeff_zero, coeff_X_zero, zero_mul, add_zero, ← Polynomial.isNilpotent_iff] lemma isUnit_iff' : IsUnit P ↔ IsUnit (eval 0 P) ∧ IsNilpotent (P /ₘ X) := by suffices P = C (eval 0 P) + X * (P /ₘ X) by conv_lhs => rw [this]; simp conv_lhs => rw [← modByMonic_add_div P monic_X] simp [modByMonic_X] theorem not_isUnit_of_natDegree_pos_of_isReduced [IsReduced R] (p : R[X]) (hpl : 0 < p.natDegree) : ¬ IsUnit p := by simp only [ne_eq, isNilpotent_iff_eq_zero, not_and, not_forall, exists_prop, Polynomial.isUnit_iff_coeff_isUnit_isNilpotent] intro _ refine ⟨p.natDegree, hpl.ne', ?_⟩ contrapose! hpl simp only [coeff_natDegree, leadingCoeff_eq_zero] at hpl simp [hpl] theorem not_isUnit_of_degree_pos_of_isReduced [IsReduced R] (p : R[X]) (hpl : 0 < p.degree) : ¬ IsUnit p := not_isUnit_of_natDegree_pos_of_isReduced _ (natDegree_pos_iff_degree_pos.mpr hpl) end CommRing section CommAlgebra variable {R S : Type*} [CommRing R] [CommRing S] [Algebra R S] (P : R[X]) {a b : S} lemma isNilpotent_aeval_sub_of_isNilpotent_sub (h : IsNilpotent (a - b)) : IsNilpotent (aeval a P - aeval b P) := by simp only [← eval_map_algebraMap] have ⟨c, hc⟩ := evalSubFactor (map (algebraMap R S) P) a b exact hc ▸ (Commute.all _ _).isNilpotent_mul_left h variable {P} lemma isUnit_aeval_of_isUnit_aeval_of_isNilpotent_sub (hb : IsUnit (aeval b P)) (hab : IsNilpotent (a - b)) : IsUnit (aeval a P) := by rw [← add_sub_cancel (aeval b P) (aeval a P)] refine IsNilpotent.isUnit_add_left_of_commute ?_ hb (Commute.all _ _) exact isNilpotent_aeval_sub_of_isNilpotent_sub P hab end CommAlgebra end Polynomial
Lex.lean
/- Copyright (c) 2025 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import Mathlib.Order.Interval.Basic import Mathlib.Data.Prod.Lex import Mathlib.Tactic.FastInstance /-! # The lexicographic order on intervals This order is compatible with the inclusion ordering, but is total. Under this ordering, `[(3, 3), (2, 2), (2, 3), (1, 1), (1, 2), (1, 3)]` is sorted. -/ namespace NonemptyInterval variable {α} section LELT variable [LT α] [LE α] instance : LE (Lex (NonemptyInterval α)) where le x y := toLex (ofLex x).toDualProd ≤ toLex (ofLex y).toDualProd instance : LT (Lex (NonemptyInterval α)) where lt x y := toLex (ofLex x).toDualProd < toLex (ofLex y).toDualProd theorem toLex_le_toLex {x y : NonemptyInterval α} : toLex x ≤ toLex y ↔ y.fst < x.fst ∨ x.fst = y.fst ∧ x.snd ≤ y.snd := Prod.lex_def theorem toLex_lt_toLex {x y : NonemptyInterval α} : toLex x < toLex y ↔ y.fst < x.fst ∨ x.fst = y.fst ∧ x.snd < y.snd := Prod.lex_def instance [DecidableEq α] [DecidableLT α] [DecidableLE α] : DecidableLE (Lex (NonemptyInterval α)) := fun _ _ => decidable_of_iff' _ toLex_le_toLex instance [DecidableEq α] [DecidableLT α] : DecidableLT (Lex (NonemptyInterval α)) := fun _ _ => decidable_of_iff' _ toLex_lt_toLex -- Sanity check on the ordering. /-- info: [(3, 3), (2, 2), (2, 3), (1, 1), (1, 2), (1, 3)] -/ #guard_msgs in #eval [ NonemptyInterval.mk (1, 1) (by grind), NonemptyInterval.mk (1, 2) (by grind), NonemptyInterval.mk (1, 3) (by grind), NonemptyInterval.mk (2, 2) (by grind), NonemptyInterval.mk (2, 3) (by grind), NonemptyInterval.mk (3, 3) (by grind)].map toLex |>.mergeSort.map (·.toProd) end LELT instance [Preorder α] : Preorder (Lex (NonemptyInterval α)) := fast_instance% Preorder.lift fun x => toLex (ofLex x).toDualProd theorem toLex_mono [PartialOrder α] : Monotone (toLex : NonemptyInterval α → _) := Prod.Lex.toLex_mono.comp toDualProd_mono theorem toLex_strictMono [PartialOrder α] : StrictMono (toLex : NonemptyInterval α → _) := Prod.Lex.toLex_strictMono.comp toDualProd_strictMono instance [PartialOrder α] : PartialOrder (Lex (NonemptyInterval α)) := fast_instance% PartialOrder.lift (fun x => toLex (ofLex x).toDualProd) <| toLex.injective.comp <| toDualProd_injective.comp ofLex.injective instance [LinearOrder α] : LinearOrder (Lex (NonemptyInterval α)) := fast_instance% { LinearOrder.lift' (fun x : Lex (NonemptyInterval α) => toLex (ofLex x).toDualProd) <| toLex.injective.comp <| toDualProd_injective.comp ofLex.injective with toDecidableEq := inferInstance toDecidableLT := inferInstance toDecidableLE := inferInstance } end NonemptyInterval
Pow.lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.Algebra.Order.Monoid.Unbundled.Pow import Mathlib.Data.Nat.Prime.Basic /-! # Prime numbers This file develops the theory of prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. -/ namespace Nat theorem pow_minFac {n k : ℕ} (hk : k ≠ 0) : (n ^ k).minFac = n.minFac := by rcases eq_or_ne n 1 with (rfl | hn) · simp have hnk : n ^ k ≠ 1 := fun hk' => hn ((pow_eq_one_iff hk).1 hk') apply (minFac_le_of_dvd (minFac_prime hn).two_le ((minFac_dvd n).pow hk)).antisymm apply minFac_le_of_dvd (minFac_prime hnk).two_le ((minFac_prime hnk).dvd_of_dvd_pow (minFac_dvd _)) theorem Prime.pow_minFac {p k : ℕ} (hp : p.Prime) (hk : k ≠ 0) : (p ^ k).minFac = p := by rw [Nat.pow_minFac hk, hp.minFac_eq] end Nat
ImageHyperplane.lean
/- Copyright (c) 2023 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Geometry.Euclidean.Inversion.Basic import Mathlib.Geometry.Euclidean.PerpBisector /-! # Image of a hyperplane under inversion In this file we prove that the inversion with center `c` and radius `R ≠ 0` maps a sphere passing through the center to a hyperplane, and vice versa. More precisely, it maps a sphere with center `y ≠ c` and radius `dist y c` to the hyperplane `AffineSubspace.perpBisector c (EuclideanGeometry.inversion c R y)`. The exact statements are a little more complicated because `EuclideanGeometry.inversion c R` sends the center to itself, not to a point at infinity. We also prove that the inversion sends an affine subspace passing through the center to itself. ## Keywords inversion -/ open Metric Function AffineMap Set AffineSubspace open scoped Topology variable {V P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P] [NormedAddTorsor V P] {c x y : P} {R : ℝ} namespace EuclideanGeometry /-- The inversion with center `c` and radius `R` maps a sphere passing through the center to a hyperplane. -/ theorem inversion_mem_perpBisector_inversion_iff (hR : R ≠ 0) (hx : x ≠ c) (hy : y ≠ c) : inversion c R x ∈ perpBisector c (inversion c R y) ↔ dist x y = dist y c := by rw [mem_perpBisector_iff_dist_eq, dist_inversion_inversion hx hy, dist_inversion_center] have hx' := dist_ne_zero.2 hx have hy' := dist_ne_zero.2 hy -- takes 300ms, but the "equivalent" simp call fails -> hard to speed up field_simp [mul_assoc, mul_comm, hx, hx.symm, eq_comm] /-- The inversion with center `c` and radius `R` maps a sphere passing through the center to a hyperplane. -/ theorem inversion_mem_perpBisector_inversion_iff' (hR : R ≠ 0) (hy : y ≠ c) : inversion c R x ∈ perpBisector c (inversion c R y) ↔ dist x y = dist y c ∧ x ≠ c := by rcases eq_or_ne x c with rfl | hx · simp [*] · simp [inversion_mem_perpBisector_inversion_iff hR hx hy, hx] theorem preimage_inversion_perpBisector_inversion (hR : R ≠ 0) (hy : y ≠ c) : inversion c R ⁻¹' perpBisector c (inversion c R y) = sphere y (dist y c) \ {c} := Set.ext fun _ ↦ inversion_mem_perpBisector_inversion_iff' hR hy theorem preimage_inversion_perpBisector (hR : R ≠ 0) (hy : y ≠ c) : inversion c R ⁻¹' perpBisector c y = sphere (inversion c R y) (R ^ 2 / dist y c) \ {c} := by rw [← dist_inversion_center, ← preimage_inversion_perpBisector_inversion hR, inversion_inversion] <;> simp [*] theorem image_inversion_perpBisector (hR : R ≠ 0) (hy : y ≠ c) : inversion c R '' perpBisector c y = sphere (inversion c R y) (R ^ 2 / dist y c) \ {c} := by rw [image_eq_preimage_of_inverse (inversion_involutive _ hR) (inversion_involutive _ hR), preimage_inversion_perpBisector hR hy] theorem preimage_inversion_sphere_dist_center (hR : R ≠ 0) (hy : y ≠ c) : inversion c R ⁻¹' sphere y (dist y c) = insert c (perpBisector c (inversion c R y) : Set P) := by ext x rcases eq_or_ne x c with rfl | hx; · simp [dist_comm] rw [mem_preimage, mem_sphere, ← inversion_mem_perpBisector_inversion_iff hR] <;> simp [*] theorem image_inversion_sphere_dist_center (hR : R ≠ 0) (hy : y ≠ c) : inversion c R '' sphere y (dist y c) = insert c (perpBisector c (inversion c R y) : Set P) := by rw [image_eq_preimage_of_inverse (inversion_involutive _ hR) (inversion_involutive _ hR), preimage_inversion_sphere_dist_center hR hy] /-- Inversion sends an affine subspace passing through the center to itself. -/ theorem mapsTo_inversion_affineSubspace_of_mem {p : AffineSubspace ℝ P} (hp : c ∈ p) : MapsTo (inversion c R) p p := fun _ ↦ AffineMap.lineMap_mem _ hp /-- Inversion sends an affine subspace passing through the center to itself. -/ theorem image_inversion_affineSubspace_of_mem {p : AffineSubspace ℝ P} (hR : R ≠ 0) (hp : c ∈ p) : inversion c R '' p = p := (mapsTo_inversion_affineSubspace_of_mem hp).image_subset.antisymm fun x hx ↦ ⟨inversion c R x, mapsTo_inversion_affineSubspace_of_mem hp hx, inversion_inversion _ hR _⟩ end EuclideanGeometry
Properties.lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kexing Ying -/ import Mathlib.LinearAlgebra.BilinearForm.Hom import Mathlib.LinearAlgebra.Dual.Lemmas /-! # Bilinear form This file defines various properties of bilinear forms, including reflexivity, symmetry, alternativity, adjoint, and non-degeneracy. For orthogonality, see `Mathlib/LinearAlgebra/BilinearForm/Orthogonal.lean`. ## Notations Given any term `B` of type `BilinForm`, due to a coercion, can use the notation `B x y` to refer to the function field, ie. `B x y = B.bilin x y`. In this file we use the following type variables: - `M`, `M'`, ... are modules over the commutative semiring `R`, - `M₁`, `M₁'`, ... are modules over the commutative ring `R₁`, - `V`, ... is a vector space over the field `K`. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ open LinearMap (BilinForm) open Module universe u v w variable {R : Type*} {M : Type*} [CommSemiring R] [AddCommMonoid M] [Module R M] variable {R₁ : Type*} {M₁ : Type*} [CommRing R₁] [AddCommGroup M₁] [Module R₁ M₁] variable {V : Type*} {K : Type*} [Field K] [AddCommGroup V] [Module K V] variable {M' : Type*} [AddCommMonoid M'] [Module R M'] variable {B : BilinForm R M} {B₁ : BilinForm R₁ M₁} namespace LinearMap namespace BilinForm /-! ### Reflexivity, symmetry, and alternativity -/ /-- The proposition that a bilinear form is reflexive -/ def IsRefl (B : BilinForm R M) : Prop := LinearMap.IsRefl B namespace IsRefl theorem eq_zero (H : B.IsRefl) : ∀ {x y : M}, B x y = 0 → B y x = 0 := fun {x y} => H x y protected theorem neg {B : BilinForm R₁ M₁} (hB : B.IsRefl) : (-B).IsRefl := fun x y => neg_eq_zero.mpr ∘ hB x y ∘ neg_eq_zero.mp protected theorem smul {α} [Semiring α] [Module α R] [SMulCommClass R α R] [NoZeroSMulDivisors α R] (a : α) {B : BilinForm R M} (hB : B.IsRefl) : (a • B).IsRefl := fun _ _ h => (smul_eq_zero.mp h).elim (fun ha => smul_eq_zero_of_left ha _) fun hBz => smul_eq_zero_of_right _ (hB _ _ hBz) protected theorem groupSMul {α} [Group α] [DistribMulAction α R] [SMulCommClass R α R] (a : α) {B : BilinForm R M} (hB : B.IsRefl) : (a • B).IsRefl := fun x y => (smul_eq_zero_iff_eq _).mpr ∘ hB x y ∘ (smul_eq_zero_iff_eq _).mp end IsRefl @[simp] theorem isRefl_zero : (0 : BilinForm R M).IsRefl := fun _ _ _ => rfl @[simp] theorem isRefl_neg {B : BilinForm R₁ M₁} : (-B).IsRefl ↔ B.IsRefl := ⟨fun h => neg_neg B ▸ h.neg, IsRefl.neg⟩ /-- The proposition that a bilinear form is symmetric -/ structure IsSymm (B : BilinForm R M) : Prop where protected eq : ∀ x y, B x y = B y x theorem isSymm_def : IsSymm B ↔ ∀ x y, B x y = B y x where mp := fun ⟨h⟩ ↦ h mpr h := ⟨h⟩ theorem isSymm_iff : IsSymm B ↔ LinearMap.IsSymm B := by simp [isSymm_def, LinearMap.isSymm_def] namespace IsSymm theorem isRefl (H : B.IsSymm) : B.IsRefl := fun x y H1 => H.eq x y ▸ H1 protected theorem add {B₁ B₂ : BilinForm R M} (hB₁ : B₁.IsSymm) (hB₂ : B₂.IsSymm) : (B₁ + B₂).IsSymm := ⟨fun x y => (congr_arg₂ (· + ·) (hB₁.eq x y) (hB₂.eq x y) :)⟩ protected theorem sub {B₁ B₂ : BilinForm R₁ M₁} (hB₁ : B₁.IsSymm) (hB₂ : B₂.IsSymm) : (B₁ - B₂).IsSymm := ⟨fun x y => (congr_arg₂ Sub.sub (hB₁.eq x y) (hB₂.eq x y) :)⟩ protected theorem neg {B : BilinForm R₁ M₁} (hB : B.IsSymm) : (-B).IsSymm := ⟨fun x y => congr_arg Neg.neg (hB.eq x y)⟩ protected theorem smul {α} [Monoid α] [DistribMulAction α R] [SMulCommClass R α R] (a : α) {B : BilinForm R M} (hB : B.IsSymm) : (a • B).IsSymm := ⟨fun x y => congr_arg (a • ·) (hB.eq x y)⟩ /-- The restriction of a symmetric bilinear form on a submodule is also symmetric. -/ theorem restrict {B : BilinForm R M} (b : B.IsSymm) (W : Submodule R M) : (B.restrict W).IsSymm := ⟨fun x y => b.eq x y⟩ end IsSymm @[simp] theorem isSymm_zero : (0 : BilinForm R M).IsSymm := ⟨fun _ _ => rfl⟩ @[simp] theorem isSymm_neg {B : BilinForm R₁ M₁} : (-B).IsSymm ↔ B.IsSymm := ⟨fun h => neg_neg B ▸ h.neg, IsSymm.neg⟩ theorem isSymm_iff_flip : B.IsSymm ↔ flipHom B = B where mp := fun ⟨h⟩ ↦ by ext; simp [h] mpr h := ⟨fun x y ↦ by rw [← flip_apply, h]⟩ section polarization variable {R : Type*} [Field R] [NeZero (2 : R)] [Module R M] {B C : BilinForm R M} /-- Polarization identity: a symmetric bilinear form can be expressed through the values it takes on the diagonal. -/ lemma IsSymm.polarization (x y : M) (hB : B.IsSymm) : B x y = (B (x + y) (x + y) - B x x - B y y) / 2 := by simp only [map_add, LinearMap.add_apply] rw [hB.eq y x] ring_nf rw [mul_assoc, inv_mul_cancel₀ two_ne_zero, mul_one] /-- A symmetric bilinear form is characterized by the values it takes on the diagonal. -/ lemma ext_of_isSymm (hB : IsSymm B) (hC : IsSymm C) (h : ∀ x, B x x = C x x) : B = C := by ext x y rw [hB.polarization, hC.polarization] simp_rw [h] /-- A symmetric bilinear form is characterized by the values it takes on the diagonal. -/ lemma ext_iff_of_isSymm (hB : IsSymm B) (hC : IsSymm C) : B = C ↔ ∀ x, B x x = C x x where mp h := by simp [h] mpr := ext_of_isSymm hB hC end polarization lemma isSymm_iff_basis {ι : Type*} (b : Basis ι R M) : IsSymm B ↔ ∀ i j, B (b i) (b j) = B (b j) (b i) where mp := fun ⟨h⟩ i j ↦ h _ _ mpr := by refine fun h ↦ ⟨fun x y ↦ ?_⟩ obtain ⟨fx, tx, ix, -, hx⟩ := Submodule.mem_span_iff_exists_finset_subset.1 (by simp : x ∈ Submodule.span R (Set.range b)) obtain ⟨fy, ty, iy, -, hy⟩ := Submodule.mem_span_iff_exists_finset_subset.1 (by simp : y ∈ Submodule.span R (Set.range b)) rw [← hx, ← hy] simp only [map_sum, map_smul, coeFn_sum, Finset.sum_apply, smul_apply, smul_eq_mul, Finset.mul_sum] rw [Finset.sum_comm] refine Finset.sum_congr rfl (fun b₁ h₁ ↦ Finset.sum_congr rfl fun b₂ h₂ ↦ ?_) rw [mul_left_comm] obtain ⟨i, rfl⟩ := ix h₁ obtain ⟨j, rfl⟩ := iy h₂ rw [h] /-- The proposition that a bilinear form is alternating -/ def IsAlt (B : BilinForm R M) : Prop := LinearMap.IsAlt B namespace IsAlt theorem self_eq_zero (H : B.IsAlt) (x : M) : B x x = 0 := LinearMap.IsAlt.self_eq_zero H x theorem neg_eq (H : B₁.IsAlt) (x y : M₁) : -B₁ x y = B₁ y x := LinearMap.IsAlt.neg H x y theorem isRefl (H : B₁.IsAlt) : B₁.IsRefl := LinearMap.IsAlt.isRefl H theorem eq_of_add_add_eq_zero [IsCancelAdd R] {a b c : M} (H : B.IsAlt) (hAdd : a + b + c = 0) : B a b = B b c := LinearMap.IsAlt.eq_of_add_add_eq_zero H hAdd protected theorem add {B₁ B₂ : BilinForm R M} (hB₁ : B₁.IsAlt) (hB₂ : B₂.IsAlt) : (B₁ + B₂).IsAlt := fun x => (congr_arg₂ (· + ·) (hB₁ x) (hB₂ x) :).trans <| add_zero _ protected theorem sub {B₁ B₂ : BilinForm R₁ M₁} (hB₁ : B₁.IsAlt) (hB₂ : B₂.IsAlt) : (B₁ - B₂).IsAlt := fun x => (congr_arg₂ Sub.sub (hB₁ x) (hB₂ x)).trans <| sub_zero _ protected theorem neg {B : BilinForm R₁ M₁} (hB : B.IsAlt) : (-B).IsAlt := fun x => neg_eq_zero.mpr <| hB x protected theorem smul {α} [Monoid α] [DistribMulAction α R] [SMulCommClass R α R] (a : α) {B : BilinForm R M} (hB : B.IsAlt) : (a • B).IsAlt := fun x => (congr_arg (a • ·) (hB x)).trans <| smul_zero _ end IsAlt @[simp] theorem isAlt_zero : (0 : BilinForm R M).IsAlt := fun _ => rfl @[simp] theorem isAlt_neg {B : BilinForm R₁ M₁} : (-B).IsAlt ↔ B.IsAlt := ⟨fun h => neg_neg B ▸ h.neg, IsAlt.neg⟩ end BilinForm namespace BilinForm /-- A nondegenerate bilinear form is a bilinear form such that the only element that is orthogonal to every other element is `0`; i.e., for all nonzero `m` in `M`, there exists `n` in `M` with `B m n ≠ 0`. Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a chirality; in addition to this "left" nondegeneracy condition one could define a "right" nondegeneracy condition that in the situation described, `B n m ≠ 0`. This variant definition is not currently provided in mathlib. In finite dimension either definition implies the other. -/ def Nondegenerate (B : BilinForm R M) : Prop := ∀ m : M, (∀ n : M, B m n = 0) → m = 0 section variable (R M) /-- In a non-trivial module, zero is not non-degenerate. -/ theorem not_nondegenerate_zero [Nontrivial M] : ¬(0 : BilinForm R M).Nondegenerate := let ⟨m, hm⟩ := exists_ne (0 : M) fun h => hm (h m fun _ => rfl) end variable {M' : Type*} variable [AddCommMonoid M'] [Module R M'] theorem Nondegenerate.ne_zero [Nontrivial M] {B : BilinForm R M} (h : B.Nondegenerate) : B ≠ 0 := fun h0 => not_nondegenerate_zero R M <| h0 ▸ h theorem Nondegenerate.congr {B : BilinForm R M} (e : M ≃ₗ[R] M') (h : B.Nondegenerate) : (congr e B).Nondegenerate := fun m hm => e.symm.map_eq_zero_iff.1 <| h (e.symm m) fun n => (congr_arg _ (e.symm_apply_apply n).symm).trans (hm (e n)) @[simp] theorem nondegenerate_congr_iff {B : BilinForm R M} (e : M ≃ₗ[R] M') : (congr e B).Nondegenerate ↔ B.Nondegenerate := ⟨fun h => by convert h.congr e.symm rw [congr_congr, e.self_trans_symm, congr_refl, LinearEquiv.refl_apply], Nondegenerate.congr e⟩ /-- A bilinear form is nondegenerate if and only if it has a trivial kernel. -/ theorem nondegenerate_iff_ker_eq_bot {B : BilinForm R M} : B.Nondegenerate ↔ LinearMap.ker B = ⊥ := by rw [LinearMap.ker_eq_bot'] simp [Nondegenerate, LinearMap.ext_iff] theorem Nondegenerate.ker_eq_bot {B : BilinForm R M} (h : B.Nondegenerate) : LinearMap.ker B = ⊥ := nondegenerate_iff_ker_eq_bot.mp h theorem compLeft_injective (B : BilinForm R₁ M₁) (b : B.Nondegenerate) : Function.Injective B.compLeft := fun φ ψ h => by ext w refine eq_of_sub_eq_zero (b _ ?_) intro v rw [sub_left, ← compLeft_apply, ← compLeft_apply, ← h, sub_self] theorem isAdjointPair_unique_of_nondegenerate (B : BilinForm R₁ M₁) (b : B.Nondegenerate) (φ ψ₁ ψ₂ : M₁ →ₗ[R₁] M₁) (hψ₁ : IsAdjointPair B B ψ₁ φ) (hψ₂ : IsAdjointPair B B ψ₂ φ) : ψ₁ = ψ₂ := B.compLeft_injective b <| ext fun v w => by rw [compLeft_apply, compLeft_apply, hψ₁, hψ₂] section FiniteDimensional variable [FiniteDimensional K V] /-- Given a nondegenerate bilinear form `B` on a finite-dimensional vector space, `B.toDual` is the linear equivalence between a vector space and its dual. -/ noncomputable def toDual (B : BilinForm K V) (b : B.Nondegenerate) : V ≃ₗ[K] Module.Dual K V := B.linearEquivOfInjective (LinearMap.ker_eq_bot.mp <| b.ker_eq_bot) Subspace.dual_finrank_eq.symm theorem toDual_def {B : BilinForm K V} (b : B.SeparatingLeft) {m n : V} : B.toDual b m n = B m n := rfl @[simp] lemma apply_toDual_symm_apply {B : BilinForm K V} {hB : B.Nondegenerate} (f : Module.Dual K V) (v : V) : B ((B.toDual hB).symm f) v = f v := by change B.toDual hB ((B.toDual hB).symm f) v = f v simp only [LinearEquiv.apply_symm_apply] lemma Nondegenerate.flip {B : BilinForm K V} (hB : B.Nondegenerate) : B.flip.Nondegenerate := by intro x hx apply (Module.evalEquiv K V).injective ext f obtain ⟨y, rfl⟩ := (B.toDual hB).surjective f simpa using hx y lemma nonDegenerateFlip_iff {B : BilinForm K V} : B.flip.Nondegenerate ↔ B.Nondegenerate := ⟨Nondegenerate.flip, Nondegenerate.flip⟩ end FiniteDimensional section DualBasis variable {ι : Type*} [DecidableEq ι] [Finite ι] /-- The `B`-dual basis `B.dualBasis hB b` to a finite basis `b` satisfies `B (B.dualBasis hB b i) (b j) = B (b i) (B.dualBasis hB b j) = if i = j then 1 else 0`, where `B` is a nondegenerate (symmetric) bilinear form and `b` is a finite basis. -/ noncomputable def dualBasis (B : BilinForm K V) (hB : B.Nondegenerate) (b : Basis ι K V) : Basis ι K V := haveI := FiniteDimensional.of_fintype_basis b b.dualBasis.map (B.toDual hB).symm @[simp] theorem dualBasis_repr_apply (B : BilinForm K V) (hB : B.Nondegenerate) (b : Basis ι K V) (x i) : (B.dualBasis hB b).repr x i = B x (b i) := by have := FiniteDimensional.of_fintype_basis b rw [dualBasis, Basis.map_repr, LinearEquiv.symm_symm, LinearEquiv.trans_apply, Basis.dualBasis_repr, toDual_def] theorem apply_dualBasis_left (B : BilinForm K V) (hB : B.Nondegenerate) (b : Basis ι K V) (i j) : B (B.dualBasis hB b i) (b j) = if j = i then 1 else 0 := by have := FiniteDimensional.of_fintype_basis b rw [dualBasis, Basis.map_apply, Basis.coe_dualBasis, ← toDual_def hB, LinearEquiv.apply_symm_apply, Basis.coord_apply, Basis.repr_self, Finsupp.single_apply] theorem apply_dualBasis_right (B : BilinForm K V) (hB : B.Nondegenerate) (sym : B.IsSymm) (b : Basis ι K V) (i j) : B (b i) (B.dualBasis hB b j) = if i = j then 1 else 0 := by rw [sym.eq, apply_dualBasis_left] @[simp] lemma dualBasis_dualBasis_flip [FiniteDimensional K V] (B : BilinForm K V) (hB : B.Nondegenerate) {ι : Type*} [Finite ι] [DecidableEq ι] (b : Basis ι K V) : B.dualBasis hB (B.flip.dualBasis hB.flip b) = b := by ext i refine LinearMap.ker_eq_bot.mp hB.ker_eq_bot ((B.flip.dualBasis hB.flip b).ext (fun j ↦ ?_)) simp_rw [apply_dualBasis_left, ← B.flip_apply, apply_dualBasis_left, @eq_comm _ i j] @[simp] lemma dualBasis_flip_dualBasis (B : BilinForm K V) (hB : B.Nondegenerate) {ι} [Finite ι] [DecidableEq ι] [FiniteDimensional K V] (b : Basis ι K V) : B.flip.dualBasis hB.flip (B.dualBasis hB b) = b := dualBasis_dualBasis_flip _ hB.flip b @[simp] lemma dualBasis_dualBasis (B : BilinForm K V) (hB : B.Nondegenerate) (hB' : B.IsSymm) {ι} [Finite ι] [DecidableEq ι] [FiniteDimensional K V] (b : Basis ι K V) : B.dualBasis hB (B.dualBasis hB b) = b := by convert dualBasis_dualBasis_flip _ hB.flip b rwa [eq_comm, ← isSymm_iff_flip] end DualBasis section LinearAdjoints variable [FiniteDimensional K V] /-- Given bilinear forms `B₁, B₂` where `B₂` is nondegenerate, `symmCompOfNondegenerate` is the linear map `B₂ ∘ B₁`. -/ noncomputable def symmCompOfNondegenerate (B₁ B₂ : BilinForm K V) (b₂ : B₂.Nondegenerate) : V →ₗ[K] V := (B₂.toDual b₂).symm.toLinearMap.comp B₁ theorem comp_symmCompOfNondegenerate_apply (B₁ : BilinForm K V) {B₂ : BilinForm K V} (b₂ : B₂.Nondegenerate) (v : V) : B₂ (B₁.symmCompOfNondegenerate B₂ b₂ v) = B₁ v := by rw [symmCompOfNondegenerate] simp only [coe_comp, LinearEquiv.coe_coe, Function.comp_apply] erw [LinearEquiv.apply_symm_apply (B₂.toDual b₂)] @[simp] theorem symmCompOfNondegenerate_left_apply (B₁ : BilinForm K V) {B₂ : BilinForm K V} (b₂ : B₂.Nondegenerate) (v w : V) : B₂ (symmCompOfNondegenerate B₁ B₂ b₂ w) v = B₁ w v := by conv_lhs => rw [comp_symmCompOfNondegenerate_apply] /-- Given the nondegenerate bilinear form `B` and the linear map `φ`, `leftAdjointOfNondegenerate` provides the left adjoint of `φ` with respect to `B`. The lemma proving this property is `BilinForm.isAdjointPairLeftAdjointOfNondegenerate`. -/ noncomputable def leftAdjointOfNondegenerate (B : BilinForm K V) (b : B.Nondegenerate) (φ : V →ₗ[K] V) : V →ₗ[K] V := symmCompOfNondegenerate (B.compRight φ) B b theorem isAdjointPairLeftAdjointOfNondegenerate (B : BilinForm K V) (b : B.Nondegenerate) (φ : V →ₗ[K] V) : IsAdjointPair B B (B.leftAdjointOfNondegenerate b φ) φ := fun x y => (B.compRight φ).symmCompOfNondegenerate_left_apply b y x /-- Given the nondegenerate bilinear form `B`, the linear map `φ` has a unique left adjoint given by `BilinForm.leftAdjointOfNondegenerate`. -/ theorem isAdjointPair_iff_eq_of_nondegenerate (B : BilinForm K V) (b : B.Nondegenerate) (ψ φ : V →ₗ[K] V) : IsAdjointPair B B ψ φ ↔ ψ = B.leftAdjointOfNondegenerate b φ := ⟨fun h => B.isAdjointPair_unique_of_nondegenerate b φ ψ _ h (isAdjointPairLeftAdjointOfNondegenerate _ _ _), fun h => h.symm ▸ isAdjointPairLeftAdjointOfNondegenerate _ _ _⟩ end LinearAdjoints end BilinForm end LinearMap
FunctorCategory.lean
/- Copyright (c) 2022 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kim Morrison -/ import Mathlib.CategoryTheory.Monoidal.Rigid.Basic import Mathlib.CategoryTheory.Monoidal.FunctorCategory /-! # Functors from a groupoid into a right/left rigid category form a right/left rigid category. (Using the pointwise monoidal structure on the functor category.) -/ noncomputable section open CategoryTheory open CategoryTheory.MonoidalCategory namespace CategoryTheory.Monoidal variable {C D : Type*} [Groupoid C] [Category D] [MonoidalCategory D] instance functorHasRightDual [RightRigidCategory D] (F : C ⥤ D) : HasRightDual F where rightDual := { obj := fun X => (F.obj X)ᘁ map := fun f => (F.map (inv f))ᘁ map_comp := fun f g => by simp [comp_rightAdjointMate] } exact := { evaluation' := { app := fun _ => ε_ _ _ naturality := fun X Y f => by dsimp rw [Category.comp_id, Functor.map_inv, ← id_tensor_comp_tensor_id, Category.assoc, id_tensorHom, tensorHom_id, rightAdjointMate_comp_evaluation, ← MonoidalCategory.whiskerLeft_comp_assoc, IsIso.hom_inv_id, MonoidalCategory.whiskerLeft_id, Category.id_comp] } coevaluation' := { app := fun _ => η_ _ _ naturality := fun X Y f => by dsimp rw [Functor.map_inv, Category.id_comp, ← id_tensor_comp_tensor_id, id_tensorHom, tensorHom_id, ← Category.assoc, coevaluation_comp_rightAdjointMate, Category.assoc, ← comp_whiskerRight, IsIso.inv_hom_id, id_whiskerRight, Category.comp_id] } } instance rightRigidFunctorCategory [RightRigidCategory D] : RightRigidCategory (C ⥤ D) where instance functorHasLeftDual [LeftRigidCategory D] (F : C ⥤ D) : HasLeftDual F where leftDual := { obj := fun X => ᘁ(F.obj X) map := fun f => ᘁ(F.map (inv f)) map_comp := fun f g => by simp [comp_leftAdjointMate] } exact := { evaluation' := { app := fun _ => ε_ _ _ naturality := fun X Y f => by simp [tensorHom_def, leftAdjointMate_comp_evaluation] } coevaluation' := { app := fun _ => η_ _ _ naturality := fun X Y f => by simp [tensorHom_def, coevaluation_comp_leftAdjointMate_assoc] } } instance leftRigidFunctorCategory [LeftRigidCategory D] : LeftRigidCategory (C ⥤ D) where instance rigidFunctorCategory [RigidCategory D] : RigidCategory (C ⥤ D) where end CategoryTheory.Monoidal
CompNotation.lean
/- Copyright (c) 2025 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne, Lorenzo Luccioli -/ import Mathlib.Probability.Kernel.Basic /-! # Notation for the compostition of a measure and a kernel This operation, for which we introduce the notation `∘ₘ`, takes `μ : Measure α` and `κ : Kernel α β` and creates `κ ∘ₘ μ : Measure β`. The integral of a function against `κ ∘ₘ μ` is `∫⁻ x, f x ∂(κ ∘ₘ μ) = ∫⁻ a, ∫⁻ b, f b ∂(κ a) ∂μ`. This file does not define composition but only introduces notation for `MeasureTheory.Measure.bind μ κ`. ## Notations * `κ ∘ₘ μ = MeasureTheory.Measure.bind μ κ`, for `κ` a kernel. -/ /- This file is only for lemmas that are direct specializations of `Measure.bind` to kernels, anything more involved should go elsewhere (for example the `MeasureComp` file). -/ assert_not_exists ProbabilityTheory.Kernel.compProd open ProbabilityTheory namespace MeasureTheory.Measure variable {α β : Type*} {mα : MeasurableSpace α} {mβ : MeasurableSpace β} {μ : Measure α} {κ : Kernel α β} /-- Composition of a measure and a kernel. Notation for `MeasureTheory.Measure.bind` -/ scoped[ProbabilityTheory] notation:100 κ:101 " ∘ₘ " μ:100 => MeasureTheory.Measure.bind μ κ @[simp] lemma comp_apply_univ [IsMarkovKernel κ] : (κ ∘ₘ μ) Set.univ = μ Set.univ := by simp [bind_apply .univ κ.aemeasurable] lemma deterministic_comp_eq_map {f : α → β} (hf : Measurable f) : Kernel.deterministic f hf ∘ₘ μ = μ.map f := Measure.bind_dirac_eq_map μ hf @[simp] lemma id_comp : Kernel.id ∘ₘ μ = μ := by rw [Kernel.id, deterministic_comp_eq_map, Measure.map_id] lemma swap_comp {μ : Measure (α × β)} : (Kernel.swap α β) ∘ₘ μ = μ.map Prod.swap := deterministic_comp_eq_map measurable_swap @[simp] lemma const_comp {ν : Measure β} : (Kernel.const α ν) ∘ₘ μ = μ Set.univ • ν := μ.bind_const end MeasureTheory.Measure
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.TopComparison import Mathlib.Topology.Category.CompactlyGenerated /-! # The adjunction between condensed sets and topological spaces This file defines the functor `condensedSetToTopCat : CondensedSet.{u} ⥤ TopCat.{u + 1}` which is left adjoint to `topCatToCondensedSet : TopCat.{u + 1} ⥤ CondensedSet.{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 compactly generated spaces, and we conclude that the functor `topCatToCondensedSet` is fully faithful when restricted to compactly generated spaces. -/ universe u open Condensed CondensedSet CategoryTheory CompHaus variable (X : CondensedSet.{u}) /-- Auxiliary definition to define the topology on `X(*)` for a condensed set `X`. -/ private def CondensedSet.coinducingCoprod : (Σ (i : (S : CompHaus.{u}) × X.val.obj ⟨S⟩), i.fst) → X.val.obj ⟨of PUnit⟩ := fun ⟨⟨_, i⟩, s⟩ ↦ X.val.map ((of PUnit.{u + 1}).const s).op i /-- Let `X` be a condensed set. We define a topology on `X(*)` as the quotient topology of all the maps from compact Hausdorff `S` spaces to `X(*)`, corresponding to elements of `X(S)`. In other words, the topology coinduced by the map `CondensedSet.coinducingCoprod` above. -/ local instance : TopologicalSpace (X.val.obj ⟨CompHaus.of PUnit⟩) := TopologicalSpace.coinduced (coinducingCoprod X) inferInstance /-- The object part of the functor `CondensedSet ⥤ TopCat` -/ abbrev CondensedSet.toTopCat : TopCat.{u + 1} := TopCat.of (X.val.obj ⟨of PUnit⟩) namespace CondensedSet lemma continuous_coinducingCoprod {S : CompHaus.{u}} (x : X.val.obj ⟨S⟩) : Continuous fun a ↦ (X.coinducingCoprod ⟨⟨S, x⟩, a⟩) := by suffices ∀ (i : (T : CompHaus.{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 : CondensedSet} (f : X ⟶ Y) attribute [local instance] Types.instFunLike Types.instConcreteCategory in /-- The map part of the functor `CondensedSet ⥤ TopCat` -/ @[simps!] def toTopCatMap : X.toTopCat ⟶ Y.toTopCat := TopCat.ofHom { toFun := f.val.app ⟨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 Y _ } end CondensedSet /-- The functor `CondensedSet ⥤ TopCat` -/ @[simps] def condensedSetToTopCat : CondensedSet.{u} ⥤ TopCat.{u + 1} where obj X := X.toTopCat map f := toTopCatMap f namespace CondensedSet /-- The counit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ noncomputable def topCatAdjunctionCounit (X : TopCat.{u + 1}) : X.toCondensedSet.toTopCat ⟶ X := TopCat.ofHom { toFun x := x.1 PUnit.unit continuous_toFun := by rw [continuous_coinduced_dom] continuity } /-- `simp`-normal form of the lemma that `@[simps]` would generate. -/ @[simp] lemma topCatAdjunctionCounit_hom_apply (X : TopCat) (x) : -- We have to specify here to not infer the `TopologicalSpace` instance on `C(PUnit, X)`, -- which suggests type synonyms are being unfolded too far somewhere. DFunLike.coe (F := @ContinuousMap C(PUnit, X) X (_) _) (TopCat.Hom.hom (topCatAdjunctionCounit X)) x = x PUnit.unit := rfl /-- The counit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` is always bijective, but not an isomorphism in general (the inverse isn't continuous unless `X` is compactly generated). -/ noncomputable def topCatAdjunctionCounitEquiv (X : TopCat.{u + 1}) : X.toCondensedSet.toTopCat ≃ X where toFun := topCatAdjunctionCounit X invFun x := ContinuousMap.const _ x lemma topCatAdjunctionCounit_bijective (X : TopCat.{u + 1}) : Function.Bijective (topCatAdjunctionCounit X) := (topCatAdjunctionCounitEquiv X).bijective /-- The unit of the adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ @[simps val_app val_app_apply] noncomputable def topCatAdjunctionUnit (X : CondensedSet.{u}) : X ⟶ X.toTopCat.toCondensedSet 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 : CompHaus.{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 `condensedSetToTopCat ⊣ topCatToCondensedSet` -/ noncomputable def topCatAdjunction : condensedSetToTopCat.{u} ⊣ topCatToCondensedSet 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 : topCatToCondensedSet.Faithful := topCatAdjunction.faithful_R_of_epi_counit_app open CompactlyGenerated instance (X : CondensedSet.{u}) : UCompactlyGeneratedSpace.{u, u + 1} X.toTopCat := by apply uCompactlyGeneratedSpace_of_continuous_maps intro Y _ f h rw [continuous_coinduced_dom, continuous_sigma_iff] exact fun ⟨S, s⟩ ↦ h S ⟨_, continuous_coinducingCoprod X _⟩ instance (X : CondensedSet.{u}) : UCompactlyGeneratedSpace.{u, u + 1} (condensedSetToTopCat.obj X) := inferInstanceAs (UCompactlyGeneratedSpace.{u, u + 1} X.toTopCat) /-- The functor from condensed sets to topological spaces lands in compactly generated spaces. -/ def condensedSetToCompactlyGenerated : CondensedSet.{u} ⥤ CompactlyGenerated.{u, u + 1} where obj X := CompactlyGenerated.of (condensedSetToTopCat.obj X) map f := toTopCatMap f /-- The functor from topological spaces to condensed sets restricted to compactly generated spaces. -/ noncomputable def compactlyGeneratedToCondensedSet : CompactlyGenerated.{u, u + 1} ⥤ CondensedSet.{u} := compactlyGeneratedToTop ⋙ topCatToCondensedSet /-- The adjunction `condensedSetToTopCat ⊣ topCatToCondensedSet` restricted to compactly generated spaces. -/ noncomputable def compactlyGeneratedAdjunction : condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet := topCatAdjunction.restrictFullyFaithful (iC := 𝟭 _) (iD := compactlyGeneratedToTop) (Functor.FullyFaithful.id _) fullyFaithfulCompactlyGeneratedToTop (Iso.refl _) (Iso.refl _) /-- The counit of the adjunction `condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet` is a homeomorphism. -/ noncomputable def compactlyGeneratedAdjunctionCounitHomeo (X : TopCat.{u + 1}) [UCompactlyGeneratedSpace.{u} X] : X.toCondensedSet.toTopCat ≃ₜ X where toEquiv := topCatAdjunctionCounitEquiv X continuous_toFun := (topCatAdjunctionCounit X).hom.continuous continuous_invFun := by apply continuous_from_uCompactlyGeneratedSpace exact fun _ _ ↦ continuous_coinducingCoprod X.toCondensedSet _ /-- The counit of the adjunction `condensedSetToCompactlyGenerated ⊣ compactlyGeneratedToCondensedSet` is an isomorphism. -/ noncomputable def compactlyGeneratedAdjunctionCounitIso (X : CompactlyGenerated.{u, u + 1}) : condensedSetToCompactlyGenerated.obj (compactlyGeneratedToCondensedSet.obj X) ≅ X := isoOfHomeo (compactlyGeneratedAdjunctionCounitHomeo X.toTop) instance : IsIso compactlyGeneratedAdjunction.counit := by rw [NatTrans.isIso_iff_isIso_app] intro X exact inferInstanceAs (IsIso (compactlyGeneratedAdjunctionCounitIso X).hom) /-- The functor from topological spaces to condensed sets restricted to compactly generated spaces is fully faithful. -/ noncomputable def fullyFaithfulCompactlyGeneratedToCondensedSet : compactlyGeneratedToCondensedSet.FullyFaithful := compactlyGeneratedAdjunction.fullyFaithfulROfIsIsoCounit end CondensedSet
Instances.lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import Mathlib.Control.Applicative import Mathlib.Control.Traversable.Basic import Mathlib.Data.List.Forall2 import Mathlib.Data.Set.Functor /-! # LawfulTraversable instances This file provides instances of `LawfulTraversable` for types from the core library: `Option`, `List` and `Sum`. -/ universe u v section Option open Functor variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] variable [LawfulApplicative G] theorem Option.id_traverse {α} (x : Option α) : Option.traverse (pure : α → Id α) x = pure x := by cases x <;> rfl theorem Option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : Option α) : Option.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk (Option.traverse f <$> Option.traverse g x) := by cases x <;> (simp [Option.traverse, Option.mapM, functor_norm] <;> rfl) theorem Option.traverse_eq_map_id {α β} (f : α → β) (x : Option α) : Option.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by cases x <;> rfl variable (η : ApplicativeTransformation F G) theorem Option.naturality [LawfulApplicative F] {α β} (f : α → F β) (x : Option α) : η (Option.traverse f x) = Option.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems rcases x with - | x <;> simp! [*, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure, Option.traverse] end Option instance : LawfulTraversable Option := { show LawfulMonad Option from inferInstance with id_traverse := Option.id_traverse comp_traverse := Option.comp_traverse traverse_eq_map_id := Option.traverse_eq_map_id naturality := fun η _ _ f x => Option.naturality η f x } namespace List variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] section variable [LawfulApplicative G] open Applicative Functor List protected theorem id_traverse {α} (xs : List α) : (List.traverse pure xs : Id _) = pure xs := by induction xs <;> simp! [*, List.traverse, functor_norm] protected theorem comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : List α) : List.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk (List.traverse f <$> List.traverse g x) := by induction x <;> simp! [*, functor_norm] <;> rfl protected theorem traverse_eq_map_id {α β} (f : α → β) (x : List α) : List.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by induction x <;> simp! [*, functor_norm] variable [LawfulApplicative F] (η : ApplicativeTransformation F G) protected theorem naturality {α β} (f : α → F β) (x : List α) : η (List.traverse f x) = List.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems induction x <;> simp! [*, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure] instance : LawfulTraversable.{u} List := { show LawfulMonad List from inferInstance with id_traverse := List.id_traverse comp_traverse := List.comp_traverse traverse_eq_map_id := List.traverse_eq_map_id naturality := List.naturality } end section Traverse variable {α' β' : Type u} (f : α' → F β') @[simp] theorem traverse_nil : traverse f ([] : List α') = (pure [] : F (List β')) := rfl @[simp] theorem traverse_cons (a : α') (l : List α') : traverse f (a :: l) = (· :: ·) <$> f a <*> traverse f l := rfl variable [LawfulApplicative F] @[simp] theorem traverse_append : ∀ as bs : List α', traverse f (as ++ bs) = (· ++ ·) <$> traverse f as <*> traverse f bs | [], bs => by simp [functor_norm] | a :: as, bs => by simp [traverse_append as bs, functor_norm]; congr theorem mem_traverse {f : α' → Set β'} : ∀ (l : List α') (n : List β'), n ∈ traverse f l ↔ Forall₂ (fun b a => b ∈ f a) n l | [], [] => by simp | a :: as, [] => by simp | [], b :: bs => by simp | a :: as, b :: bs => by simp [mem_traverse as bs] end Traverse end List namespace Sum section Traverse variable {σ : Type u} variable {F G : Type u → Type u} variable [Applicative F] [Applicative G] open Applicative Functor protected theorem traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : Sum.traverse f (g <$> x) = Sum.traverse (f ∘ g) x := by cases x <;> simp [Sum.traverse, functor_norm] <;> rfl protected theorem id_traverse {σ α} (x : σ ⊕ α) : Sum.traverse (pure : α → Id α) x = x := by cases x <;> rfl variable [LawfulApplicative G] protected theorem comp_traverse {α β γ : Type u} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : Sum.traverse (Comp.mk ∘ (f <$> ·) ∘ g) x = Comp.mk.{u} (Sum.traverse f <$> Sum.traverse g x) := by cases x <;> (simp! [Sum.traverse, map_id, functor_norm] <;> rfl) protected theorem traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : Sum.traverse ((pure : _ → Id _) ∘ f) x = (pure : _ → Id _) (f <$> x) := by induction x <;> simp! [*, functor_norm] <;> rfl protected theorem map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (f <$> ·) <$> Sum.traverse g x = Sum.traverse (f <$> g ·) x := by cases x <;> simp [Sum.traverse, functor_norm] <;> congr variable [LawfulApplicative F] (η : ApplicativeTransformation F G) protected theorem naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (Sum.traverse f x) = Sum.traverse (@η _ ∘ f) x := by -- Porting note: added `ApplicativeTransformation` theorems cases x <;> simp! [Sum.traverse, functor_norm, ApplicativeTransformation.preserves_map, ApplicativeTransformation.preserves_seq, ApplicativeTransformation.preserves_pure] end Traverse instance {σ : Type u} : LawfulTraversable.{u} (Sum σ) := { show LawfulMonad (Sum σ) from inferInstance with id_traverse := Sum.id_traverse comp_traverse := Sum.comp_traverse traverse_eq_map_id := Sum.traverse_eq_map_id naturality := Sum.naturality } end Sum
Frm.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.Order.Category.Frm import Mathlib.Topology.Category.CompHaus.Basic import Mathlib.Topology.Sets.Opens /-! The forgetful functor from `TopCatᵒᵖ` to `Frm`. -/ universe u open TopologicalSpace Opposite CategoryTheory /-- The forgetful functor from `TopCatᵒᵖ` to `Frm`. -/ @[simps] def topCatOpToFrm : TopCatᵒᵖ ⥤ Frm where obj X := Frm.of (Opens (unop X : TopCat)) map f := Frm.ofHom <| Opens.comap <| (Quiver.Hom.unop f).hom -- Note, `CompHaus` is too strong. We only need `T0Space`. instance CompHausOpToFrame.faithful : (compHausToTop.op ⋙ topCatOpToFrm.{u}).Faithful := ⟨fun {X _ _ _} h => Quiver.Hom.unop_inj <| ConcreteCategory.ext <| Opens.comap_injective (β := (unop X).toTop) <| FrameHom.ext <| CategoryTheory.congr_fun h⟩
Basic.lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.Algebra.Module.Torsion import Mathlib.LinearAlgebra.Dimension.Constructions import Mathlib.LinearAlgebra.Dimension.Subsingleton /-! # Rank and torsion ## Main statements - `rank_quotient_eq_of_le_torsion` : `rank M/N = rank M` if `N ≤ torsion M`. -/ open Submodule theorem rank_quotient_eq_of_le_torsion {R M : Type*} [CommRing R] [AddCommGroup M] [Module R M] {M' : Submodule R M} (hN : M' ≤ torsion R M) : Module.rank R (M ⧸ M') = Module.rank R M := (rank_quotient_le M').antisymm <| by nontriviality R rw [Module.rank] refine ciSup_le fun ⟨s, hs⟩ ↦ LinearIndependent.cardinal_le_rank (v := (M'.mkQ ·)) ?_ rw [LinearIndepOn, linearIndependent_iff'] at hs simp_rw [linearIndependent_iff', ← map_smul, ← map_sum, mkQ_apply, Quotient.mk_eq_zero] intro t g hg i hi obtain ⟨r, hg⟩ := hN hg simp_rw [Finset.smul_sum, Submonoid.smul_def, smul_smul] at hg exact r.prop.2 _ (mul_comm (g i) r ▸ hs t _ hg i hi)
BilinearMap.lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import Mathlib.Algebra.Module.Submodule.Equiv import Mathlib.Algebra.NoZeroSMulDivisors.Basic /-! # Basics on bilinear maps This file provides basics on bilinear maps. The most general form considered are maps that are semilinear in both arguments. They are of type `M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P`, where `M` and `N` are modules over `R` and `S` respectively, `P` is a module over both `R₂` and `S₂` with commuting actions, and `ρ₁₂ : R →+* R₂` and `σ₁₂ : S →+* S₂`. ## Main declarations * `LinearMap.mk₂`: a constructor for bilinear maps, taking an unbundled function together with proof witnesses of bilinearity * `LinearMap.flip`: turns a bilinear map `M × N → P` into `N × M → P` * `LinearMap.lflip`: given a linear map from `M` to `N →ₗ[R] P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to `M →ₗ[R] P`. * `LinearMap.lcomp`: composition of a given linear map `M → N` with a linear map `N → P` as a linear map from `Nₗ →ₗ[R] Pₗ` to `M →ₗ[R] Pₗ` * `LinearMap.llcomp`: composition of linear maps as a bilinear map from `(M →ₗ[R] N) × (N →ₗ[R] P)` to `M →ₗ[R] P` * `LinearMap.compl₂`: composition of a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. * `LinearMap.compr₂`: composition of a linear map `P → Q` and a bilinear map `M → N → P` to form a bilinear map `M → N → Q`. * `LinearMap.lsmul`: scalar multiplication as a bilinear map `R × M → M` ## Tags bilinear -/ open Function namespace LinearMap section Semiring -- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps variable {R : Type*} [Semiring R] {S : Type*} [Semiring S] variable {R₂ : Type*} [Semiring R₂] {S₂ : Type*} [Semiring S₂] variable {M : Type*} {N : Type*} {P : Type*} variable {M₂ : Type*} {N₂ : Type*} {P₂ : Type*} variable {Pₗ : Type*} variable {M' : Type*} {P' : Type*} variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] variable [AddCommMonoid M₂] [AddCommMonoid N₂] [AddCommMonoid P₂] [AddCommMonoid Pₗ] variable [AddCommGroup M'] [AddCommGroup P'] variable [Module R M] [Module S N] [Module R₂ P] [Module S₂ P] variable [Module R M₂] [Module S N₂] [Module R P₂] [Module S₂ P₂] variable [Module R Pₗ] [Module S Pₗ] variable [Module R M'] [Module R₂ P'] [Module S₂ P'] variable [SMulCommClass S₂ R₂ P] [SMulCommClass S R Pₗ] [SMulCommClass S₂ R₂ P'] variable [SMulCommClass S₂ R P₂] variable {ρ₁₂ : R →+* R₂} {σ₁₂ : S →+* S₂} variable (ρ₁₂ σ₁₂) /-- Create a bilinear map from a function that is semilinear in each component. See `mk₂'` and `mk₂` for the linear case. -/ def mk₂'ₛₗ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c : R) (m n), f (c • m) n = ρ₁₂ c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c : S) (m n), f m (c • n) = σ₁₂ c • f m n) : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P where toFun m := { toFun := f m map_add' := H3 m map_smul' := fun c => H4 c m } map_add' m₁ m₂ := LinearMap.ext <| H1 m₁ m₂ map_smul' c m := LinearMap.ext <| H2 c m variable {ρ₁₂ σ₁₂} @[simp] theorem mk₂'ₛₗ_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂'ₛₗ ρ₁₂ σ₁₂ f H1 H2 H3 H4 : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) m n = f m n := rfl variable (R S) /-- Create a bilinear map from a function that is linear in each component. See `mk₂` for the special case where both arguments come from modules over the same ring. -/ def mk₂' (f : M → N → Pₗ) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c : R) (m n), f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c : S) (m n), f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] Pₗ := mk₂'ₛₗ (RingHom.id R) (RingHom.id S) f H1 H2 H3 H4 variable {R S} @[simp] theorem mk₂'_apply (f : M → N → Pₗ) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] Pₗ) m n = f m n := rfl theorem ext₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : ∀ m n, f m n = g m n) : f = g := LinearMap.ext fun m => LinearMap.ext fun n => H m n theorem congr_fun₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (h : f = g) (x y) : f x y = g x y := LinearMap.congr_fun (LinearMap.congr_fun h x) y theorem ext_iff₂ {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} : f = g ↔ ∀ m n, f m n = g m n := ⟨congr_fun₂, ext₂⟩ section attribute [local instance] SMulCommClass.symm /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P := mk₂'ₛₗ σ₁₂ ρ₁₂ (fun n m => f m n) (fun _ _ m => (f m).map_add _ _) (fun _ _ m => (f m).map_smulₛₗ _ _) (fun n m₁ m₂ => by simp only [map_add, add_apply]) -- Note: https://github.com/leanprover-community/mathlib4/pull/8386 changed `map_smulₛₗ` into `map_smulₛₗ _`. -- It looks like we now run out of assignable metavariables. (fun c n m => by simp only [map_smulₛₗ _, smul_apply]) end @[simp] theorem flip_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (m : M) (n : N) : flip f n m = f m n := rfl attribute [local instance] SMulCommClass.symm @[simp] theorem flip_flip (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : f.flip.flip = f := LinearMap.ext₂ fun _x _y => (f.flip.flip_apply _ _).trans (f.flip_apply _ _) theorem flip_inj {f g : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P} (H : flip f = flip g) : f = g := ext₂ fun m n => show flip f n m = flip g n m by rw [H] theorem map_zero₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_sub₂ (f : M' →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P') (x y z) : f (x - y) z = f x z - f y z := (flip f z).map_sub _ _ theorem map_add₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (f : M₂ →ₗ[R] N₂ →ₛₗ[σ₁₂] P₂) (r : R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ theorem map_smulₛₗ₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (r : R) (x y) : f (r • x) y = ρ₁₂ r • f x y := (flip f y).map_smulₛₗ _ _ theorem map_sum₂ {ι : Type*} (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (t : Finset ι) (x : ι → M) (y) : f (∑ i ∈ t, x i) y = ∑ i ∈ t, f (x i) y := _root_.map_sum (flip f y) _ _ /-- Restricting a bilinear map in the second entry -/ def domRestrict₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : Submodule S N) : M →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P where toFun m := (f m).domRestrict q map_add' m₁ m₂ := LinearMap.ext fun _ => by simp only [map_add, domRestrict_apply, add_apply] map_smul' c m := LinearMap.ext fun _ => by simp only [f.map_smulₛₗ, domRestrict_apply, smul_apply] theorem domRestrict₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (q : Submodule S N) (x : M) (y : q) : f.domRestrict₂ q x y = f x y := rfl /-- Restricting a bilinear map in both components -/ def domRestrict₁₂ (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : Submodule R M) (q : Submodule S N) : p →ₛₗ[ρ₁₂] q →ₛₗ[σ₁₂] P := (f.domRestrict p).domRestrict₂ q theorem domRestrict₁₂_apply (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) (p : Submodule R M) (q : Submodule S N) (x : p) (y : q) : f.domRestrict₁₂ p q x y = f x y := rfl section restrictScalars variable (R' S' : Type*) variable [Semiring R'] [Semiring S'] [Module R' M] [Module S' N] [Module R' Pₗ] [Module S' Pₗ] variable [SMulCommClass S' R' Pₗ] variable [SMul S' S] [IsScalarTower S' S N] [IsScalarTower S' S Pₗ] variable [SMul R' R] [IsScalarTower R' R M] [IsScalarTower R' R Pₗ] /-- If `B : M → N → Pₗ` is `R`-`S` bilinear and `R'` and `S'` are compatible scalar multiplications, then the restriction of scalars is a `R'`-`S'` bilinear map. -/ @[simps!] def restrictScalars₁₂ (B : M →ₗ[R] N →ₗ[S] Pₗ) : M →ₗ[R'] N →ₗ[S'] Pₗ := LinearMap.mk₂' R' S' (B · ·) B.map_add₂ (fun r' m _ ↦ by dsimp only rw [← smul_one_smul R r' m, map_smul₂, smul_one_smul]) (fun _ ↦ map_add _) (fun _ x ↦ (B x).map_smul_of_tower _) theorem restrictScalars₁₂_injective : Function.Injective (LinearMap.restrictScalars₁₂ R' S' : (M →ₗ[R] N →ₗ[S] Pₗ) → (M →ₗ[R'] N →ₗ[S'] Pₗ)) := fun _ _ h ↦ ext₂ (congr_fun₂ h :) @[simp] theorem restrictScalars₁₂_inj {B B' : M →ₗ[R] N →ₗ[S] Pₗ} : B.restrictScalars₁₂ R' S' = B'.restrictScalars₁₂ R' S' ↔ B = B' := (restrictScalars₁₂_injective R' S').eq_iff end restrictScalars /-- `LinearMap.flip` as an isomorphism of modules. -/ def lflip {R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P] [SMulCommClass R₂ R₀ P] : (M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) ≃ₗ[R₀] (N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P) where toFun := flip invFun := flip map_add' _ _ := rfl map_smul' _ _ := rfl left_inv _ := rfl right_inv _ := rfl @[simp] theorem lflip_symm {R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P] [SMulCommClass R₂ R₀ P] : (lflip : (M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) ≃ₗ[R₀] (N →ₛₗ[σ₁₂] M →ₛₗ[ρ₁₂] P)).symm = lflip := rfl @[simp] theorem lflip_apply {R₀ : Type*} [Semiring R₀] [Module R₀ P] [SMulCommClass S₂ R₀ P] [SMulCommClass R₂ R₀ P] (f : M →ₛₗ[ρ₁₂] N →ₛₗ[σ₁₂] P) : lflip (R₀ := R₀) f = f.flip := rfl end Semiring section Semiring variable {R R₂ R₃ R₄ R₅ : Type*} variable {M N P Q : Type*} variable [Semiring R] [Semiring R₂] [Semiring R₃] [Semiring R₄] [Semiring R₅] variable {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃} variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q] variable [Module R M] [Module R₂ N] [Module R₃ P] [Module R₄ Q] [Module R₅ P] variable [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₄₂ σ₂₃ σ₄₃] variable [SMulCommClass R₃ R₅ P] {σ₁₅ : R →+* R₅} variable (R₅ P σ₂₃) /-- Composing a semilinear map `M → N` and a semilinear map `N → P` to form a semilinear map `M → P` is itself a linear map. -/ def lcompₛₗ (f : M →ₛₗ[σ₁₂] N) : (N →ₛₗ[σ₂₃] P) →ₗ[R₅] M →ₛₗ[σ₁₃] P := letI := SMulCommClass.symm flip <| LinearMap.comp (flip id) f variable {P σ₂₃ R₅} @[simp] theorem lcompₛₗ_apply (f : M →ₛₗ[σ₁₂] N) (g : N →ₛₗ[σ₂₃] P) (x : M) : lcompₛₗ R₅ P σ₂₃ f g x = g (f x) := rfl /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) (g : Q →ₛₗ[σ₄₂] N) : M →ₛₗ[σ₁₅] Q →ₛₗ[σ₄₃] P where toFun a := (lcompₛₗ R₅ P σ₂₃ g) (h a) map_add' _ _ := by simp [map_add] map_smul' _ _ := by simp only [LinearMap.map_smulₛₗ, lcompₛₗ] rfl @[simp] theorem compl₂_apply (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) (g : Q →ₛₗ[σ₄₂] N) (m : M) (q : Q) : h.compl₂ g m q = h m (g q) := rfl @[simp] theorem compl₂_id (h : M →ₛₗ[σ₁₅] N →ₛₗ[σ₂₃] P) : h.compl₂ LinearMap.id = h := by ext rw [compl₂_apply, id_coe, _root_.id] end Semiring section CommSemiring variable {R R₁ R₂ : Type*} [CommSemiring R] [Semiring R₁] [Semiring R₂] variable {A : Type*} [Semiring A] {B : Type*} [Semiring B] variable {M : Type*} {N : Type*} {P : Type*} {Q : Type*} variable {Mₗ : Type*} {Nₗ : Type*} {Pₗ : Type*} {Qₗ Qₗ' : Type*} variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q] variable [AddCommMonoid Mₗ] [AddCommMonoid Nₗ] [AddCommMonoid Pₗ] variable [AddCommMonoid Qₗ] [AddCommMonoid Qₗ'] variable [Module R M] variable [Module R Mₗ] [Module R Nₗ] [Module R Pₗ] [Module R Qₗ] [Module R Qₗ'] variable [Module R₁ Mₗ] [Module R₂ N] [Module R₁ Pₗ] [Module R₁ Qₗ] variable [Module R₂ Pₗ] [Module R₂ Qₗ'] variable (R) /-- Create a bilinear map from a function that is linear in each component. This is a shorthand for `mk₂'` for the common case when `R = S`. -/ def mk₂ (f : M → Nₗ → Pₗ) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c : R) (m n), f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c : R) (m n), f m (c • n) = c • f m n) : M →ₗ[R] Nₗ →ₗ[R] Pₗ := mk₂' R R f H1 H2 H3 H4 @[simp] theorem mk₂_apply (f : M → Nₗ → Pₗ) {H1 H2 H3 H4} (m : M) (n : Nₗ) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] Nₗ →ₗ[R] Pₗ) m n = f m n := rfl variable {R} variable (A Pₗ) variable [Module A Pₗ] [SMulCommClass R A Pₗ] /-- Composing a given linear map `M → N` with a linear map `N → P` as a linear map from `Nₗ →ₗ[R] Pₗ` to `M →ₗ[R] Pₗ`. -/ def lcomp (f : M →ₗ[R] Nₗ) : (Nₗ →ₗ[R] Pₗ) →ₗ[A] M →ₗ[R] Pₗ := lcompₛₗ _ _ _ f variable {A Pₗ} @[simp] theorem lcomp_apply (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) (x : M) : lcomp A _ f g x = g (f x) := rfl theorem lcomp_apply' (f : M →ₗ[R] Nₗ) (g : Nₗ →ₗ[R] Pₗ) : lcomp A Pₗ f g = g ∘ₗ f := rfl /-- Composing linear maps `Q → M` and `Q' → N` with a bilinear map `M → N → P` to form a bilinear map `Q → Q' → P`. -/ def compl₁₂ [SMulCommClass R₂ R₁ Pₗ] (f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) (g : Qₗ →ₗ[R₁] Mₗ) (g' : Qₗ' →ₗ[R₂] N) : Qₗ →ₗ[R₁] Qₗ' →ₗ[R₂] Pₗ := (f.comp g).compl₂ g' @[simp] theorem compl₁₂_apply [SMulCommClass R₂ R₁ Pₗ] (f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) (g : Qₗ →ₗ[R₁] Mₗ) (g' : Qₗ' →ₗ[R₂] N) (x : Qₗ) (y : Qₗ') : f.compl₁₂ g g' x y = f (g x) (g' y) := rfl @[simp] theorem compl₁₂_id_id [SMulCommClass R₂ R₁ Pₗ] (f : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ) : f.compl₁₂ LinearMap.id LinearMap.id = f := by ext simp_rw [compl₁₂_apply, id_coe, _root_.id] theorem compl₁₂_inj [SMulCommClass R₂ R₁ Pₗ] {f₁ f₂ : Mₗ →ₗ[R₁] N →ₗ[R₂] Pₗ} {g : Qₗ →ₗ[R₁] Mₗ} {g' : Qₗ' →ₗ[R₂] N} (hₗ : Function.Surjective g) (hᵣ : Function.Surjective g') : f₁.compl₁₂ g g' = f₂.compl₁₂ g g' ↔ f₁ = f₂ := by constructor <;> intro h · -- B₁.comp l r = B₂.comp l r → B₁ = B₂ ext x y obtain ⟨x', hx⟩ := hₗ x subst hx obtain ⟨y', hy⟩ := hᵣ y subst hy convert LinearMap.congr_fun₂ h x' y' using 0 · -- B₁ = B₂ → B₁.comp l r = B₂.comp l r subst h; rfl omit [Module R M] in /-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to form a bilinear map `M → N → Q`. See `LinearMap.compr₂ₛₗ` for a version of this which does not support towers of scalars but which does support semi-linear maps. -/ def compr₂ [Module R A] [Module A M] [Module A Qₗ] [SMulCommClass R A Qₗ] [IsScalarTower R A Qₗ] [IsScalarTower R A Pₗ] (f : M →ₗ[A] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[A] Qₗ) : M →ₗ[A] Nₗ →ₗ[R] Qₗ where toFun x := g.restrictScalars R ∘ₗ (f x) map_add' _ _ := by ext; simp map_smul' _ _ := by ext; simp omit [Module R M] in @[simp] theorem compr₂_apply [Module R A] [Module A M] [Module A Qₗ] [SMulCommClass R A Qₗ] [IsScalarTower R A Qₗ] [IsScalarTower R A Pₗ] (f : M →ₗ[A] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[A] Qₗ) (m : M) (n : Nₗ) : f.compr₂ g m n = g (f m n) := rfl /-- A version of `Function.Injective.comp` for composition of a bilinear map with a linear map. -/ theorem injective_compr₂_of_injective (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (hf : Injective f) (hg : Injective g) : Injective (f.compr₂ g) := hg.injective_linearMapComp_left.comp hf /-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/ theorem surjective_compr₂_of_exists_rightInverse (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ →ₗ[R] Qₗ) (hf : Surjective f) (hg : ∃ g' : Qₗ →ₗ[R] Pₗ, g.comp g' = LinearMap.id) : Surjective (f.compr₂ g) := (surjective_comp_left_of_exists_rightInverse hg).comp hf /-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/ theorem surjective_compr₂_of_equiv (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ ≃ₗ[R] Qₗ) (hf : Surjective f) : Surjective (f.compr₂ g.toLinearMap) := surjective_compr₂_of_exists_rightInverse f g.toLinearMap hf ⟨g.symm, by simp⟩ /-- A version of `Function.Bijective.comp` for composition of a bilinear map with a linear map. -/ theorem bijective_compr₂_of_equiv (f : M →ₗ[R] Nₗ →ₗ[R] Pₗ) (g : Pₗ ≃ₗ[R] Qₗ) (hf : Bijective f) : Bijective (f.compr₂ g.toLinearMap) := ⟨injective_compr₂_of_injective f g.toLinearMap hf.1 g.bijective.1, surjective_compr₂_of_equiv f g hf.2⟩ section CommSemiringSemilinear variable {R₂ R₃ R₄ M N P Q : Type*} variable [CommSemiring R₂] [CommSemiring R₃] [CommSemiring R₄] variable [AddCommMonoid M] [AddCommMonoid N] [AddCommMonoid P] [AddCommMonoid Q] variable [Module R M] [Module R₂ N] [Module R₃ P] [Module R₄ Q] variable {σ₁₂ : R →+* R₂} {σ₁₃ : R →+* R₃} {σ₁₄ : R →+* R₄} {σ₂₃ : R₂ →+* R₃} variable {σ₂₄ : R₂ →+* R₄} {σ₃₄ : R₃ →+* R₄} {σ₄₂ : R₄ →+* R₂} {σ₄₃ : R₄ →+* R₃} variable [RingHomCompTriple σ₁₂ σ₂₃ σ₁₃] [RingHomCompTriple σ₄₂ σ₂₃ σ₄₃] variable [RingHomCompTriple σ₂₃ σ₃₄ σ₂₄] [RingHomCompTriple σ₁₃ σ₃₄ σ₁₄] variable [RingHomCompTriple σ₂₄ σ₄₃ σ₂₃] variable (M N P) variable (R₃) in /-- Composing linear maps as a bilinear map from `(M →ₛₗ[σ₁₂] N) × (N →ₛₗ[σ₂₃] P)` to `M →ₛₗ[σ₁₃] P`. -/ def llcomp : (N →ₛₗ[σ₂₃] P) →ₗ[R₃] (M →ₛₗ[σ₁₂] N) →ₛₗ[σ₂₃] M →ₛₗ[σ₁₃] P := flip { toFun := lcompₛₗ _ P σ₂₃ map_add' := fun _f _f' => ext₂ fun g _x => g.map_add _ _ map_smul' := fun (_c : R₂) _f => ext₂ fun g _x => g.map_smulₛₗ _ _ } variable {M N P} @[simp] theorem llcomp_apply (f : N →ₛₗ[σ₂₃] P) (g : M →ₛₗ[σ₁₂] N) (x : M) : llcomp _ M N P f g x = f (g x) := rfl theorem llcomp_apply' (f : N →ₛₗ[σ₂₃] P) (g : M →ₛₗ[σ₁₂] N) : llcomp _ M N P f g = f ∘ₛₗ g := rfl omit [Module R M] in /-- Composing a linear map `P →ₛₗ[σ₃₄] Q` and a bilinear map `M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P` to form a bilinear map `M →ₛₗ[σ₁₄] N →ₛₗ[σ₂₄] Q`. See `LinearMap.compr₂` for a version of this definition, which does not support semi-linear maps but which does support towers of scalars. -/ def compr₂ₛₗ (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) : M →ₛₗ[σ₁₄] N →ₛₗ[σ₂₄] Q := llcomp _ N P Q g ∘ₛₗ f @[simp] theorem compr₂ₛₗ_apply (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) (m : M) (n : N) : f.compr₂ₛₗ g m n = g (f m n) := rfl /-- A version of `Function.Injective.comp` for composition of a bilinear map with a linear map. -/ theorem injective_compr₂ₛₗ_of_injective (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) (hf : Injective f) (hg : Injective g) : Injective (f.compr₂ₛₗ g) := hg.injective_linearMapComp_left.comp hf /-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/ theorem surjective_compr₂ₛₗ_of_exists_rightInverse [RingHomInvPair σ₃₄ σ₄₃] (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P →ₛₗ[σ₃₄] Q) (hf : Surjective f) (hg : ∃ g' : Q →ₛₗ[σ₄₃] P, g.comp g' = LinearMap.id) : Surjective (f.compr₂ₛₗ g) := (surjective_comp_left_of_exists_rightInverse hg).comp hf /-- A version of `Function.Surjective.comp` for composition of a bilinear map with a linear map. -/ theorem surjective_compr₂ₛₗ_of_equiv [RingHomInvPair σ₃₄ σ₄₃] [RingHomInvPair σ₄₃ σ₃₄] (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P ≃ₛₗ[σ₃₄] Q) (hf : Surjective f) : Surjective (f.compr₂ₛₗ g.toLinearMap) := surjective_compr₂ₛₗ_of_exists_rightInverse f g.toLinearMap hf ⟨g.symm, by simp⟩ /-- A version of `Function.Bijective.comp` for composition of a bilinear map with a linear map. -/ theorem bijective_compr₂ₛₗ_of_equiv [RingHomInvPair σ₃₄ σ₄₃] [RingHomInvPair σ₄₃ σ₃₄] (f : M →ₛₗ[σ₁₃] N →ₛₗ[σ₂₃] P) (g : P ≃ₛₗ[σ₃₄] Q) (hf : Bijective f) : Bijective (f.compr₂ₛₗ g.toLinearMap) := ⟨injective_compr₂ₛₗ_of_injective f g.toLinearMap hf.1 g.bijective.1, surjective_compr₂ₛₗ_of_equiv f g hf.2⟩ end CommSemiringSemilinear variable (R M) /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul : R →ₗ[R] M →ₗ[R] M := mk₂ R (· • ·) add_smul (fun _ _ _ => mul_smul _ _ _) smul_add fun r s m => by simp only [smul_smul, mul_comm] variable {R} lemma lsmul_eq_DistribMulAction_toLinearMap (r : R) : lsmul R M r = DistribMulAction.toLinearMap R M r := rfl variable {M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl variable (R M Nₗ) in /-- A shorthand for the type of `R`-bilinear `Nₗ`-valued maps on `M`. -/ protected abbrev BilinMap : Type _ := M →ₗ[R] M →ₗ[R] Nₗ variable (R M) in /-- For convenience, a shorthand for the type of bilinear forms from `M` to `R`. -/ protected abbrev BilinForm : Type _ := LinearMap.BilinMap R M R end CommSemiring section CommRing variable {R M : Type*} [CommRing R] section AddCommGroup variable [AddCommGroup M] [Module R M] theorem lsmul_injective [NoZeroSMulDivisors R M] {x : R} (hx : x ≠ 0) : Function.Injective (lsmul R M x) := smul_right_injective _ hx theorem ker_lsmul [NoZeroSMulDivisors R M] {a : R} (ha : a ≠ 0) : LinearMap.ker (LinearMap.lsmul R M a) = ⊥ := LinearMap.ker_eq_bot_of_injective (LinearMap.lsmul_injective ha) end AddCommGroup end CommRing open Function section restrictScalarsRange variable {R S M P M' P' : Type*} [Semiring R] [Semiring S] [SMul S R] [AddCommMonoid M] [Module R M] [AddCommMonoid P] [Module R P] [Module S M] [Module S P] [IsScalarTower S R M] [IsScalarTower S R P] [AddCommMonoid M'] [Module S M'] [AddCommMonoid P'] [Module S P'] variable (i : M' →ₗ[S] M) (k : P' →ₗ[S] P) (hk : Injective k) (f : M →ₗ[R] P) (hf : ∀ m, f (i m) ∈ LinearMap.range k) /-- Restrict the scalars and range of a linear map. -/ noncomputable def restrictScalarsRange : M' →ₗ[S] P' := ((f.restrictScalars S).comp i).codLift k hk hf @[simp] lemma restrictScalarsRange_apply (m : M') : k (restrictScalarsRange i k hk f hf m) = f (i m) := by have : k (restrictScalarsRange i k hk f hf m) = (k ∘ₗ ((f.restrictScalars S).comp i).codLift k hk hf) m := rfl rw [this, comp_codLift, comp_apply, restrictScalars_apply] @[simp] lemma eq_restrictScalarsRange_iff (m : M') (p : P') : p = restrictScalarsRange i k hk f hf m ↔ k p = f (i m) := by rw [← restrictScalarsRange_apply i k hk f hf m, hk.eq_iff] @[simp] lemma restrictScalarsRange_apply_eq_zero_iff (m : M') : restrictScalarsRange i k hk f hf m = 0 ↔ f (i m) = 0 := by rw [← hk.eq_iff, restrictScalarsRange_apply, map_zero] end restrictScalarsRange section restrictScalarsRange₂ variable {R S M N P M' N' P' : Type*} [CommSemiring R] [CommSemiring S] [SMul S R] [AddCommMonoid M] [Module R M] [AddCommMonoid N] [Module R N] [AddCommMonoid P] [Module R P] [Module S M] [Module S N] [Module S P] [IsScalarTower S R M] [IsScalarTower S R N] [IsScalarTower S R P] [AddCommMonoid M'] [Module S M'] [AddCommMonoid N'] [Module S N'] [AddCommMonoid P'] [Module S P'] [SMulCommClass R S P] variable (i : M' →ₗ[S] M) (j : N' →ₗ[S] N) (k : P' →ₗ[S] P) (hk : Injective k) (B : M →ₗ[R] N →ₗ[R] P) (hB : ∀ m n, B (i m) (j n) ∈ LinearMap.range k) /-- Restrict the scalars, domains, and range of a bilinear map. -/ noncomputable def restrictScalarsRange₂ : M' →ₗ[S] N' →ₗ[S] P' := (((LinearMap.restrictScalarsₗ S R _ _ _).comp (B.restrictScalars S)).compl₁₂ i j).codRestrict₂ k hk hB @[simp] lemma restrictScalarsRange₂_apply (m : M') (n : N') : k (restrictScalarsRange₂ i j k hk B hB m n) = B (i m) (j n) := by simp [restrictScalarsRange₂] @[simp] lemma eq_restrictScalarsRange₂_iff (m : M') (n : N') (p : P') : p = restrictScalarsRange₂ i j k hk B hB m n ↔ k p = B (i m) (j n) := by rw [← restrictScalarsRange₂_apply i j k hk B hB m n, hk.eq_iff] @[simp] lemma restrictScalarsRange₂_apply_eq_zero_iff (m : M') (n : N') : restrictScalarsRange₂ i j k hk B hB m n = 0 ↔ B (i m) (j n) = 0 := by rw [← hk.eq_iff, restrictScalarsRange₂_apply, map_zero] end restrictScalarsRange₂ end LinearMap
Basic.lean
/- Copyright (c) 2017 Kim Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Kim Morrison, Mario Carneiro, Andrew Yang -/ import Mathlib.Topology.Category.TopCat.Adjunctions import Mathlib.CategoryTheory.Limits.Types.Limits import Mathlib.CategoryTheory.Limits.Types.Colimits import Mathlib.CategoryTheory.Limits.Shapes.Terminal import Mathlib.CategoryTheory.Adjunction.Limits /-! # The category of topological spaces has all limits and colimits Further, these limits and colimits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ open TopologicalSpace CategoryTheory CategoryTheory.Limits Opposite universe v u u' w noncomputable section local notation "forget" => forget TopCat namespace TopCat section Limits variable {J : Type v} [Category.{w} J] /-- A choice of limit cone for a functor `F : J ⥤ TopCat`. Generally you should just use `limit.cone F`, unless you need the actual definition (which is in terms of `Types.limitCone`). -/ def limitCone (F : J ⥤ TopCat.{max v u}) : Cone F where pt := TopCat.of { u : ∀ j : J, F.obj j | ∀ {i j : J} (f : i ⟶ j), F.map f (u i) = u j } π := { app := fun j => ofHom { toFun := fun u => u.val j -- Porting note: `continuity` from the original mathlib3 proof failed here. continuous_toFun := Continuous.comp (continuous_apply _) (continuous_subtype_val) } naturality := fun X Y f => by ext a exact (a.2 f).symm } /-- The chosen cone `TopCat.limitCone F` for a functor `F : J ⥤ TopCat` is a limit cone. Generally you should just use `limit.isLimit F`, unless you need the actual definition (which is in terms of `Types.limitConeIsLimit`). -/ def limitConeIsLimit (F : J ⥤ TopCat.{max v u}) : IsLimit (limitCone.{v,u} F) where lift S := ofHom { toFun := fun x => ⟨fun _ => S.π.app _ x, fun f => by dsimp rw [← S.w f] rfl⟩ continuous_toFun := Continuous.subtype_mk (continuous_pi fun j => (S.π.app j).hom.2) fun x i j f => by dsimp rw [← S.w f] rfl } uniq S m h := by ext a simp [← h] rfl section variable {F : J ⥤ TopCat.{u}} (c : Cone (F ⋙ forget)) /-- Given a functor `F : J ⥤ TopCat` and a cone `c : Cone (F ⋙ forget)` of the underlying functor to types, this is the type `c.pt` with the infimum of the induced topologies by the maps `c.π.app j`. -/ def conePtOfConeForget : Type _ := c.pt instance topologicalSpaceConePtOfConeForget : TopologicalSpace (conePtOfConeForget c) := (⨅ j, (F.obj j).str.induced (c.π.app j)) /-- Given a functor `F : J ⥤ TopCat` and a cone `c : Cone (F ⋙ forget)` of the underlying functor to types, this is a cone for `F` whose point is `c.pt` with the infimum of the induced topologies by the maps `c.π.app j`. -/ @[simps pt π_app] def coneOfConeForget : Cone F where pt := of (conePtOfConeForget c) π := { app j := ofHom (ContinuousMap.mk (c.π.app j) (by rw [continuous_iff_le_induced] exact iInf_le (fun j ↦ (F.obj j).str.induced (c.π.app j)) j)) naturality j j' φ := by ext apply congr_fun (c.π.naturality φ) } /-- Given a functor `F : J ⥤ TopCat` and a cone `c : Cone (F ⋙ forget)` of the underlying functor to types, the limit of `F` is `c.pt` equipped with the infimum of the induced topologies by the maps `c.π.app j`. -/ def isLimitConeOfForget (c : Cone (F ⋙ forget)) (hc : IsLimit c) : IsLimit (coneOfConeForget c) := by refine IsLimit.ofFaithful forget (ht := hc) (fun s ↦ ofHom (ContinuousMap.mk (hc.lift ((forget).mapCone s)) ?_)) (fun _ ↦ rfl) rw [continuous_iff_coinduced_le] dsimp [topologicalSpaceConePtOfConeForget] rw [le_iInf_iff] intro j rw [coinduced_le_iff_le_induced, induced_compose] convert continuous_iff_le_induced.1 (s.π.app j).hom.continuous exact hc.fac ((forget).mapCone s) j end section IsLimit variable {F : J ⥤ TopCat.{u}} (c : Cone F) (hc : IsLimit c) include hc theorem induced_of_isLimit : c.pt.str = ⨅ j, (F.obj j).str.induced (c.π.app j) := by let c' := coneOfConeForget ((forget).mapCone c) let hc' : IsLimit c' := isLimitConeOfForget _ (isLimitOfPreserves forget hc) let e := IsLimit.conePointUniqueUpToIso hc' hc have he (j : J) : e.inv ≫ c'.π.app j = c.π.app j := IsLimit.conePointUniqueUpToIso_inv_comp hc' hc j apply (homeoOfIso e.symm).induced_eq.symm.trans dsimp [coneOfConeForget_pt, c', topologicalSpaceConePtOfConeForget] conv_rhs => simp only [← he] simp [← induced_compose, homeoOfIso, c'] end IsLimit variable (F : J ⥤ TopCat.{u}) theorem limit_topology [HasLimit F] : (limit F).str = ⨅ j, (F.obj j).str.induced (limit.π F j) := induced_of_isLimit _ (limit.isLimit _) lemma hasLimit_iff_small_sections : HasLimit F ↔ Small.{u} ((F ⋙ forget).sections) := by rw [← Types.hasLimit_iff_small_sections] constructor <;> intro · infer_instance · exact ⟨⟨_, isLimitConeOfForget _ (limit.isLimit _)⟩⟩ instance topCat_hasLimitsOfShape (J : Type v) [Category J] [Small.{u} J] : HasLimitsOfShape J TopCat.{u} where has_limit := fun F => by rw [hasLimit_iff_small_sections] infer_instance instance topCat_hasLimitsOfSize [UnivLE.{v, u}] : HasLimitsOfSize.{w, v} TopCat.{u} where instance topCat_hasLimits : HasLimits TopCat.{u} := TopCat.topCat_hasLimitsOfSize.{u, u} instance forget_preservesLimitsOfSize : PreservesLimitsOfSize.{w, v} (forget : TopCat.{u} ⥤ _) where instance forget_preservesLimits : PreservesLimits (forget : TopCat.{u} ⥤ _) where end Limits section Colimits variable {J : Type v} [Category.{w} J] {F : J ⥤ TopCat.{u}} section variable (c : Cocone (F ⋙ forget)) /-- Given a functor `F : J ⥤ TopCat` and a cocone `c : Cocone (F ⋙ forget)` of the underlying cocone of types, this is the type `c.pt` with the supremum of the topologies that are coinduced by the maps `c.ι.app j`. -/ def coconePtOfCoconeForget : Type _ := c.pt instance topologicalSpaceCoconePtOfCoconeForget : TopologicalSpace (coconePtOfCoconeForget c) := (⨆ j, (F.obj j).str.coinduced (c.ι.app j)) /-- Given a functor `F : J ⥤ TopCat` and a cocone `c : Cocone (F ⋙ forget)` of the underlying cocone of types, this is a cocone for `F` whose point is `c.pt` with the supremum of the coinduced topologies by the maps `c.ι.app j`. -/ @[simps pt ι_app] def coconeOfCoconeForget : Cocone F where pt := of (coconePtOfCoconeForget c) ι := { app j := ofHom (ContinuousMap.mk (c.ι.app j) (by rw [continuous_iff_coinduced_le] exact le_iSup (fun j ↦ (F.obj j).str.coinduced (c.ι.app j)) j)) naturality j j' φ := by ext apply congr_fun (c.ι.naturality φ) } /-- Given a functor `F : J ⥤ TopCat` and a cocone `c : Cocone (F ⋙ forget)` of the underlying cocone of types, the colimit of `F` is `c.pt` equipped with the supremum of the coinduced topologies by the maps `c.ι.app j`. -/ def isColimitCoconeOfForget (c : Cocone (F ⋙ forget)) (hc : IsColimit c) : IsColimit (coconeOfCoconeForget c) := by refine IsColimit.ofFaithful forget (ht := hc) (fun s ↦ ofHom (ContinuousMap.mk (hc.desc ((forget).mapCocone s)) ?_)) (fun _ ↦ rfl) rw [continuous_iff_le_induced] dsimp [topologicalSpaceCoconePtOfCoconeForget] rw [iSup_le_iff] intro j rw [coinduced_le_iff_le_induced, induced_compose] convert continuous_iff_le_induced.1 (s.ι.app j).hom.continuous exact hc.fac ((forget).mapCocone s) j end section IsColimit variable (c : Cocone F) (hc : IsColimit c) include hc theorem coinduced_of_isColimit : c.pt.str = ⨆ j, (F.obj j).str.coinduced (c.ι.app j) := by let c' := coconeOfCoconeForget ((forget).mapCocone c) let hc' : IsColimit c' := isColimitCoconeOfForget _ (isColimitOfPreserves forget hc) let e := IsColimit.coconePointUniqueUpToIso hc' hc have he (j : J) : c'.ι.app j ≫ e.hom = c.ι.app j := IsColimit.comp_coconePointUniqueUpToIso_hom hc' hc j apply (homeoOfIso e).coinduced_eq.symm.trans dsimp [coconeOfCoconeForget_pt, c', topologicalSpaceCoconePtOfCoconeForget] simp only [coinduced_iSup] conv_rhs => simp only [← he] rfl lemma isOpen_iff_of_isColimit (X : Set c.pt) : IsOpen X ↔ ∀ (j : J), IsOpen (c.ι.app j ⁻¹' X) := by trans (⨆ (j : J), (F.obj j).str.coinduced (c.ι.app j)).IsOpen X · rw [← coinduced_of_isColimit c hc, isOpen_fold] · simp only [← isOpen_coinduced] apply isOpen_iSup_iff lemma isClosed_iff_of_isColimit (X : Set c.pt) : IsClosed X ↔ ∀ (j : J), IsClosed (c.ι.app j ⁻¹' X) := by simp only [← isOpen_compl_iff, isOpen_iff_of_isColimit _ hc, Functor.const_obj_obj, Set.preimage_compl] lemma continuous_iff_of_isColimit {X : Type w} [TopologicalSpace X] (f : c.pt → X) : Continuous f ↔ ∀ (j : J), Continuous (f ∘ c.ι.app j) := by simp only [continuous_def, isOpen_iff_of_isColimit _ hc] tauto end IsColimit variable (F) theorem colimit_topology (F : J ⥤ TopCat.{u}) [HasColimit F] : (colimit F).str = ⨆ j, (F.obj j).str.coinduced (colimit.ι F j) := coinduced_of_isColimit _ (colimit.isColimit _) theorem colimit_isOpen_iff (F : J ⥤ TopCat.{u}) [HasColimit F] (U : Set ((colimit F : _) : Type u)) : IsOpen U ↔ ∀ j, IsOpen (colimit.ι F j ⁻¹' U) := by apply isOpen_iff_of_isColimit _ (colimit.isColimit _) lemma hasColimit_iff_small_colimitType : HasColimit F ↔ Small.{u} (F ⋙ forget).ColimitType := by rw [← Types.hasColimit_iff_small_colimitType] constructor <;> intro · infer_instance · exact ⟨⟨_, isColimitCoconeOfForget _ (colimit.isColimit _)⟩⟩ @[deprecated (since := "2025-04-01")] alias hasColimit_iff_small_quot := hasColimit_iff_small_colimitType instance topCat_hasColimitsOfShape (J : Type v) [Category J] [Small.{u} J] : HasColimitsOfShape J TopCat.{u} where has_colimit := fun F => by rw [hasColimit_iff_small_colimitType] infer_instance instance topCat_hasColimitsOfSize [UnivLE.{v, u}] : HasColimitsOfSize.{w, v} TopCat.{u} where instance topCat_hasColimits : HasColimits TopCat.{u} := TopCat.topCat_hasColimitsOfSize.{u, u} instance forget_preservesColimitsOfSize : PreservesColimitsOfSize.{w, v} (forget : TopCat.{u} ⥤ _) where instance forget_preservesColimits : PreservesColimits (forget : TopCat.{u} ⥤ Type u) where end Colimits /-- The terminal object of `Top` is `PUnit`. -/ def isTerminalPUnit : IsTerminal (TopCat.of PUnit.{u + 1}) := haveI : ∀ X, Unique (X ⟶ TopCat.of PUnit.{u + 1}) := fun X => ⟨⟨ofHom ⟨fun _ => PUnit.unit, continuous_const⟩⟩, fun f => by ext⟩ Limits.IsTerminal.ofUnique _ /-- The terminal object of `Top` is `PUnit`. -/ def terminalIsoPUnit : ⊤_ TopCat.{u} ≅ TopCat.of PUnit := terminalIsTerminal.uniqueUpToIso isTerminalPUnit /-- The initial object of `Top` is `PEmpty`. -/ def isInitialPEmpty : IsInitial (TopCat.of PEmpty.{u + 1}) := haveI : ∀ X, Unique (TopCat.of PEmpty.{u + 1} ⟶ X) := fun X => ⟨⟨ofHom ⟨fun x => x.elim, by continuity⟩⟩, fun f => by ext ⟨⟩⟩ Limits.IsInitial.ofUnique _ /-- The initial object of `Top` is `PEmpty`. -/ def initialIsoPEmpty : ⊥_ TopCat.{u} ≅ TopCat.of PEmpty := initialIsInitial.uniqueUpToIso isInitialPEmpty end TopCat
FunctionField.lean
/- Copyright (c) 2022 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import Mathlib.AlgebraicGeometry.Properties /-! # Function field of integral schemes We define the function field of an irreducible scheme as the stalk of the generic point. This is a field when the scheme is integral. ## Main definition * `AlgebraicGeometry.Scheme.functionField`: The function field of an integral scheme. * `AlgebraicGeometry.Scheme.germToFunctionField`: The canonical map from a component into the function field. This map is injective. -/ -- Explicit universe annotations were used in this file to improve performance https://github.com/leanprover-community/mathlib4/issues/12737 universe u v open TopologicalSpace Opposite CategoryTheory CategoryTheory.Limits TopCat namespace AlgebraicGeometry variable (X : Scheme) /-- The function field of an irreducible scheme is the local ring at its generic point. Despite the name, this is a field only when the scheme is integral. -/ noncomputable abbrev Scheme.functionField [IrreducibleSpace X] : CommRingCat := X.presheaf.stalk (genericPoint X) /-- The restriction map from a component to the function field. -/ noncomputable abbrev Scheme.germToFunctionField [IrreducibleSpace X] (U : X.Opens) [h : Nonempty U] : Γ(X, U) ⟶ X.functionField := X.presheaf.germ U (genericPoint X) (((genericPoint_spec X).mem_open_set_iff U.isOpen).mpr (by simpa using h)) noncomputable instance [IrreducibleSpace X] (U : X.Opens) [Nonempty U] : Algebra Γ(X, U) X.functionField := (X.germToFunctionField U).hom.toAlgebra noncomputable instance [IsIntegral X] : Field X.functionField := by refine .ofIsUnitOrEqZero fun a ↦ ?_ obtain ⟨U, m, s, rfl⟩ := TopCat.Presheaf.germ_exist _ _ a rw [or_iff_not_imp_right, ← (X.presheaf.germ _ _ m).hom.map_zero] intro ha replace ha := ne_of_apply_ne _ ha have hs : genericPoint X ∈ RingedSpace.basicOpen _ s := by rw [← SetLike.mem_coe, (genericPoint_spec X).mem_open_set_iff, Set.univ_inter, Set.nonempty_iff_ne_empty, Ne, ← Opens.coe_bot, ← SetLike.ext'_iff] · erw [basicOpen_eq_bot_iff] exact ha · exact (RingedSpace.basicOpen _ _).isOpen have := (X.presheaf.germ _ _ hs).hom.isUnit_map (RingedSpace.isUnit_res_basicOpen _ s) rwa [Presheaf.germ_res_apply] at this theorem germ_injective_of_isIntegral [IsIntegral X] {U : X.Opens} (x : X) (hx : x ∈ U) : Function.Injective (X.presheaf.germ U x hx) := by rw [injective_iff_map_eq_zero] intro y hy rw [← (X.presheaf.germ U x hx).hom.map_zero] at hy obtain ⟨W, hW, iU, iV, e⟩ := X.presheaf.germ_eq _ hx hx _ _ hy cases Subsingleton.elim iU iV haveI : Nonempty W := ⟨⟨_, hW⟩⟩ exact map_injective_of_isIntegral X iU e theorem Scheme.germToFunctionField_injective [IsIntegral X] (U : X.Opens) [Nonempty U] : Function.Injective (X.germToFunctionField U) := germ_injective_of_isIntegral _ _ _ theorem genericPoint_eq_of_isOpenImmersion {X Y : Scheme} (f : X ⟶ Y) [H : IsOpenImmersion f] [hX : IrreducibleSpace X] [IrreducibleSpace Y] : f.base (genericPoint X) = genericPoint Y := by apply ((genericPoint_spec Y).eq _).symm convert (genericPoint_spec X).image (show Continuous f.base by fun_prop) symm rw [← Set.univ_subset_iff] convert subset_closure_inter_of_isPreirreducible_of_isOpen _ H.base_open.isOpen_range _ · rw [Set.univ_inter, Set.image_univ] · apply PreirreducibleSpace.isPreirreducible_univ (X := Y) · exact ⟨_, trivial, Set.mem_range_self hX.2.some⟩ noncomputable instance stalkFunctionFieldAlgebra [IrreducibleSpace X] (x : X) : Algebra (X.presheaf.stalk x) X.functionField := by -- TODO: can we write this normally after the refactor finishes? apply RingHom.toAlgebra exact (X.presheaf.stalkSpecializes ((genericPoint_spec X).specializes trivial)).hom instance functionField_isScalarTower [IrreducibleSpace X] (U : X.Opens) (x : U) [Nonempty U] : IsScalarTower Γ(X, U) (X.presheaf.stalk x) X.functionField := by apply IsScalarTower.of_algebraMap_eq' simp_rw [RingHom.algebraMap_toAlgebra] change _ = (X.presheaf.germ U x x.2 ≫ _).hom rw [X.presheaf.germ_stalkSpecializes] noncomputable instance (R : CommRingCat.{u}) [IsDomain R] : Algebra R (Spec R).functionField := -- TODO: can we write this normally after the refactor finishes? RingHom.toAlgebra <| by apply CommRingCat.Hom.hom; apply StructureSheaf.toStalk @[simp] theorem genericPoint_eq_bot_of_affine (R : CommRingCat) [IsDomain R] : genericPoint (Spec R) = (⊥ : PrimeSpectrum R) := by apply (genericPoint_spec (Spec R)).eq rw [isGenericPoint_def] rw [← PrimeSpectrum.zeroLocus_vanishingIdeal_eq_closure, PrimeSpectrum.vanishingIdeal_singleton] rw [← PrimeSpectrum.zeroLocus_singleton_zero] rfl instance functionField_isFractionRing_of_affine (R : CommRingCat.{u}) [IsDomain R] : IsFractionRing R (Spec R).functionField := by convert StructureSheaf.IsLocalization.to_stalk R (genericPoint (Spec R)) delta IsFractionRing IsLocalization.AtPrime -- Porting note: `congr` does not work for `Iff` apply Eq.to_iff congr 1 rw [genericPoint_eq_bot_of_affine] ext exact mem_nonZeroDivisors_iff_ne_zero instance {X : Scheme} [IsIntegral X] {U : X.Opens} [Nonempty U] : IsIntegral U := isIntegral_of_isOpenImmersion U.ι theorem IsAffineOpen.primeIdealOf_genericPoint {X : Scheme} [IsIntegral X] {U : X.Opens} (hU : IsAffineOpen U) [h : Nonempty U] : hU.primeIdealOf ⟨genericPoint X, ((genericPoint_spec X).mem_open_set_iff U.isOpen).mpr (by simpa using h)⟩ = genericPoint (Spec Γ(X, U)) := by haveI : IsAffine _ := hU delta IsAffineOpen.primeIdealOf convert genericPoint_eq_of_isOpenImmersion (U.toScheme.isoSpec.hom ≫ Spec.map (X.presheaf.map (eqToHom U.isOpenEmbedding_obj_top).op)) -- Porting note: this was `ext1` apply Subtype.ext exact (genericPoint_eq_of_isOpenImmersion U.ι).symm theorem functionField_isFractionRing_of_isAffineOpen [IsIntegral X] (U : X.Opens) (hU : IsAffineOpen U) [Nonempty U] : IsFractionRing Γ(X, U) X.functionField := by haveI : IsAffine _ := hU haveI : IsIntegral U := @isIntegral_of_isAffine_of_isDomain _ _ _ (by rw [Scheme.Opens.toScheme_presheaf_obj, Opens.isOpenEmbedding_obj_top]; infer_instance) delta IsFractionRing Scheme.functionField convert hU.isLocalization_stalk ⟨genericPoint X, (((genericPoint_spec X).mem_open_set_iff U.isOpen).mpr (by simpa using ‹Nonempty U›))⟩ using 1 rw [hU.primeIdealOf_genericPoint, genericPoint_eq_bot_of_affine] ext; exact mem_nonZeroDivisors_iff_ne_zero instance (x : X) : IsAffine (X.affineCover.obj x) := AlgebraicGeometry.isAffine_Spec _ instance [IsIntegral X] (x : X) : IsFractionRing (X.presheaf.stalk x) X.functionField := let U : X.Opens := (X.affineCover.map x).opensRange have hU : IsAffineOpen U := isAffineOpen_opensRange (X.affineCover.map x) let x : U := ⟨x, X.affineCover.covers x⟩ have : Nonempty U := ⟨x⟩ let M := (hU.primeIdealOf x).asIdeal.primeCompl have := hU.isLocalization_stalk x have := functionField_isFractionRing_of_isAffineOpen X U hU -- Porting note: the following two lines were not needed. let _hA := Presheaf.algebra_section_stalk X.presheaf x have := functionField_isScalarTower X U x .isFractionRing_of_isDomain_of_isLocalization M ↑(Presheaf.stalk X.presheaf x) (Scheme.functionField X) instance [IsIntegral X] {x : X} : IsDomain (X.presheaf.stalk x) := Function.Injective.isDomain _ (IsFractionRing.injective (X.presheaf.stalk x) (X.functionField)) end AlgebraicGeometry
algnum.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq path. From mathcomp Require Import div choice fintype tuple finfun bigop prime. From mathcomp Require Import ssralg poly polydiv ssrnum ssrint archimedean rat. From mathcomp Require Import finalg zmodp matrix mxalgebra mxpoly vector intdiv. From mathcomp Require Import falgebra fieldext separable galois algC cyclotomic. (******************************************************************************) (* This file provides a few basic results and constructions in algebraic *) (* number theory, that are used in the character theory library. Most of *) (* these could be generalized to a more abstract setting. Note that the type *) (* of abstract number fields is simply extFieldType rat. We define here: *) (* x \in Crat_span X <=> x is a Q-linear combination of elements of *) (* X : seq algC. *) (* x \in Cint_span X <=> x is a Z-linear combination of elements of *) (* X : seq algC. *) (* x \in Aint <=> x : algC is an algebraic integer, i.e., the (monic) *) (* polynomial of x over Q has integer coefficients. *) (* (e %| a)%A <=> e divides a with respect to algebraic integers, *) (* (e %| a)%Ax i.e., a is in the algebraic integer ideal generated *) (* by e. This is is notation for a \in dvdA e, where *) (* dvdv is the (collective) predicate for the Aint *) (* ideal generated by e. As in the (e %| a)%C notation *) (* e and a can be coerced to algC from nat or int. *) (* The (e %| a)%Ax display form is a workaround for *) (* design limitations of the Coq Notation facilities. *) (* (a == b %[mod e])%A, (a != b %[mod e])%A <=> *) (* a is equal (resp. not equal) to b mod e, i.e., a and *) (* b belong to the same e * Aint class. We do not *) (* force a, b and e to be algebraic integers. *) (* #[x]%C == the multiplicative order of x, i.e., the n such that *) (* x is an nth primitive root of unity, or 0 if x is not *) (* a root of unity. *) (* In addition several lemmas prove the (constructive) existence of number *) (* fields and of automorphisms of algC. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope algC_scope. Declare Scope algC_expanded_scope. Import GRing.Theory Num.Theory. Local Open Scope ring_scope. Local Notation ZtoQ := (intr : int -> rat). Local Notation ZtoC := (intr : int -> algC). Local Notation QtoC := (ratr : rat -> algC). Local Notation intrp := (map_poly intr). Local Notation pZtoQ := (map_poly ZtoQ). Local Notation pZtoC := (map_poly ZtoC). Local Notation pQtoC := (map_poly ratr). Local Definition intr_inj_ZtoC := (intr_inj : injective ZtoC). #[local] Hint Resolve intr_inj_ZtoC : core. Section MoreAlgCaut. Implicit Type rR : unitRingType. Lemma alg_num_field (Qz : fieldExtType rat) a : a%:A = ratr a :> Qz. Proof. by rewrite -in_algE fmorph_eq_rat. Qed. Lemma rmorphZ_num (Qz : fieldExtType rat) rR (f : {rmorphism Qz -> rR}) a x : f (a *: x) = ratr a * f x. Proof. by rewrite -mulr_algl rmorphM alg_num_field fmorph_rat. Qed. Lemma fmorph_numZ (Qz1 Qz2 : fieldExtType rat) (f : {rmorphism Qz1 -> Qz2}) : scalable f. Proof. by move=> a x; rewrite rmorphZ_num -alg_num_field mulr_algl. Qed. End MoreAlgCaut. (* Number fields and rational spans. *) Lemma algC_PET (s : seq algC) : {z | exists a : nat ^ size s, z = \sum_(i < size s) s`_i *+ a i & exists ps, s = [seq (pQtoC p).[z] | p <- ps]}. Proof. elim: s => [|x s [z /sig_eqW[a Dz] /sig_eqW[ps Ds]]]. by exists 0; [exists [ffun _ => 2%N]; rewrite big_ord0 | exists nil]. have r_exists (y : algC): {r | r != 0 & root (pQtoC r) y}. have [r [_ mon_r] dv_r] := minCpolyP y. by exists r; rewrite ?monic_neq0 ?dv_r. suffices /sig_eqW[[n [|px [|pz []]]]// [Dpx Dpz]]: exists np, let zn := x *+ np.1 + z in [:: x; z] = [seq (pQtoC p).[zn] | p <- np.2]. - exists (x *+ n + z). exists [ffun i => oapp a n (unlift ord0 i)]. rewrite /= big_ord_recl ffunE unlift_none Dz; congr (_ + _). by apply: eq_bigr => i _; rewrite ffunE liftK. exists (px :: [seq p \Po pz | p <- ps]); rewrite /= -Dpx; congr (_ :: _). rewrite -map_comp Ds; apply: eq_map => p /=. by rewrite map_comp_poly horner_comp -Dpz. have [rx nz_rx rx0] := r_exists x. have [rz nz_rz rz0] := r_exists (- z). have pchar0_Q: [pchar rat] =i pred0 by apply: pchar_num. have [n [[pz Dpz] [px Dpx]]] := pchar0_PET nz_rz rz0 nz_rx rx0 pchar0_Q. by exists (n, [:: px; - pz]); rewrite /= !raddfN hornerN -[z]opprK Dpz Dpx. Qed. Lemma num_field_exists (s : seq algC) : {Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC} & {s1 : seq Qs | map QsC s1 = s & <<1 & s1>>%VS = fullv}}}. Proof. have [z /sig_eqW[a Dz] /sig_eqW[ps Ds]] := algC_PET s. suffices [Qs [QsC [z1 z1C z1gen]]]: {Qs : fieldExtType rat & {QsC : {rmorphism Qs -> algC} & {z1 : Qs | QsC z1 = z & forall xx, exists p, fieldExt_horner z1 p = xx}}}. - set inQs := fieldExt_horner z1 in z1gen *; pose s1 := map inQs ps. have inQsK p: QsC (inQs p) = (pQtoC p).[z]. rewrite /= -horner_map z1C -map_poly_comp; congr _.[z]. by apply: eq_map_poly => b /=; rewrite alg_num_field fmorph_rat. exists Qs, QsC, s1; first by rewrite -map_comp Ds (eq_map inQsK). have sz_ps: size ps = size s by rewrite Ds size_map. apply/vspaceP=> x; rewrite memvf; have [p {x}<-] := z1gen x. elim/poly_ind: p => [|p b ApQs]; first by rewrite /inQs rmorph0 mem0v. rewrite /inQs rmorphD rmorphM /= fieldExt_hornerX fieldExt_hornerC -/inQs /=. suffices ->: z1 = \sum_(i < size s) s1`_i *+ a i. rewrite memvD ?memvZ ?mem1v ?memvM ?memv_suml // => i _. by rewrite rpredMn ?seqv_sub_adjoin ?mem_nth // size_map sz_ps. apply: (fmorph_inj QsC); rewrite z1C Dz rmorph_sum; apply: eq_bigr => i _. by rewrite rmorphMn {1}Ds !(nth_map 0) ?sz_ps //= inQsK. have [r [Dr /monic_neq0 nz_r] dv_r] := minCpolyP z. have rz0: root (pQtoC r) z by rewrite dv_r. have irr_r: irreducible_poly r. by apply/(subfx_irreducibleP rz0 nz_r)=> q qz0 nzq; rewrite dvdp_leq // -dv_r. exists (SubFieldExtType rz0 irr_r), (@subfx_inj _ _ QtoC z r). exists (subfx_root _ z r) => [|x]; first exact: subfx_inj_root. by have{x} [p ->] := subfxEroot rz0 nz_r x; exists p. Qed. Definition in_Crat_span s x := exists a : rat ^ size s, x = \sum_i QtoC (a i) * s`_i. Fact Crat_span_subproof s x : decidable (in_Crat_span s x). Proof. have [Qxs [QxsC [[|x1 s1] // [<- <-] {x s} _]]] := num_field_exists (x :: s). apply: decP (x1 \in <<in_tuple s1>>%VS) _; rewrite /in_Crat_span size_map. apply: (iffP idP) => [/coord_span-> | [a Dx]]. move: (coord _) => a; exists [ffun i => a i x1]; rewrite rmorph_sum /=. by apply: eq_bigr => i _; rewrite ffunE rmorphZ_num (nth_map 0). have{Dx} ->: x1 = \sum_i a i *: s1`_i. apply: (fmorph_inj QxsC); rewrite Dx rmorph_sum /=. by apply: eq_bigr => i _; rewrite rmorphZ_num (nth_map 0). by apply: memv_suml => i _; rewrite memvZ ?memv_span ?mem_nth. Qed. Definition Crat_span s : pred algC := Crat_span_subproof s. Lemma Crat_spanP s x : reflect (in_Crat_span s x) (x \in Crat_span s). Proof. exact: sumboolP. Qed. Lemma mem_Crat_span s : {subset s <= Crat_span s}. Proof. move=> _ /(nthP 0)[ix ltxs <-]; pose i0 := Ordinal ltxs. apply/Crat_spanP; exists [ffun i => (i == i0)%:R]. rewrite (bigD1_ord i0) //= ffunE eqxx // rmorph1 mul1r. by rewrite big1 ?addr0 // => i; rewrite ffunE rmorph_nat mulr_natl lift_eqF. Qed. Fact Crat_span_zmod_closed s : zmod_closed (Crat_span s). Proof. split=> [|_ _ /Crat_spanP[x ->] /Crat_spanP[y ->]]. apply/Crat_spanP; exists 0. by apply/esym/big1=> i _; rewrite ffunE rmorph0 mul0r. apply/Crat_spanP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _. by rewrite -mulrBl -rmorphB !ffunE. Qed. HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Crat_span s) (Crat_span_zmod_closed s). Section NumFieldProj. Variables (Qn : fieldExtType rat) (QnC : {rmorphism Qn -> algC}). Lemma Crat_spanZ b a : {in Crat_span b, forall x, ratr a * x \in Crat_span b}. Proof. move=> _ /Crat_spanP[a1 ->]; apply/Crat_spanP; exists [ffun i => a * a1 i]. by rewrite mulr_sumr; apply: eq_bigr => i _; rewrite ffunE mulrA -rmorphM. Qed. Lemma Crat_spanM b : {in Crat & Crat_span b, forall a x, a * x \in Crat_span b}. Proof. by move=> _ x /CratP[a ->]; apply: Crat_spanZ. Qed. (* In principle CtoQn could be taken to be additive and Q-linear, but this *) (* would require a limit construction. *) Lemma num_field_proj : {CtoQn | CtoQn 0 = 0 & cancel QnC CtoQn}. Proof. pose b := vbasis {:Qn}. have Qn_bC (u : {x | x \in Crat_span (map QnC b)}): {y | QnC y = sval u}. case: u => _ /= /Crat_spanP/sig_eqW[a ->]. exists (\sum_i a i *: b`_i); rewrite rmorph_sum /=; apply: eq_bigr => i _. by rewrite rmorphZ_num (nth_map 0) // -(size_map QnC). pose CtoQn x := oapp (fun u => sval (Qn_bC u)) 0 (insub x). suffices QnCK: cancel QnC CtoQn by exists CtoQn; rewrite // -(rmorph0 QnC) /=. move=> x; rewrite /CtoQn insubT => /= [|Qn_x]; last first. by case: (Qn_bC _) => x1 /= /fmorph_inj. rewrite (coord_vbasis (memvf x)) rmorph_sum rpred_sum //= => i _. rewrite rmorphZ_num Crat_spanZ ?mem_Crat_span // -/b. by rewrite -tnth_nth -tnth_map mem_tnth. Qed. Lemma restrict_aut_to_num_field (nu : {rmorphism algC -> algC}) : (forall x, exists y, nu (QnC x) = QnC y) -> {nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}. Proof. move=> Qn_nu; pose nu0 x := sval (sig_eqW (Qn_nu x)). have QnC_nu0: {morph QnC : x / nu0 x >-> nu x}. by rewrite /nu0 => x; case: (sig_eqW _). have nu0a : zmod_morphism nu0. by move=> x y; apply: (fmorph_inj QnC); rewrite !(QnC_nu0, rmorphB). have nu0m : monoid_morphism nu0. split=> [|x y]; apply: (fmorph_inj QnC); rewrite ?QnC_nu0 ?rmorph1 //. by rewrite !rmorphM /= !QnC_nu0. pose nu0aM := GRing.isZmodMorphism.Build Qn Qn nu0 nu0a. pose nu0mM := GRing.isMonoidMorphism.Build Qn Qn nu0 nu0m. pose nu0RM : {rmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM. pose nu0lM := GRing.isScalable.Build rat Qn Qn *:%R nu0 (fmorph_numZ nu0RM). pose nu0LRM : {lrmorphism _ -> _} := HB.pack nu0 nu0aM nu0mM nu0lM. by exists nu0LRM. Qed. Lemma map_Qnum_poly (nu : {rmorphism algC -> algC}) p : p \in polyOver 1%VS -> map_poly (nu \o QnC) p = (map_poly QnC p). Proof. move=> Qp; apply/polyP=> i; rewrite /= !coef_map /=. have /vlineP[a ->]: p`_i \in 1%VS by apply: polyOverP. by rewrite alg_num_field !fmorph_rat. Qed. End NumFieldProj. Lemma restrict_aut_to_normal_num_field (Qn : splittingFieldType rat) (QnC : {rmorphism Qn -> algC})(nu : {rmorphism algC -> algC}) : {nu0 : {lrmorphism Qn -> Qn} | {morph QnC : x / nu0 x >-> nu x}}. Proof. apply: restrict_aut_to_num_field => x. case: (splitting_field_normal 1%AS x) => rs /eqP Hrs. have: root (map_poly (nu \o QnC) (minPoly 1%AS x)) (nu (QnC x)). by rewrite fmorph_root root_minPoly. rewrite map_Qnum_poly ?minPolyOver // Hrs. rewrite [map_poly _ _](_:_ = \prod_(y <- map QnC rs) ('X - y%:P)). by rewrite root_prod_XsubC; case/mapP => y _ ?; exists y. by rewrite big_map rmorph_prod /=; apply: eq_bigr => i _; rewrite map_polyXsubC. Qed. (* Integral spans. *) Lemma dec_Cint_span (V : vectType algC) m (s : m.-tuple V) v : decidable (inIntSpan s v). Proof. have s_s (i : 'I_m): s`_i \in <<s>>%VS by rewrite memv_span ?memt_nth. have s_Zs a: \sum_(i < m) s`_i *~ a i \in <<s>>%VS. by rewrite memv_suml // => i _; rewrite -scaler_int memvZ. case s_v: (v \in <<s>>%VS); last by right=> [[a Dv]]; rewrite Dv s_Zs in s_v. pose IzT := {: 'I_m * 'I_(\dim <<s>>)}; pose Iz := 'I_#|IzT|. pose b := vbasis <<s>>. pose z_s := [seq coord b ij.2 (tnth s ij.1) | ij : IzT]. pose rank2 j i: Iz := enum_rank (i, j); pose val21 (p : Iz) := (enum_val p).1. pose inQzs w := [forall j, Crat_span z_s (coord b j w)]. have enum_pairK j: {in predT, cancel (rank2 j) val21}. by move=> i; rewrite /val21 enum_rankK. have Qz_Zs a: inQzs (\sum_(i < m) s`_i *~ a i). apply/forallP=> j; apply/Crat_spanP; rewrite /in_Crat_span size_map -cardE. exists [ffun ij => (a (val21 ij))%:Q *+ ((enum_val ij).2 == j)]. rewrite linear_sum {1}(reindex_onto _ _ (enum_pairK j)) big_mkcond /=. apply: eq_bigr => ij _ /=; rewrite nth_image (tnth_nth 0) ffunE /val21. rewrite raddfMz rmorphMn rmorph_int mulrnAl mulrzl /=. rewrite (can2_eq (@enum_rankK _) (@enum_valK _)). by case: (enum_val ij) => i j1; rewrite xpair_eqE eqxx; have [->|] := eqVneq. case Qz_v: (inQzs v); last by right=> [[a Dv]]; rewrite Dv Qz_Zs in Qz_v. have [Qz [QzC [z1s Dz_s _]]] := num_field_exists z_s. have sz_z1s: size z1s = #|IzT| by rewrite -(size_map QzC) Dz_s size_map cardE. have xv j: {x | coord b j v = QzC x}. apply: sig_eqW; have /Crat_spanP[x ->] := forallP Qz_v j. exists (\sum_ij x ij *: z1s`_ij); rewrite rmorph_sum; apply: eq_bigr => ij _. by rewrite rmorphZ_num -[in RHS](nth_map _ 0) ?Dz_s // -(size_map QzC) Dz_s. pose sz := [tuple [ffun j => z1s`_(rank2 j i)] | i < m]. have [Zsv | Zs'v] := dec_Qint_span sz [ffun j => sval (xv j)]. left; have{Zsv} [a Dv] := Zsv; exists a. transitivity (\sum_j \sum_(i < m) QzC ((sz`_i *~ a i) j) *: b`_j). rewrite {1}(coord_vbasis s_v) -/b; apply: eq_bigr => j _. rewrite -scaler_suml; congr (_ *: _). have{Dv} /ffunP/(_ j) := Dv; rewrite sum_ffunE !ffunE -rmorph_sum => <-. by case: (xv j). rewrite exchange_big; apply: eq_bigr => i _. rewrite (coord_vbasis (s_s i)) -/b mulrz_suml; apply: eq_bigr => j _. rewrite scalerMzl ffunMzE rmorphMz; congr ((_ *~ _) *: _). rewrite nth_mktuple ffunE -(nth_map _ 0) ?sz_z1s // Dz_s. by rewrite nth_image enum_rankK /= (tnth_nth 0). right=> [[a Dv]]; case: Zs'v; exists a. apply/ffunP=> j; rewrite sum_ffunE !ffunE; apply: (fmorph_inj QzC). case: (xv j) => /= _ <-; rewrite Dv linear_sum rmorph_sum /=. apply: eq_bigr => i _; rewrite nth_mktuple raddfMz !ffunMzE rmorphMz ffunE. by rewrite -(nth_map _ 0 QzC) ?sz_z1s // Dz_s nth_image enum_rankK -tnth_nth. Qed. Definition Cint_span (s : seq algC) : pred algC := fun x => dec_Cint_span (in_tuple [seq \row_(i < 1) y | y <- s]) (\row_i x). Lemma Cint_spanP n (s : n.-tuple algC) x : reflect (inIntSpan s x) (x \in Cint_span s). Proof. rewrite unfold_in; case: (dec_Cint_span _ _) => [Zs_x | Zs'x] /=. left; have{Zs_x} [] := Zs_x; rewrite /= size_map size_tuple => a /rowP/(_ 0). rewrite !mxE => ->; exists a; rewrite summxE; apply: eq_bigr => i _. by rewrite -scaler_int (nth_map 0) ?size_tuple // !mxE mulrzl. right=> [[a Dx]]; have{Zs'x} [] := Zs'x. rewrite /inIntSpan /= size_map size_tuple; exists a. apply/rowP=> i0; rewrite !mxE summxE Dx; apply: eq_bigr => i _. by rewrite -scaler_int mxE mulrzl (nth_map 0) ?size_tuple // !mxE. Qed. Lemma mem_Cint_span s : {subset s <= Cint_span s}. Proof. move=> _ /(nthP 0)[ix ltxs <-]; apply/(Cint_spanP (in_tuple s)). exists [ffun i => i == Ordinal ltxs : int]. rewrite (bigD1 (Ordinal ltxs)) //= ffunE eqxx. by rewrite big1 ?addr0 // => i; rewrite ffunE => /negbTE->. Qed. Lemma Cint_span_zmod_closed s : zmod_closed (Cint_span s). Proof. have sP := Cint_spanP (in_tuple s); split=> [|_ _ /sP[x ->] /sP[y ->]]. by apply/sP; exists 0; rewrite big1 // => i; rewrite ffunE. apply/sP; exists (x - y); rewrite -sumrB; apply: eq_bigr => i _. by rewrite !ffunE raddfB. Qed. HB.instance Definition _ s := GRing.isZmodClosed.Build _ (Cint_span s) (Cint_span_zmod_closed s). (* Automorphism extensions. *) Lemma extend_algC_subfield_aut (Qs : fieldExtType rat) (QsC : {rmorphism Qs -> algC}) (phi : {rmorphism Qs -> Qs}) : {nu : {rmorphism algC -> algC} | {morph QsC : x / phi x >-> nu x}}. Proof. pose numF_inj (Qr : fieldExtType rat) := {rmorphism Qr -> algC}. pose subAut := {Qr : _ & numF_inj Qr * {lrmorphism Qr -> Qr}}%type. pose SubAut := existT _ _ (_, _) : subAut. pose Sdom (mu : subAut) := projT1 mu. pose Sinj (mu : subAut) : {rmorphism Sdom mu -> algC} := (projT2 mu).1. pose Saut (mu : subAut) : {rmorphism Sdom mu -> Sdom mu} := (projT2 mu).2. have Sinj_poly Qr (QrC : numF_inj Qr) p: map_poly QrC (map_poly (in_alg Qr) p) = pQtoC p. - rewrite -map_poly_comp; apply: eq_map_poly => a. by rewrite /= rmorphZ_num rmorph1 mulr1. have ext1 mu0 x : {mu1 | exists y, x = Sinj mu1 y & exists2 in01 : {lrmorphism _ -> _}, Sinj mu0 =1 Sinj mu1 \o in01 & {morph in01: y / Saut mu0 y >-> Saut mu1 y}}. - pose b0 := vbasis {:Sdom mu0}. have [z _ /sig_eqW[[|px ps] // [Dx Ds]]] := algC_PET (x :: map (Sinj mu0) b0). have [p [_ mon_p] /(_ p) pz0] := minCpolyP z; rewrite dvdpp in pz0. have [r Dr] := closed_field_poly_normal (pQtoC p : {poly algC}). rewrite lead_coef_map {mon_p}(monicP mon_p) rmorph1 scale1r in Dr. have{pz0} rz: z \in r by rewrite -root_prod_XsubC -Dr. have [Qr [QrC [rr Drr genQr]]] := num_field_exists r. have{rz} [zz Dz]: {zz | QrC zz = z}. by move: rz; rewrite -Drr => /mapP/sig2_eqW[zz]; exists zz. have{ps Ds} [in01 Din01]: {in01 : {lrmorphism _ -> _} | Sinj mu0 =1 QrC \o in01}. have in01P y: {yy | Sinj mu0 y = QrC yy}. exists (\sum_i coord b0 i y *: (map_poly (in_alg Qr) ps`_i).[zz]). rewrite {1}(coord_vbasis (memvf y)) !rmorph_sum /=; apply: eq_bigr => i _. rewrite 2!rmorphZ_num -(nth_map _ 0) ?size_tuple // Ds. rewrite -horner_map Dz Sinj_poly (nth_map 0) //. by have:= congr1 size Ds; rewrite !size_map size_tuple => <-. pose in01 y := sval (in01P y). have Din01 y: Sinj mu0 y = QrC (in01 y) by rewrite /in01; case: (in01P y). pose rwM := (=^~ Din01, rmorphZ_num, rmorph1, rmorphB, rmorphM). have in01a : zmod_morphism in01. by move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM. have in01m : monoid_morphism in01. by split; try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM /= ?rwM. have in01l : scalable in01. by try move=> ? ?; apply: (fmorph_inj QrC); rewrite !rwM. pose in01aM := GRing.isZmodMorphism.Build _ _ in01 in01a. pose in01mM := GRing.isMonoidMorphism.Build _ _ in01 in01m. pose in01lM := GRing.isScalable.Build _ _ _ _ in01 in01l. pose in01LRM : {lrmorphism _ -> _} := HB.pack in01 in01aM in01mM in01lM. by exists in01LRM. have {z zz Dz px} Dx: exists xx, x = QrC xx. exists (map_poly (in_alg Qr) px).[zz]. by rewrite -horner_map Dz Sinj_poly Dx. pose lin01 := linfun in01; pose K := (lin01 @: fullv)%VS. have memK y: reflect (exists yy, y = in01 yy) (y \in K). apply: (iffP memv_imgP) => [[yy _ ->] | [yy ->]]; by exists yy; rewrite ?lfunE ?memvf. have algK: is_aspace K. rewrite /is_aspace has_algid1; last first. by apply/memK; exists 1; rewrite rmorph1. apply/prodvP=> _ _ /memK[y1 ->] /memK[y2 ->]. by apply/memK; exists (y1 * y2); rewrite rmorphM. have ker_in01: lker lin01 == 0%VS. by apply/lker0P=> y1 y2; rewrite !lfunE; apply: fmorph_inj. pose f := (lin01 \o linfun (Saut mu0) \o lin01^-1)%VF. have Df y: f (in01 y) = in01 (Saut mu0 y). transitivity (f (lin01 y)); first by rewrite !lfunE. by do 4!rewrite lfunE /=; rewrite lker0_lfunK. have hom_f: kHom 1 (ASpace algK) f. apply/kHomP_tmp; split=> [_ /vlineP[a ->] | _ _ /memK[y1 ->] /memK[y2 ->]]. by rewrite -(rmorph_alg in01) Df /= !rmorph_alg. by rewrite -rmorphM !Df !rmorphM. pose pr := map_poly (in_alg Qr) p. have Qpr: pr \is a polyOver 1%VS. by apply/polyOverP=> i; rewrite coef_map memvZ ?memv_line. have splitQr: splittingFieldFor K pr fullv. apply: splittingFieldForS (sub1v (Sub K algK)) (subvf _) _; exists rr => //. congr (_ %= _): (eqpxx pr); apply/(map_poly_inj QrC). rewrite Sinj_poly Dr -Drr big_map rmorph_prod /=; apply: eq_bigr => zz _. by rewrite map_polyXsubC. have [f1 aut_f1 Df1]:= kHom_extends (sub1v (ASpace algK)) hom_f Qpr splitQr. pose f1mM := GRing.isMonoidMorphism.Build _ _ f1 (kHom_monoid_morphism aut_f1). pose nu : {lrmorphism _ -> _} := HB.pack (fun_of_lfun f1) f1mM. exists (SubAut Qr QrC nu) => //; exists in01 => //= y. by rewrite -Df -Df1 //; apply/memK; exists y. have phiZ: scalable phi. by move=> a y; rewrite rmorphZ_num -alg_num_field mulr_algl. pose philM := GRing.isScalable.Build _ _ _ _ phi phiZ. pose phiLRM : {lrmorphism _ -> _} := HB.pack (GRing.RMorphism.sort phi) philM. pose fix ext n := if n is i.+1 then oapp (fun x => s2val (ext1 (ext i) x)) (ext i) (unpickle i) else SubAut Qs QsC phiLRM. have mem_ext x n: (pickle x < n)%N -> {xx | Sinj (ext n) xx = x}. move=> ltxn; apply: sig_eqW; elim: n ltxn => // n IHn. rewrite ltnS leq_eqVlt => /predU1P[<- | /IHn[xx <-]] /=. by rewrite pickleK /=; case: (ext1 _ x) => mu [xx]; exists xx. case: (unpickle n) => /= [y|]; last by exists xx. case: (ext1 _ y) => mu /= _ [in_mu inj_in_mu _]. by exists (in_mu xx); rewrite inj_in_mu. pose nu x := Sinj _ (Saut _ (sval (mem_ext x _ (ltnSn _)))). have nu_inj n y: nu (Sinj (ext n) y) = Sinj (ext n) (Saut (ext n) y). rewrite /nu; case: (mem_ext _ _ _); move: _.+1 => n1 y1 Dy /=. without loss /subnK Dn1: n n1 y y1 Dy / (n <= n1)%N. by move=> IH; case/orP: (leq_total n n1) => /IH => [/(_ y) | /(_ y1)]->. move: (n1 - n)%N => k in Dn1; elim: k => [|k IHk] in n Dn1 y Dy *. by move: y1 Dy; rewrite -Dn1 => y1 /fmorph_inj ->. rewrite addSnnS in Dn1; move/IHk: Dn1 => /=. case: (unpickle _) => [z|] /=; last exact. case: (ext1 _ _) => mu /= _ [in_mu Dinj Daut]. by rewrite Dy => /(_ _ (Dinj _))->; rewrite -Daut Dinj. pose le_nu (x : algC) n := (pickle x < n)%N. have max3 x1 x2 x3: exists n, [/\ le_nu x1 n, le_nu x2 n & le_nu x3 n]. exists (maxn (pickle x1) (maxn (pickle x2) (pickle x3))).+1. by apply/and3P; rewrite /le_nu !ltnS -!geq_max. have nua : zmod_morphism nu. move=> x1 x2; have [n] := max3 (x1 - x2) x1 x2. case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2]. rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphB in Dx. by rewrite (fmorph_inj _ Dx) !rmorphB -!nu_inj Dx1 Dx2. have num : monoid_morphism nu. split=> [|x1 x2]; first by rewrite -(rmorph1 QsC) (nu_inj 0) !rmorph1. have [n] := max3 (x1 * x2) x1 x2. case=> /mem_ext[y Dx] /mem_ext[y1 Dx1] /mem_ext[y2 Dx2]. rewrite -Dx nu_inj; rewrite -Dx1 -Dx2 -rmorphM in Dx. by rewrite (fmorph_inj _ Dx) !rmorphM /= -!nu_inj Dx1 Dx2. pose nuaM := GRing.isZmodMorphism.Build _ _ nu nua. pose numM := GRing.isMonoidMorphism.Build _ _ nu num. pose nuRM : {rmorphism _ -> _} := HB.pack nu nuaM numM. by exists nuRM => x; rewrite /= (nu_inj 0). Qed. (* Extended automorphisms of Q_n. *) Lemma Qn_aut_exists k n : coprime k n -> {u : {rmorphism algC -> algC} | forall z, z ^+ n = 1 -> u z = z ^+ k}. Proof. have [-> /eqnP | n_gt0 co_k_n] := posnP n. by rewrite gcdn0 => ->; exists idfun. have [z prim_z] := C_prim_root_exists n_gt0. have [Qn [QnC [[|zn []] // [Dz]]] genQn] := num_field_exists [:: z]. pose phi := kHomExtend 1 \1 zn (zn ^+ k). have homQn1: kHom 1 1 (\1%VF : 'End(Qn)) by rewrite kHom1. have pzn_zk0: root (map_poly \1%VF (minPoly 1 zn)) (zn ^+ k). rewrite -(fmorph_root QnC) rmorphXn /= Dz -map_poly_comp. rewrite (@eq_map_poly _ _ _ QnC) => [|a]; last by rewrite /= id_lfunE. set p1 := map_poly _ _. have [q1 Dp1]: exists q1, p1 = pQtoC q1. have aP i: (minPoly 1 zn)`_i \in 1%VS. by apply/polyOverP; apply: minPolyOver. have{aP} a_ i := sig_eqW (vlineP _ _ (aP i)). exists (\poly_(i < size (minPoly 1 zn)) sval (a_ i)). apply/polyP=> i; rewrite coef_poly coef_map coef_poly /=. case: ifP => _; rewrite ?rmorph0 //; case: (a_ i) => a /= ->. by rewrite alg_num_field fmorph_rat. have: root p1 z by rewrite -Dz fmorph_root root_minPoly. rewrite Dp1; have [q2 [Dq2 _] ->] := minCpolyP z. case/dvdpP=> r1 ->; rewrite rmorphM rootM /= -Dq2; apply/orP; right. rewrite (minCpoly_cyclotomic prim_z) /cyclotomic. rewrite (bigD1 (Ordinal (ltn_pmod k n_gt0))) ?coprime_modl //=. by rewrite rootM root_XsubC prim_expr_mod ?eqxx. have phim : monoid_morphism phi. by apply/kHom_monoid_morphism; rewrite -genQn span_seq1 /= kHomExtendP. pose phimM := GRing.isMonoidMorphism.Build _ _ phi phim. pose phiRM : {rmorphism _ -> _} := HB.pack (fun_of_lfun phi) phimM. have [nu Dnu] := extend_algC_subfield_aut QnC phiRM. exists nu => _ /(prim_rootP prim_z)[i ->]. rewrite rmorphXn /= exprAC -Dz -Dnu /= -{1}[zn]hornerX /phi. rewrite (kHomExtend_poly homQn1) ?polyOverX //. rewrite map_polyE map_id_in => [|?]; last by rewrite id_lfunE. by rewrite polyseqK hornerX rmorphXn. Qed. (* Algebraic integers. *) Definition Aint : {pred algC} := fun x => minCpoly x \is a polyOver Num.int. Lemma root_monic_Aint p x : root p x -> p \is monic -> p \is a polyOver Num.int -> x \in Aint. Proof. have pZtoQtoC pz: pQtoC (pZtoQ pz) = pZtoC pz. by rewrite -map_poly_comp; apply: eq_map_poly => b; rewrite /= rmorph_int. move=> px0 mon_p /floorpP[pz Dp]; rewrite unfold_in. move: px0; rewrite Dp -pZtoQtoC; have [q [-> mon_q] ->] := minCpolyP x. case/dvdpP_rat_int=> qz [a nz_a Dq] [r]. move/(congr1 (fun q1 => lead_coef (a *: pZtoQ q1))). rewrite rmorphM scalerAl -Dq lead_coefZ lead_coefM /=. have /monicP->: pZtoQ pz \is monic by rewrite -(map_monic QtoC) pZtoQtoC -Dp. rewrite (monicP mon_q) mul1r mulr1 lead_coef_map_inj //; last exact: intr_inj. rewrite Dq => ->; apply/polyOverP=> i; rewrite !(coefZ, coef_map). by rewrite -rmorphM /= rmorph_int. Qed. Lemma Cint_rat_Aint z : z \in Crat -> z \in Aint -> z \in Num.int. Proof. case/CratP=> a ->{z} /polyOverP/(_ 0). have [p [Dp mon_p] dv_p] := minCpolyP (ratr a); rewrite Dp coef_map. suffices /eqP->: p == 'X - a%:P by rewrite polyseqXsubC /= rmorphN rpredN. rewrite -eqp_monic ?monicXsubC // irredp_XsubC //. by rewrite -(size_map_poly QtoC) -Dp neq_ltn size_minCpoly orbT. by rewrite -dv_p fmorph_root root_XsubC. Qed. Lemma Aint_Cint : {subset Num.int <= Aint}. Proof. move=> x; rewrite -polyOverXsubC. by apply: root_monic_Aint; rewrite ?monicXsubC ?root_XsubC. Qed. Lemma Aint_int x : x%:~R \in Aint. Proof. by rewrite Aint_Cint. Qed. Lemma Aint0 : 0 \in Aint. Proof. exact: Aint_int 0. Qed. Lemma Aint1 : 1 \in Aint. Proof. exact: Aint_int 1. Qed. #[global] Hint Resolve Aint0 Aint1 : core. Lemma Aint_unity_root n x : (n > 0)%N -> n.-unity_root x -> x \in Aint. Proof. move=> n_gt0 xn1; apply: root_monic_Aint xn1 (monicXnsubC _ n_gt0) _. by apply/polyOverP=> i; rewrite coefB coefC -mulrb coefXn /= rpredB ?rpred_nat. Qed. Lemma Aint_prim_root n z : n.-primitive_root z -> z \in Aint. Proof. move=> pr_z; apply/(Aint_unity_root (prim_order_gt0 pr_z))/unity_rootP. exact: prim_expr_order. Qed. Lemma Aint_Cnat : {subset Num.nat <= Aint}. Proof. by move=> z /intr_nat/Aint_Cint. Qed. (* This is Isaacs, Lemma (3.3) *) Lemma Aint_subring_exists (X : seq algC) : {subset X <= Aint} -> {S : pred algC & (*a*) subring_closed S /\ (*b*) {subset X <= S} & (*c*) {Y : {n : nat & n.-tuple algC} & {subset tagged Y <= S} & forall x, reflect (inIntSpan (tagged Y) x) (x \in S)}}. Proof. move=> AZ_X; pose m := (size X).+1. pose n (i : 'I_m) := (size (minCpoly X`_i)).-2; pose N := (\max_i n i).+1. pose IY := family (fun i => [pred e : 'I_N | e <= n i]%N). have IY_0: 0 \in IY by apply/familyP=> // i; rewrite ffunE. pose inIY := enum_rank_in IY_0. pose Y := [seq \prod_(i < m) X`_i ^+ (f : 'I_N ^ m) i | f in IY]. have S_P := Cint_spanP [tuple of Y]; set S := Cint_span _ in S_P. have sYS: {subset Y <= S} by apply: mem_Cint_span. have S_1: 1 \in S. by apply/sYS/imageP; exists 0 => //; rewrite big1 // => i; rewrite ffunE. have SmulX (i : 'I_m): {in S, forall x, x * X`_i \in S}. move=> _ /S_P[x ->]; rewrite mulr_suml rpred_sum // => j _. rewrite mulrzAl rpredMz {x}// nth_image mulrC (bigD1 i) //= mulrA -exprS. move: {j}(enum_val j) (familyP (enum_valP j)) => f fP. have:= fP i; rewrite inE /= leq_eqVlt => /predU1P[-> | fi_ltn]; last first. apply/sYS/imageP; have fiK: (inord (f i).+1 : 'I_N) = (f i).+1 :> nat. by rewrite inordK // ltnS (bigmax_sup i). exists (finfun [eta f with i |-> inord (f i).+1]). apply/familyP=> i1; rewrite inE ffunE /= fun_if fiK. by case: eqP => [-> // | _]; apply: fP. rewrite (bigD1 i isT) ffunE /= eqxx fiK; congr (_ * _). by apply: eq_bigr => i1 /[!ffunE]/= /negPf->. have [/monicP ] := (minCpoly_monic X`_i, root_minCpoly X`_i). rewrite /root horner_coef lead_coefE -(subnKC (size_minCpoly _)) subn2. rewrite big_ord_recr /= addrC addr_eq0 => ->; rewrite mul1r => /eqP->. have /floorpP[p Dp]: X`_i \in Aint. by have [/(nth_default 0)-> | /(mem_nth 0)/AZ_X] := leqP (size X) i. rewrite -/(n i) Dp mulNr rpredN // mulr_suml rpred_sum // => [[e le_e]] /= _. rewrite coef_map -mulrA mulrzl rpredMz ?sYS //; apply/imageP. have eK: (inord e : 'I_N) = e :> nat by rewrite inordK // ltnS (bigmax_sup i). exists (finfun [eta f with i |-> inord e]). apply/familyP=> i1; rewrite inE ffunE /= fun_if eK. by case: eqP => [-> // | _]; apply: fP. rewrite (bigD1 i isT) ffunE /= eqxx eK; congr (_ * _). by apply: eq_bigr => i1 /[!ffunE] /= /negPf->. exists S; last by exists (Tagged (fun n => n.-tuple _) [tuple of Y]). split=> [|x Xx]; last first. by rewrite -[x]mul1r -(nth_index 0 Xx) (SmulX (Ordinal _)) // ltnS index_size. split=> // x y Sx Sy; first by rewrite rpredB. case/S_P: Sy => {y}[y ->]; rewrite mulr_sumr rpred_sum //= => j. rewrite mulrzAr rpredMz {y}// nth_image; move: {j}(enum_val j) => f. elim/big_rec: _ => [|i y _ IHy] in x Sx *; first by rewrite mulr1. rewrite mulrA {y}IHy //. elim: {f}(f i : nat) => [|e IHe] in x Sx *; first by rewrite mulr1. by rewrite exprS mulrA IHe // SmulX. Qed. Section AlgIntSubring. (* This is Isaacs, Theorem (3.4). *) Theorem fin_Csubring_Aint S n (Y : n.-tuple algC) : mulr_closed S -> (forall x, reflect (inIntSpan Y x) (x \in S)) -> {subset S <= Aint}. Proof. move=> mulS. pose Sm := GRing.isMulClosed.Build _ _ mulS. pose SC : mulrClosed _ := HB.pack S Sm. have ZP_C c: (ZtoC c)%:P \is a polyOver Num.int_num_subdef. by rewrite raddfMz rpred_int. move=> S_P x Sx; pose v := \row_(i < n) Y`_i. have [v0 | nz_v] := eqVneq v 0. case/S_P: Sx => {}x ->; rewrite big1 ?isAlgInt0 // => i _. by have /rowP/(_ i)/[!mxE] -> := v0; rewrite mul0rz. have sYS (i : 'I_n): x * Y`_i \in SC. by rewrite rpredM //; apply/S_P/Cint_spanP/mem_Cint_span/memt_nth. pose A := \matrix_(i, j < n) sval (sig_eqW (S_P _ (sYS j))) i. pose p := char_poly (map_mx ZtoC A). have: p \is a polyOver Num.int_num_subdef. rewrite rpred_sum // => s _; rewrite rpredMsign rpred_prod // => j _. by rewrite !mxE /= rpredB ?rpredMn ?polyOverX. apply: root_monic_Aint (char_poly_monic _). rewrite -eigenvalue_root_char; apply/eigenvalueP; exists v => //. apply/rowP=> j; case dAj: (sig_eqW (S_P _ (sYS j))) => [a DxY]. by rewrite !mxE DxY; apply: eq_bigr => i _; rewrite !mxE dAj /= mulrzr. Qed. (* This is Isaacs, Corollary (3.5). *) Corollary Aint_subring : subring_closed Aint. Proof. suff rAZ: {in Aint &, forall x y, (x - y \in Aint) * (x * y \in Aint)}. by split=> // x y AZx AZy; rewrite rAZ. move=> x y AZx AZy. have [|S [ringS] ] := @Aint_subring_exists [:: x; y]; first exact/allP/and3P. move=> /allP/and3P[Sx Sy _] [Y _ genYS]. have AZ_S := fin_Csubring_Aint ringS genYS. by have [_ S_B S_M] := ringS; rewrite !AZ_S ?S_B ?S_M. Qed. HB.instance Definition _ := GRing.isSubringClosed.Build _ Aint Aint_subring. End AlgIntSubring. Lemma Aint_aut (nu : {rmorphism algC -> algC}) x : (nu x \in Aint) = (x \in Aint). Proof. by rewrite !unfold_in minCpoly_aut. Qed. Definition dvdA (e : Algebraics.divisor) : {pred algC} := fun z => if e == 0 then z == 0 else z / e \in Aint. Delimit Scope algC_scope with A. Delimit Scope algC_expanded_scope with Ax. Notation "e %| x" := (x \in dvdA e) : algC_expanded_scope. Notation "e %| x" := (@in_mem Algebraics.divisor x (mem (dvdA e))) : algC_scope. Fact dvdA_zmod_closed e : zmod_closed (dvdA e). Proof. split=> [|x y]; first by rewrite unfold_in mul0r eqxx rpred0 ?if_same. rewrite ![(e %| _)%A]unfold_in. case: ifP => [_ x0 /eqP-> | _]; first by rewrite subr0. by rewrite mulrBl; apply: rpredB. Qed. HB.instance Definition _ e := GRing.isZmodClosed.Build _ (dvdA e) (dvdA_zmod_closed e). Definition eqAmod (e x y : Algebraics.divisor) := (e %| x - y)%A. Notation "x == y %[mod e ]" := (eqAmod e x y) : algC_scope. Notation "x != y %[mod e ]" := (~~ (eqAmod e x y)) : algC_scope. Lemma eqAmod_refl e x : (x == x %[mod e])%A. Proof. by rewrite /eqAmod subrr rpred0. Qed. #[global] Hint Resolve eqAmod_refl : core. Lemma eqAmod_sym e x y : ((x == y %[mod e]) = (y == x %[mod e]))%A. Proof. by rewrite /eqAmod -opprB rpredN. Qed. Lemma eqAmod_trans e y x z : (x == y %[mod e] -> y == z %[mod e] -> x == z %[mod e])%A. Proof. by move=> Exy Eyz; rewrite /eqAmod -[x](subrK y) -[_ - z]addrA rpredD. Qed. Lemma eqAmod_transl e x y z : (x == y %[mod e])%A -> (x == z %[mod e])%A = (y == z %[mod e])%A. Proof. by move/(sym_left_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed. Lemma eqAmod_transr e x y z : (x == y %[mod e])%A -> (z == x %[mod e])%A = (z == y %[mod e])%A. Proof. by move/(sym_right_transitive (eqAmod_sym e) (@eqAmod_trans e)). Qed. Lemma eqAmod0 e x : (x == 0 %[mod e])%A = (e %| x)%A. Proof. by rewrite /eqAmod subr0. Qed. Lemma eqAmodN e x y : (- x == y %[mod e])%A = (x == - y %[mod e])%A. Proof. by rewrite eqAmod_sym /eqAmod !opprK addrC. Qed. Lemma eqAmodDr e x y z : (y + x == z + x %[mod e])%A = (y == z %[mod e])%A. Proof. by rewrite /eqAmod addrAC opprD !addrA subrK. Qed. Lemma eqAmodDl e x y z : (x + y == x + z %[mod e])%A = (y == z %[mod e])%A. Proof. by rewrite !(addrC x) eqAmodDr. Qed. Lemma eqAmodD e x1 x2 y1 y2 : (x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 + y1 == x2 + y2 %[mod e])%A. Proof. by rewrite -(eqAmodDl e x2 y1) -(eqAmodDr e y1); apply: eqAmod_trans. Qed. Lemma eqAmodm0 e : (e == 0 %[mod e])%A. Proof. by rewrite /eqAmod subr0 unfold_in; case: ifPn => // /divff->. Qed. #[global] Hint Resolve eqAmodm0 : core. Lemma eqAmodMr e : {in Aint, forall z x y, x == y %[mod e] -> x * z == y * z %[mod e]}%A. Proof. move=> z Zz x y. rewrite /eqAmod -mulrBl ![(e %| _)%A]unfold_in mulf_eq0 mulrAC. by case: ifP => [_ -> // | _ Exy]; apply: rpredM. Qed. Lemma eqAmodMl e : {in Aint, forall z x y, x == y %[mod e] -> z * x == z * y %[mod e]}%A. Proof. by move=> z Zz x y Exy; rewrite !(mulrC z) eqAmodMr. Qed. Lemma eqAmodMl0 e : {in Aint, forall x, x * e == 0 %[mod e]}%A. Proof. by move=> x Zx; rewrite -(mulr0 x) eqAmodMl. Qed. Lemma eqAmodMr0 e : {in Aint, forall x, e * x == 0 %[mod e]}%A. Proof. by move=> x Zx; rewrite /= mulrC eqAmodMl0. Qed. Lemma eqAmod_addl_mul e : {in Aint, forall x y, x * e + y == y %[mod e]}%A. Proof. by move=> x Zx y; rewrite -{2}[y]add0r eqAmodDr eqAmodMl0. Qed. Lemma eqAmodM e : {in Aint &, forall x1 y2 x2 y1, x1 == x2 %[mod e] -> y1 == y2 %[mod e] -> x1 * y1 == x2 * y2 %[mod e]}%A. Proof. move=> x1 y2 Zx1 Zy2 x2 y1 eq_x /(eqAmodMl Zx1)/eqAmod_trans-> //. exact: eqAmodMr. Qed. Lemma eqAmod_rat : {in Crat & &, forall e m n, (m == n %[mod e])%A = (m == n %[mod e])%C}. Proof. move=> e m n Qe Qm Qn; rewrite /eqCmod unfold_in /eqAmod unfold_in. case: ifPn => // nz_e; apply/idP/idP=> [/Cint_rat_Aint | /Aint_Cint] -> //. by rewrite rpred_div ?rpredB. Qed. Lemma eqAmod0_rat : {in Crat &, forall e n, (n == 0 %[mod e])%A = (e %| n)%C}. Proof. by move=> e n Qe Qn; rewrite /= eqAmod_rat /eqCmod ?subr0 ?Crat0. Qed. Lemma eqAmod_nat (e m n : nat) : (m == n %[mod e])%A = (m == n %[mod e])%N. Proof. by rewrite eqAmod_rat ?rpred_nat // eqCmod_nat. Qed. Lemma eqAmod0_nat (e m : nat) : (m == 0 %[mod e])%A = (e %| m)%N. Proof. by rewrite eqAmod0_rat ?rpred_nat // dvdC_nat. Qed. (* Multiplicative order. *) Definition orderC x := let p := minCpoly x in oapp val 0 [pick n : 'I_(2 * size p ^ 2) | p == intrp 'Phi_n]. Notation "#[ x ]" := (orderC x) : C_scope. Lemma exp_orderC x : x ^+ #[x]%C = 1. Proof. rewrite /orderC; case: pickP => //= [] [n _] /= /eqP Dp. have n_gt0: (0 < n)%N. rewrite lt0n; apply: contraTneq (size_minCpoly x) => n0. by rewrite Dp n0 Cyclotomic0 rmorph1 size_poly1. have [z prim_z] := C_prim_root_exists n_gt0. rewrite prim_expr_order // -(root_cyclotomic prim_z). by rewrite -Cintr_Cyclotomic // -Dp root_minCpoly. Qed. Lemma dvdn_orderC x n : (#[x]%C %| n)%N = (x ^+ n == 1). Proof. apply/idP/eqP=> [|x_n_1]; first by apply: expr_dvd; apply: exp_orderC. have [-> | n_gt0] := posnP n; first by rewrite dvdn0. have [m prim_x m_dv_n] := prim_order_exists n_gt0 x_n_1. have{n_gt0} m_gt0 := dvdn_gt0 n_gt0 m_dv_n; congr (_ %| n)%N: m_dv_n. pose p := minCpoly x; have Dp: p = cyclotomic x m := minCpoly_cyclotomic prim_x. rewrite /orderC; case: pickP => /= [k /eqP Dp_k | no_k]; last first. suffices lt_m_2p: (m < 2 * size p ^ 2)%N. have /eqP[] := no_k (Ordinal lt_m_2p). by rewrite /= -/p Dp -Cintr_Cyclotomic. rewrite Dp size_cyclotomic (sqrnD 1) addnAC mulnDr -add1n leq_add //. suffices: (m <= \prod_(q <- primes m | q == 2) q * totient m ^ 2)%N. have [m_even | m_odd] := boolP (2%N \in primes m). by rewrite -big_filter filter_pred1_uniq ?primes_uniq // big_seq1. by rewrite big_hasC ?has_pred1 // => /leq_trans-> //; apply: leq_addl. rewrite big_mkcond totientE // -mulnn -!big_split /=. rewrite {1}[m]prod_prime_decomp // prime_decompE big_map /= !big_seq. elim/big_ind2: _ => // [n1 m1 n2 m2 | q]; first exact: leq_mul. rewrite mem_primes => /and3P[q_pr _ q_dv_m]. rewrite lognE q_pr m_gt0 q_dv_m /=; move: (logn q _) => k. rewrite !mulnA expnS leq_mul //. case: (ltngtP q 2) (prime_gt1 q_pr) => // [q_gt2|->] _. rewrite mul1n mulnAC mulnn -{1}[q]muln1 leq_mul ?expn_gt0 ?prime_gt0 //. by rewrite -(subnKC q_gt2) (ltn_exp2l 1). by rewrite !muln1 -expnS (ltn_exp2l 0). have k_prim_x: k.-primitive_root x. have k_gt0: (0 < k)%N. rewrite lt0n; apply: contraTneq (size_minCpoly x) => k0. by rewrite Dp_k k0 Cyclotomic0 rmorph1 size_poly1. have [z prim_z] := C_prim_root_exists k_gt0. rewrite -(root_cyclotomic prim_z) -Cintr_Cyclotomic //. by rewrite -Dp_k root_minCpoly. apply/eqP; rewrite eqn_dvd !(@prim_order_dvd _ _ x) //. by rewrite !prim_expr_order ?eqxx. Qed.
Basic.lean
/- Copyright (c) 2025 Weiyi Wang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Weiyi Wang -/ import Mathlib.Algebra.Order.Group.Unbundled.Abs import Mathlib.Algebra.Order.Module.Defs /-! # Further lemmas about monotonicity of scalar multiplication -/ variable {α β : Type*} variable [Ring α] [LinearOrder α] [IsOrderedRing α] variable [AddCommGroup β] [LinearOrder β] [IsOrderedAddMonoid β] variable [Module α β] [PosSMulMono α β] @[simp] theorem abs_smul (a : α) (b : β) : |a • b| = |a| • |b| := by obtain ha | ha := le_total a 0 <;> obtain hb | hb := le_total b 0 <;> simp [*, abs_of_nonneg, abs_of_nonpos, smul_nonneg, smul_nonpos_of_nonneg_of_nonpos, smul_nonpos_of_nonpos_of_nonneg, smul_nonneg_of_nonpos_of_nonpos]
Powerset.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.Finset.Powerset import Mathlib.Data.Fintype.EquivFin /-! # fintype instance for `Set α`, when `α` is a fintype -/ variable {α : Type*} open Finset instance Finset.fintype [Fintype α] : Fintype (Finset α) := ⟨univ.powerset, fun _ => Finset.mem_powerset.2 (Finset.subset_univ _)⟩ @[simp] theorem Fintype.card_finset [Fintype α] : Fintype.card (Finset α) = 2 ^ Fintype.card α := Finset.card_powerset Finset.univ namespace Finset variable [Fintype α] {s : Finset α} {k : ℕ} @[simp] lemma powerset_univ : (univ : Finset α).powerset = univ := coe_injective <| by simp [-coe_eq_univ] lemma filter_subset_univ [DecidableEq α] (s : Finset α) : ({t | t ⊆ s} : Finset _) = powerset s := by ext; simp @[simp] lemma powerset_eq_univ : s.powerset = univ ↔ s = univ := by rw [← Finset.powerset_univ, powerset_inj] lemma mem_powersetCard_univ : s ∈ powersetCard k (univ : Finset α) ↔ #s = k := mem_powersetCard.trans <| and_iff_right <| subset_univ _ variable (α) @[simp] lemma univ_filter_card_eq (k : ℕ) : ({s | #s = k} : Finset (Finset α)) = univ.powersetCard k := by ext; simp end Finset @[simp] theorem Fintype.card_finset_len [Fintype α] (k : ℕ) : Fintype.card { s : Finset α // #s = k } = Nat.choose (Fintype.card α) k := by simp [Fintype.subtype_card, Finset.card_univ] instance Set.fintype [Fintype α] : Fintype (Set α) := ⟨(@Finset.univ (Finset α) _).map coeEmb.1, fun s => by classical refine mem_map.2 ⟨({a | a ∈ s} : Finset _), Finset.mem_univ _, (coe_filter _ _).trans ?_⟩ simp⟩ -- Not to be confused with `Set.Finite`, the predicate instance Set.instFinite [Finite α] : Finite (Set α) := by cases nonempty_fintype α infer_instance @[simp] theorem Fintype.card_set [Fintype α] : Fintype.card (Set α) = 2 ^ Fintype.card α := (Finset.card_map _).trans (Finset.card_powerset _)
FixedPoints.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, Kenny Lau, Yury Kudryashov -/ import Mathlib.Dynamics.FixedPoints.Basic import Mathlib.Order.Hom.Order import Mathlib.Order.OmegaCompletePartialOrder /-! # Fixed point construction on complete lattices This file sets up the basic theory of fixed points of a monotone function in a complete lattice. ## Main definitions * `OrderHom.lfp`: The least fixed point of a bundled monotone function. * `OrderHom.gfp`: The greatest fixed point of a bundled monotone function. * `OrderHom.prevFixed`: The greatest fixed point of a bundled monotone function smaller than or equal to a given element. * `OrderHom.nextFixed`: The least fixed point of a bundled monotone function greater than or equal to a given element. * `fixedPoints.completeLattice`: The Knaster-Tarski theorem: fixed points of a monotone self-map of a complete lattice form themselves a complete lattice. ## Tags fixed point, complete lattice, monotone function -/ universe u v w variable {α : Type u} {β : Type v} {γ : Type w} open Function (fixedPoints IsFixedPt) namespace OrderHom section Basic variable [CompleteLattice α] (f : α →o α) /-- Least fixed point of a monotone function -/ def lfp : (α →o α) →o α where toFun f := sInf { a | f a ≤ a } monotone' _ _ hle := sInf_le_sInf fun a ha => (hle a).trans ha /-- Greatest fixed point of a monotone function -/ def gfp : (α →o α) →o α where toFun f := sSup { a | a ≤ f a } monotone' _ _ hle := sSup_le_sSup fun a ha => le_trans ha (hle a) theorem lfp_le {a : α} (h : f a ≤ a) : f.lfp ≤ a := sInf_le h theorem lfp_le_fixed {a : α} (h : f a = a) : f.lfp ≤ a := f.lfp_le h.le theorem le_lfp {a : α} (h : ∀ b, f b ≤ b → a ≤ b) : a ≤ f.lfp := le_sInf h theorem map_le_lfp {a : α} (ha : a ≤ f.lfp) : f a ≤ f.lfp := f.le_lfp fun _ hb => (f.mono <| le_sInf_iff.1 ha _ hb).trans hb @[simp] theorem map_lfp : f f.lfp = f.lfp := have h : f f.lfp ≤ f.lfp := f.map_le_lfp le_rfl h.antisymm <| f.lfp_le <| f.mono h theorem isFixedPt_lfp : IsFixedPt f f.lfp := f.map_lfp theorem lfp_le_map {a : α} (ha : f.lfp ≤ a) : f.lfp ≤ f a := calc f.lfp = f f.lfp := f.map_lfp.symm _ ≤ f a := f.mono ha theorem isLeast_lfp_le : IsLeast { a | f a ≤ a } f.lfp := ⟨f.map_lfp.le, fun _ => f.lfp_le⟩ theorem isLeast_lfp : IsLeast (fixedPoints f) f.lfp := ⟨f.isFixedPt_lfp, fun _ => f.lfp_le_fixed⟩ theorem lfp_induction {p : α → Prop} (step : ∀ a, p a → a ≤ f.lfp → p (f a)) (hSup : ∀ s, (∀ a ∈ s, p a) → p (sSup s)) : p f.lfp := by set s := { a | a ≤ f.lfp ∧ p a } specialize hSup s fun a => And.right suffices sSup s = f.lfp from this ▸ hSup have h : sSup s ≤ f.lfp := sSup_le fun b => And.left have hmem : f (sSup s) ∈ s := ⟨f.map_le_lfp h, step _ hSup h⟩ exact h.antisymm (f.lfp_le <| le_sSup hmem) theorem le_gfp {a : α} (h : a ≤ f a) : a ≤ f.gfp := le_sSup h theorem gfp_le {a : α} (h : ∀ b, b ≤ f b → b ≤ a) : f.gfp ≤ a := sSup_le h theorem isFixedPt_gfp : IsFixedPt f f.gfp := f.dual.isFixedPt_lfp @[simp] theorem map_gfp : f f.gfp = f.gfp := f.dual.map_lfp theorem map_le_gfp {a : α} (ha : a ≤ f.gfp) : f a ≤ f.gfp := f.dual.lfp_le_map ha theorem gfp_le_map {a : α} (ha : f.gfp ≤ a) : f.gfp ≤ f a := f.dual.map_le_lfp ha theorem isGreatest_gfp_le : IsGreatest { a | a ≤ f a } f.gfp := f.dual.isLeast_lfp_le theorem isGreatest_gfp : IsGreatest (fixedPoints f) f.gfp := f.dual.isLeast_lfp theorem gfp_induction {p : α → Prop} (step : ∀ a, p a → f.gfp ≤ a → p (f a)) (hInf : ∀ s, (∀ a ∈ s, p a) → p (sInf s)) : p f.gfp := f.dual.lfp_induction step hInf end Basic section Eqn variable [CompleteLattice α] [CompleteLattice β] (f : β →o α) (g : α →o β) -- Rolling rule theorem map_lfp_comp : f (g.comp f).lfp = (f.comp g).lfp := le_antisymm ((f.comp g).map_lfp ▸ f.mono (lfp_le_fixed _ <| congr_arg g (f.comp g).map_lfp)) <| lfp_le _ (congr_arg f (g.comp f).map_lfp).le theorem map_gfp_comp : f (g.comp f).gfp = (f.comp g).gfp := f.dual.map_lfp_comp g.dual -- Diagonal rule theorem lfp_lfp (h : α →o α →o α) : (lfp.comp h).lfp = h.onDiag.lfp := by let a := (lfp.comp h).lfp refine (lfp_le _ ?_).antisymm (lfp_le _ (Eq.le ?_)) · exact lfp_le _ h.onDiag.map_lfp.le have ha : (lfp ∘ h) a = a := (lfp.comp h).map_lfp calc h a a = h a (h a).lfp := congr_arg (h a) ha.symm _ = (h a).lfp := (h a).map_lfp _ = a := ha theorem gfp_gfp (h : α →o α →o α) : (gfp.comp h).gfp = h.onDiag.gfp := @lfp_lfp αᵒᵈ _ <| (OrderHom.dualIso αᵒᵈ αᵒᵈ).symm.toOrderEmbedding.toOrderHom.comp h.dual end Eqn section PrevNext variable [CompleteLattice α] (f : α →o α) theorem gfp_const_inf_le (x : α) : (const α x ⊓ f).gfp ≤ x := (gfp_le _) fun _ hb => hb.trans inf_le_left /-- Previous fixed point of a monotone map. If `f` is a monotone self-map of a complete lattice and `x` is a point such that `f x ≤ x`, then `f.prevFixed x hx` is the greatest fixed point of `f` that is less than or equal to `x`. -/ def prevFixed (x : α) (hx : f x ≤ x) : fixedPoints f := ⟨(const α x ⊓ f).gfp, calc f (const α x ⊓ f).gfp = x ⊓ f (const α x ⊓ f).gfp := Eq.symm <| inf_of_le_right <| (f.mono <| f.gfp_const_inf_le x).trans hx _ = (const α x ⊓ f).gfp := (const α x ⊓ f).map_gfp ⟩ /-- Next fixed point of a monotone map. If `f` is a monotone self-map of a complete lattice and `x` is a point such that `x ≤ f x`, then `f.nextFixed x hx` is the least fixed point of `f` that is greater than or equal to `x`. -/ def nextFixed (x : α) (hx : x ≤ f x) : fixedPoints f := { f.dual.prevFixed x hx with val := (const α x ⊔ f).lfp } theorem prevFixed_le {x : α} (hx : f x ≤ x) : ↑(f.prevFixed x hx) ≤ x := f.gfp_const_inf_le x theorem le_nextFixed {x : α} (hx : x ≤ f x) : x ≤ f.nextFixed x hx := f.dual.prevFixed_le hx theorem nextFixed_le {x : α} (hx : x ≤ f x) {y : fixedPoints f} (h : x ≤ y) : f.nextFixed x hx ≤ y := Subtype.coe_le_coe.1 <| lfp_le _ <| sup_le h y.2.le @[simp] theorem nextFixed_le_iff {x : α} (hx : x ≤ f x) {y : fixedPoints f} : f.nextFixed x hx ≤ y ↔ x ≤ y := ⟨fun h => (f.le_nextFixed hx).trans h, f.nextFixed_le hx⟩ @[simp] theorem le_prevFixed_iff {x : α} (hx : f x ≤ x) {y : fixedPoints f} : y ≤ f.prevFixed x hx ↔ ↑y ≤ x := f.dual.nextFixed_le_iff hx theorem le_prevFixed {x : α} (hx : f x ≤ x) {y : fixedPoints f} (h : ↑y ≤ x) : y ≤ f.prevFixed x hx := (f.le_prevFixed_iff hx).2 h theorem le_map_sup_fixedPoints (x y : fixedPoints f) : (x ⊔ y : α) ≤ f (x ⊔ y) := calc (x ⊔ y : α) = f x ⊔ f y := congr_arg₂ (· ⊔ ·) x.2.symm y.2.symm _ ≤ f (x ⊔ y) := f.mono.le_map_sup x y -- Porting note: `x ⊓ y` without the `.val`sw fails to synthesize `Inf` instance theorem map_inf_fixedPoints_le (x y : fixedPoints f) : f (x ⊓ y) ≤ x.val ⊓ y.val := f.dual.le_map_sup_fixedPoints x y theorem le_map_sSup_subset_fixedPoints (A : Set α) (hA : A ⊆ fixedPoints f) : sSup A ≤ f (sSup A) := sSup_le fun _ hx => hA hx ▸ (f.mono <| le_sSup hx) theorem map_sInf_subset_fixedPoints_le (A : Set α) (hA : A ⊆ fixedPoints f) : f (sInf A) ≤ sInf A := le_sInf fun _ hx => hA hx ▸ (f.mono <| sInf_le hx) end PrevNext end OrderHom namespace fixedPoints open OrderHom variable [CompleteLattice α] (f : α →o α) instance : SemilatticeSup (fixedPoints f) := { Subtype.partialOrder _ with sup := fun x y => f.nextFixed (x ⊔ y) (f.le_map_sup_fixedPoints x y) le_sup_left := fun _ _ => Subtype.coe_le_coe.1 <| le_sup_left.trans (f.le_nextFixed _) le_sup_right := fun _ _ => Subtype.coe_le_coe.1 <| le_sup_right.trans (f.le_nextFixed _) sup_le := fun _ _ _ hxz hyz => f.nextFixed_le _ <| sup_le hxz hyz } instance : SemilatticeInf (fixedPoints f) := { OrderDual.instSemilatticeInf (fixedPoints f.dual) with inf := fun x y => f.prevFixed (x ⊓ y) (f.map_inf_fixedPoints_le x y) } instance : CompleteSemilatticeSup (fixedPoints f) := { Subtype.partialOrder _ with sSup := fun s => f.nextFixed (sSup (Subtype.val '' s)) (f.le_map_sSup_subset_fixedPoints (Subtype.val '' s) fun _ ⟨x, hx⟩ => hx.2 ▸ x.2) le_sSup := fun _ _ hx => Subtype.coe_le_coe.1 <| le_trans (le_sSup <| Set.mem_image_of_mem _ hx) (f.le_nextFixed _) sSup_le := fun _ _ hx => f.nextFixed_le _ <| sSup_le <| Set.forall_mem_image.2 hx } instance : CompleteSemilatticeInf (fixedPoints f) := { Subtype.partialOrder _ with sInf := fun s => f.prevFixed (sInf (Subtype.val '' s)) (f.map_sInf_subset_fixedPoints_le (Subtype.val '' s) fun _ ⟨x, hx⟩ => hx.2 ▸ x.2) le_sInf := fun _ _ hx => f.le_prevFixed _ <| le_sInf <| Set.forall_mem_image.2 hx sInf_le := fun _ _ hx => Subtype.coe_le_coe.1 <| le_trans (f.prevFixed_le _) (sInf_le <| Set.mem_image_of_mem _ hx) } /-- **Knaster-Tarski Theorem**: The fixed points of `f` form a complete lattice. -/ instance completeLattice : CompleteLattice (fixedPoints f) where __ := inferInstanceAs (SemilatticeInf (fixedPoints f)) __ := inferInstanceAs (SemilatticeSup (fixedPoints f)) __ := inferInstanceAs (CompleteSemilatticeInf (fixedPoints f)) __ := inferInstanceAs (CompleteSemilatticeSup (fixedPoints f)) top := ⟨f.gfp, f.isFixedPt_gfp⟩ bot := ⟨f.lfp, f.isFixedPt_lfp⟩ le_top x := f.le_gfp x.2.ge bot_le x := f.lfp_le x.2.le open OmegaCompletePartialOrder fixedPoints /-- **Kleene's fixed point Theorem**: The least fixed point in a complete lattice is the supremum of iterating a function on bottom arbitrary often. -/ theorem lfp_eq_sSup_iterate (h : ωScottContinuous f) : f.lfp = ⨆ n, f^[n] ⊥ := by apply le_antisymm · apply lfp_le_fixed exact Function.mem_fixedPoints.mp (ωSup_iterate_mem_fixedPoint ⟨f, h.map_ωSup_of_orderHom⟩ ⊥ bot_le) · apply le_lfp intro a h_a exact ωSup_iterate_le_prefixedPoint ⟨f, h.map_ωSup_of_orderHom⟩ ⊥ bot_le h_a bot_le theorem gfp_eq_sInf_iterate (h : ωScottContinuous f.dual) : f.gfp = ⨅ n, f^[n] ⊤ := lfp_eq_sSup_iterate f.dual h end fixedPoints
PropInstances.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.Order.Disjoint /-! # The order on `Prop` Instances on `Prop` such as `DistribLattice`, `BoundedOrder`, `LinearOrder`. -/ /-- Propositions form a distributive lattice. -/ instance Prop.instDistribLattice : DistribLattice Prop where sup := Or le_sup_left := @Or.inl le_sup_right := @Or.inr sup_le := fun _ _ _ => Or.rec inf := And inf_le_left := @And.left inf_le_right := @And.right le_inf := fun _ _ _ Hab Hac Ha => And.intro (Hab Ha) (Hac Ha) le_sup_inf := fun _ _ _ => or_and_left.2 /-- Propositions form a bounded order. -/ instance Prop.instBoundedOrder : BoundedOrder Prop where top := True le_top _ _ := True.intro bot := False bot_le := @False.elim @[simp] theorem Prop.bot_eq_false : (⊥ : Prop) = False := rfl @[simp] theorem Prop.top_eq_true : (⊤ : Prop) = True := rfl instance Prop.le_isTotal : IsTotal Prop (· ≤ ·) := ⟨fun p q => by by_cases h : q <;> simp [h]⟩ noncomputable instance Prop.linearOrder : LinearOrder Prop := by classical exact Lattice.toLinearOrder Prop @[simp] theorem sup_Prop_eq : (· ⊔ ·) = (· ∨ ·) := rfl @[simp] theorem inf_Prop_eq : (· ⊓ ·) = (· ∧ ·) := rfl namespace Pi variable {ι : Type*} {α' : ι → Type*} [∀ i, PartialOrder (α' i)] theorem disjoint_iff [∀ i, OrderBot (α' i)] {f g : ∀ i, α' i} : Disjoint f g ↔ ∀ i, Disjoint (f i) (g i) := by classical constructor · intro h i x hf hg exact (update_le_iff.mp <| h (update_le_iff.mpr ⟨hf, fun _ _ => bot_le⟩) (update_le_iff.mpr ⟨hg, fun _ _ => bot_le⟩)).1 · intro h x hf hg i apply h i (hf i) (hg i) theorem codisjoint_iff [∀ i, OrderTop (α' i)] {f g : ∀ i, α' i} : Codisjoint f g ↔ ∀ i, Codisjoint (f i) (g i) := @disjoint_iff _ (fun i => (α' i)ᵒᵈ) _ _ _ _ theorem isCompl_iff [∀ i, BoundedOrder (α' i)] {f g : ∀ i, α' i} : IsCompl f g ↔ ∀ i, IsCompl (f i) (g i) := by simp_rw [_root_.isCompl_iff, disjoint_iff, codisjoint_iff, forall_and] end Pi @[simp] theorem Prop.disjoint_iff {P Q : Prop} : Disjoint P Q ↔ ¬(P ∧ Q) := disjoint_iff_inf_le @[simp] theorem Prop.codisjoint_iff {P Q : Prop} : Codisjoint P Q ↔ P ∨ Q := codisjoint_iff_le_sup.trans <| forall_const True @[simp] theorem Prop.isCompl_iff {P Q : Prop} : IsCompl P Q ↔ ¬(P ↔ Q) := by rw [_root_.isCompl_iff, Prop.disjoint_iff, Prop.codisjoint_iff, not_iff] by_cases P <;> by_cases Q <;> simp [*] section decidable_instances universe u variable {α : Type u} instance Prop.decidablePredBot : DecidablePred (⊥ : α → Prop) := fun _ => instDecidableFalse instance Prop.decidablePredTop : DecidablePred (⊤ : α → Prop) := fun _ => instDecidableTrue instance Prop.decidableRelBot : DecidableRel (⊥ : α → α → Prop) := fun _ _ => instDecidableFalse instance Prop.decidableRelTop : DecidableRel (⊤ : α → α → Prop) := fun _ _ => instDecidableTrue end decidable_instances
WithVal.lean
/- Copyright (c) 2025 Salvatore Mercuri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Salvatore Mercuri -/ import Mathlib.Topology.UniformSpace.Completion import Mathlib.Topology.Algebra.Valued.ValuationTopology import Mathlib.NumberTheory.NumberField.Basic /-! # Ring topologised by a valuation For a given valuation `v : Valuation R Γ₀` on a ring `R` taking values in `Γ₀`, this file defines the type synonym `WithVal v` of `R`. By assigning a `Valued (WithVal v) Γ₀` instance, `WithVal v` represents the ring `R` equipped with the topology coming from `v`. The type synonym `WithVal v` is in isomorphism to `R` as rings via `WithVal.equiv v`. This isomorphism should be used to explicitly map terms of `WithVal v` to terms of `R`. The `WithVal` type synonym is used to define the completion of `R` with respect to `v` in `Valuation.Completion`. An example application of this is `IsDedekindDomain.HeightOneSpectrum.adicCompletion`, which is the completion of the field of fractions of a Dedekind domain with respect to a height-one prime ideal of the domain. ## Main definitions - `WithVal` : type synonym for a ring equipped with the topology coming from a valuation. - `WithVal.equiv` : the canonical ring equivalence between `WithValuation v` and `R`. - `Valuation.Completion` : the uniform space completion of a field `K` according to the uniform structure defined by the specified valuation. -/ noncomputable section variable {R Γ₀ : Type*} [LinearOrderedCommGroupWithZero Γ₀] /-- Type synonym for a ring equipped with the topology coming from a valuation. -/ @[nolint unusedArguments] def WithVal [Ring R] : Valuation R Γ₀ → Type _ := fun _ => R namespace WithVal section Instances variable {P S : Type*} [LinearOrderedCommGroupWithZero Γ₀] instance [Ring R] (v : Valuation R Γ₀) : Ring (WithVal v) := inferInstanceAs (Ring R) instance [CommRing R] (v : Valuation R Γ₀) : CommRing (WithVal v) := inferInstanceAs (CommRing R) instance [Field R] (v : Valuation R Γ₀) : Field (WithVal v) := inferInstanceAs (Field R) instance [Ring R] (v : Valuation R Γ₀) : Inhabited (WithVal v) := ⟨0⟩ instance [CommSemiring S] [CommRing R] [Algebra S R] (v : Valuation R Γ₀) : Algebra S (WithVal v) := inferInstanceAs (Algebra S R) instance [CommRing S] [CommRing R] [Algebra S R] [IsFractionRing S R] (v : Valuation R Γ₀) : IsFractionRing S (WithVal v) := inferInstanceAs (IsFractionRing S R) instance [Ring R] [SMul S R] (v : Valuation R Γ₀) : SMul S (WithVal v) := inferInstanceAs (SMul S R) instance [Ring R] [SMul P S] [SMul S R] [SMul P R] [IsScalarTower P S R] (v : Valuation R Γ₀) : IsScalarTower P S (WithVal v) := inferInstanceAs (IsScalarTower P S R) variable [CommRing R] (v : Valuation R Γ₀) instance {S : Type*} [Ring S] [Algebra R S] : Algebra (WithVal v) S := inferInstanceAs (Algebra R S) instance {S : Type*} [Ring S] [Algebra R S] (w : Valuation S Γ₀) : Algebra R (WithVal w) := inferInstanceAs (Algebra R S) instance {P S : Type*} [Ring S] [Semiring P] [Module P R] [Module P S] [Algebra R S] [IsScalarTower P R S] : IsScalarTower P (WithVal v) S := inferInstanceAs (IsScalarTower P R S) end Instances variable [Ring R] (v : Valuation R Γ₀) /-- Canonical ring equivalence between `WithVal v` and `R`. -/ def equiv : WithVal v ≃+* R := RingEquiv.refl _ instance {R} [Ring R] (v : Valuation R Γ₀) : Valued (WithVal v) Γ₀ := Valued.mk' (v.comap (WithVal.equiv v)) @[simp] theorem apply_equiv (r : WithVal v) : (Valued.v : Valuation (WithVal v) Γ₀) (WithVal.equiv v r) = v r := rfl @[simp] theorem apply_symm_equiv (r : R) : v ((WithVal.equiv v).symm r) = v r := rfl end WithVal /-! The completion of a field with respect to a valuation. -/ namespace Valuation open WithVal variable {R : Type*} [Ring R] (v : Valuation R Γ₀) /-- The completion of a field with respect to a valuation. -/ abbrev Completion := UniformSpace.Completion (WithVal v) instance : Coe R v.Completion := inferInstanceAs <| Coe (WithVal v) (UniformSpace.Completion (WithVal v)) end Valuation namespace NumberField.RingOfIntegers variable {K : Type*} [Field K] [NumberField K] (v : Valuation K Γ₀) instance : CoeHead (𝓞 (WithVal v)) (WithVal v) := inferInstanceAs (CoeHead (𝓞 K) K) instance : IsDedekindDomain (𝓞 (WithVal v)) := inferInstanceAs (IsDedekindDomain (𝓞 K)) instance (R : Type*) [CommRing R] [Algebra R K] [IsIntegralClosure R ℤ K] : IsIntegralClosure R ℤ (WithVal v) := ‹IsIntegralClosure R ℤ K› /-- The ring equivalence between `𝓞 (WithVal v)` and an integral closure of `ℤ` in `K`. -/ @[simps!] def withValEquiv (R : Type*) [CommRing R] [Algebra R K] [IsIntegralClosure R ℤ K] : 𝓞 (WithVal v) ≃+* R := NumberField.RingOfIntegers.equiv R end NumberField.RingOfIntegers open scoped NumberField in /-- The ring of integers of `WithVal v`, when `v` is a valuation on `ℚ`, is equivalent to `ℤ`. -/ @[simps! apply] def Rat.ringOfIntegersWithValEquiv (v : Valuation ℚ Γ₀) : 𝓞 (WithVal v) ≃+* ℤ := NumberField.RingOfIntegers.withValEquiv v ℤ
GammaCompN.lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.AlgebraicTopology.DoldKan.FunctorGamma import Mathlib.AlgebraicTopology.DoldKan.SplitSimplicialObject import Mathlib.CategoryTheory.Idempotents.HomologicalComplex import Mathlib.Tactic.SuppressCompilation /-! The counit isomorphism of the Dold-Kan equivalence The purpose of this file is to construct natural isomorphisms `N₁Γ₀ : Γ₀ ⋙ N₁ ≅ toKaroubi (ChainComplex C ℕ)` and `N₂Γ₂ : Γ₂ ⋙ N₂ ≅ 𝟭 (Karoubi (ChainComplex C ℕ))`. (See `Equivalence.lean` for the general strategy of proof of the Dold-Kan equivalence.) -/ suppress_compilation noncomputable section open CategoryTheory CategoryTheory.Category CategoryTheory.Functor CategoryTheory.Limits CategoryTheory.Idempotents Opposite SimplicialObject Simplicial namespace AlgebraicTopology namespace DoldKan variable {C : Type*} [Category C] [Preadditive C] [HasFiniteCoproducts C] /-- The isomorphism `(Γ₀.splitting K).nondegComplex ≅ K` for all `K : ChainComplex C ℕ`. -/ @[simps!] def Γ₀NondegComplexIso (K : ChainComplex C ℕ) : (Γ₀.splitting K).nondegComplex ≅ K := HomologicalComplex.Hom.isoOfComponents (fun _ => Iso.refl _) (by rintro _ n (rfl : n + 1 = _) dsimp simp only [id_comp, comp_id, AlternatingFaceMapComplex.obj_d_eq, Preadditive.sum_comp, Preadditive.comp_sum] rw [Fintype.sum_eq_single (0 : Fin (n + 2))] · simp only [Fin.val_zero, pow_zero, one_zsmul] rw [δ, Γ₀.Obj.mapMono_on_summand_id_assoc, Γ₀.Obj.Termwise.mapMono_δ₀, Splitting.cofan_inj_πSummand_eq_id] dsimp only [Γ₀.splitting, Splitting.summand.eq_1, Splitting.IndexSet.id_fst] rw [comp_id] · intro i hi dsimp simp only [Preadditive.zsmul_comp, Preadditive.comp_zsmul] rw [δ, Γ₀.Obj.mapMono_on_summand_id_assoc, Γ₀.Obj.Termwise.mapMono_eq_zero, zero_comp, zsmul_zero] · intro h replace h := congr_arg SimplexCategory.len h change n + 1 = n at h omega · simpa only [Isδ₀.iff] using hi) /-- The natural isomorphism `(Γ₀.splitting K).nondegComplex ≅ K` for `K : ChainComplex C ℕ`. -/ def Γ₀'CompNondegComplexFunctor : Γ₀' ⋙ Split.nondegComplexFunctor ≅ 𝟭 (ChainComplex C ℕ) := NatIso.ofComponents Γ₀NondegComplexIso /-- The natural isomorphism `Γ₀ ⋙ N₁ ≅ toKaroubi (ChainComplex C ℕ)`. -/ def N₁Γ₀ : Γ₀ ⋙ N₁ ≅ toKaroubi (ChainComplex C ℕ) := calc Γ₀ ⋙ N₁ ≅ Γ₀' ⋙ Split.forget C ⋙ N₁ := Functor.associator _ _ _ _ ≅ Γ₀' ⋙ Split.nondegComplexFunctor ⋙ toKaroubi _ := (isoWhiskerLeft Γ₀' Split.toKaroubiNondegComplexFunctorIsoN₁.symm) _ ≅ (Γ₀' ⋙ Split.nondegComplexFunctor) ⋙ toKaroubi _ := (Functor.associator _ _ _).symm _ ≅ 𝟭 _ ⋙ toKaroubi (ChainComplex C ℕ) := isoWhiskerRight Γ₀'CompNondegComplexFunctor _ _ ≅ toKaroubi (ChainComplex C ℕ) := Functor.leftUnitor _ theorem N₁Γ₀_app (K : ChainComplex C ℕ) : N₁Γ₀.app K = (Γ₀.splitting K).toKaroubiNondegComplexIsoN₁.symm ≪≫ (toKaroubi _).mapIso (Γ₀NondegComplexIso K) := by ext1 dsimp [N₁Γ₀] erw [id_comp, comp_id, comp_id] rfl theorem N₁Γ₀_hom_app (K : ChainComplex C ℕ) : N₁Γ₀.hom.app K = (Γ₀.splitting K).toKaroubiNondegComplexIsoN₁.inv ≫ (toKaroubi _).map (Γ₀NondegComplexIso K).hom := by change (N₁Γ₀.app K).hom = _ simp only [N₁Γ₀_app] rfl theorem N₁Γ₀_inv_app (K : ChainComplex C ℕ) : N₁Γ₀.inv.app K = (toKaroubi _).map (Γ₀NondegComplexIso K).inv ≫ (Γ₀.splitting K).toKaroubiNondegComplexIsoN₁.hom := by change (N₁Γ₀.app K).inv = _ simp only [N₁Γ₀_app] rfl @[simp] theorem N₁Γ₀_hom_app_f_f (K : ChainComplex C ℕ) (n : ℕ) : (N₁Γ₀.hom.app K).f.f n = (Γ₀.splitting K).toKaroubiNondegComplexIsoN₁.inv.f.f n := by rw [N₁Γ₀_hom_app] apply comp_id @[simp] theorem N₁Γ₀_inv_app_f_f (K : ChainComplex C ℕ) (n : ℕ) : (N₁Γ₀.inv.app K).f.f n = (Γ₀.splitting K).toKaroubiNondegComplexIsoN₁.hom.f.f n := by rw [N₁Γ₀_inv_app] apply id_comp /-- Compatibility isomorphism between `toKaroubi _ ⋙ Γ₂ ⋙ N₂` and `Γ₀ ⋙ N₁` which are functors `ChainComplex C ℕ ⥤ Karoubi (ChainComplex C ℕ)`. -/ def N₂Γ₂ToKaroubiIso : toKaroubi (ChainComplex C ℕ) ⋙ Γ₂ ⋙ N₂ ≅ Γ₀ ⋙ N₁ := calc toKaroubi (ChainComplex C ℕ) ⋙ Γ₂ ⋙ N₂ ≅ toKaroubi (ChainComplex C ℕ) ⋙ (Γ₂ ⋙ N₂) := (Functor.associator _ _ _).symm _ ≅ (Γ₀ ⋙ toKaroubi (SimplicialObject C)) ⋙ N₂ := isoWhiskerRight ((functorExtension₂CompWhiskeringLeftToKaroubiIso _ _).app Γ₀) N₂ _ ≅ Γ₀ ⋙ toKaroubi (SimplicialObject C) ⋙ N₂ := Functor.associator _ _ _ _ ≅ Γ₀ ⋙ N₁ := isoWhiskerLeft Γ₀ ((functorExtension₁CompWhiskeringLeftToKaroubiIso _ _).app N₁) @[simp] lemma N₂Γ₂ToKaroubiIso_hom_app (X : ChainComplex C ℕ) : (N₂Γ₂ToKaroubiIso.hom.app X).f = PInfty := by ext n dsimp [N₂Γ₂ToKaroubiIso] simp only [comp_id, assoc, PInfty_f_idem] conv_rhs => rw [← PInfty_f_idem] congr 1 apply (Γ₀.splitting X).hom_ext' intro A rw [Splitting.ι_desc_assoc, assoc] apply id_comp @[simp] lemma N₂Γ₂ToKaroubiIso_inv_app (X : ChainComplex C ℕ) : (N₂Γ₂ToKaroubiIso.inv.app X).f = PInfty := by ext n dsimp [N₂Γ₂ToKaroubiIso] simp only [comp_id, PInfty_f_idem_assoc, AlternatingFaceMapComplex.obj_X, Γ₀_obj_obj] convert comp_id _ apply (Γ₀.splitting X).hom_ext' intro A rw [Splitting.ι_desc] erw [comp_id, id_comp] /-- The counit isomorphism of the Dold-Kan equivalence for additive categories. -/ def N₂Γ₂ : Γ₂ ⋙ N₂ ≅ 𝟭 (Karoubi (ChainComplex C ℕ)) := ((whiskeringLeft _ _ _).obj (toKaroubi (ChainComplex C ℕ))).preimageIso (N₂Γ₂ToKaroubiIso ≪≫ N₁Γ₀) @[simp] theorem N₂Γ₂_inv_app_f_f (X : Karoubi (ChainComplex C ℕ)) (n : ℕ) : (N₂Γ₂.inv.app X).f.f n = X.p.f n ≫ ((Γ₀.splitting X.X).cofan _).inj (Splitting.IndexSet.id (op ⦋n⦌)) := by dsimp [N₂Γ₂] simp only [whiskeringLeft_obj_preimage_app, NatTrans.comp_app, Functor.comp_map, Karoubi.comp_f, N₂Γ₂ToKaroubiIso_inv_app, HomologicalComplex.comp_f, N₁Γ₀_inv_app_f_f, toKaroubi_obj_X, Splitting.toKaroubiNondegComplexIsoN₁_hom_f_f, PInfty_on_Γ₀_splitting_summand_eq_self, N₂_map_f_f, Γ₂_map_f_app, unop_op, Karoubi.decompId_p_f, PInfty_on_Γ₀_splitting_summand_eq_self_assoc, Splitting.IndexSet.id_fst, SimplexCategory.len_mk, Splitting.ι_desc] apply Karoubi.HomologicalComplex.p_idem_assoc lemma whiskerLeft_toKaroubi_N₂Γ₂_hom : whiskerLeft (toKaroubi (ChainComplex C ℕ)) N₂Γ₂.hom = N₂Γ₂ToKaroubiIso.hom ≫ N₁Γ₀.hom := by let e : _ ≅ toKaroubi (ChainComplex C ℕ) ⋙ 𝟭 _ := N₂Γ₂ToKaroubiIso ≪≫ N₁Γ₀ have h := ((whiskeringLeft _ _ (Karoubi (ChainComplex C ℕ))).obj (toKaroubi (ChainComplex C ℕ))).map_preimage e.hom dsimp only [whiskeringLeft, N₂Γ₂, Functor.preimageIso] at h ⊢ exact h theorem N₂Γ₂_compatible_with_N₁Γ₀ (K : ChainComplex C ℕ) : N₂Γ₂.hom.app ((toKaroubi _).obj K) = N₂Γ₂ToKaroubiIso.hom.app K ≫ N₁Γ₀.hom.app K := congr_app whiskerLeft_toKaroubi_N₂Γ₂_hom K end DoldKan end AlgebraicTopology
FiniteMultiequalizer.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.CategoryTheory.FinCategory.Basic import Mathlib.CategoryTheory.Limits.Shapes.Multiequalizer import Mathlib.Tactic.DeriveFintype /-! # Finiteness instances on multi-spans -/ namespace CategoryTheory.Limits namespace WalkingMulticospan variable {J : MulticospanShape} [Fintype J.L] [Fintype J.R] instance : Fintype (WalkingMulticospan J) := .ofEquiv _ (proxy_equiv% (WalkingMulticospan J)) instance [DecidableEq J.L] [DecidableEq J.R] : FinCategory (WalkingMulticospan J) where fintypeHom | .left a, .left b => ⟨if e : a = b then {eqToHom (e ▸ rfl)} else ∅, by rintro ⟨⟩; simp⟩ | .left a, .right b => ⟨⟨(if e : J.fst b = a then {eqToHom (e ▸ rfl) ≫ Hom.fst b} else 0) + (if e : J.snd b = a then {eqToHom (e ▸ rfl) ≫ Hom.snd b} else 0), by split_ifs with h₁ h₂ · simp only [Multiset.singleton_add, Multiset.nodup_cons, Multiset.mem_singleton, Multiset.nodup_singleton, and_true] let f : ((left a : WalkingMulticospan J) ⟶ right b) → Prop | .fst a => True | .snd a => False apply ne_of_apply_ne f conv_lhs => tactic => subst h₁; simp only [eqToHom_refl, Category.id_comp, f] conv_rhs => tactic => subst h₂; simp only [eqToHom_refl, Category.id_comp, f] simp all_goals simp⟩, by rintro ⟨⟩ <;> simp⟩ | .right a, .left b => ⟨∅, by rintro ⟨⟩⟩ | .right a, .right b => ⟨if e : a = b then {eqToHom (e ▸ rfl)} else ∅, by rintro ⟨⟩; simp⟩ end WalkingMulticospan namespace WalkingMultispan variable {J : MultispanShape} [Fintype J.L] [Fintype J.R] instance : Fintype (WalkingMultispan J) := .ofEquiv _ (proxy_equiv% (WalkingMultispan J)) instance [DecidableEq J.L] [DecidableEq J.R] : FinCategory (WalkingMultispan J) where fintypeHom | .left a, .left b => ⟨if e : a = b then {eqToHom (e ▸ rfl)} else ∅, by rintro ⟨⟩; simp⟩ | .left a, .right b => ⟨⟨(if e : J.fst a = b then {Hom.fst a ≫ eqToHom (e ▸ rfl)} else 0) + (if e : J.snd a = b then {Hom.snd a ≫ eqToHom (e ▸ rfl)} else 0), by split_ifs with h₁ h₂ · simp only [Multiset.singleton_add, Multiset.nodup_cons, Multiset.mem_singleton, Multiset.nodup_singleton, and_true] let f : ((left a : WalkingMultispan J) ⟶ right b) → Prop | .fst a => True | .snd a => False apply ne_of_apply_ne f conv_lhs => tactic => subst h₁; simp only [eqToHom_refl, f] conv_rhs => tactic => subst h₂; simp only [eqToHom_refl, f] simp all_goals simp⟩, by rintro ⟨⟩ <;> simp⟩ | .right a, .left b => ⟨∅, by rintro ⟨⟩⟩ | .right a, .right b => ⟨if e : a = b then {eqToHom (e ▸ rfl)} else ∅, by rintro ⟨⟩; simp⟩ end WalkingMultispan end CategoryTheory.Limits
ConjAct.lean
/- Copyright (c) 2024 Antoine Chambert-Loir. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Antoine Chambert-Loir -/ import Mathlib.Algebra.Group.Action.Pointwise.Finset import Mathlib.GroupTheory.Perm.Cycle.Factors /-! # Some lemmas pertaining to the action of `ConjAct (Perm α)` on `Perm α` We prove some lemmas related to the action of `ConjAct (Perm α)` on `Perm α`: Let `α` be a decidable fintype. * `conj_support_eq` relates the support of `k • g` with that of `g` * `cycleFactorsFinset_conj_eq`, `mem_cycleFactorsFinset_conj'` and `cycleFactorsFinset_conj` relate the set of cycles of `g`, `g.cycleFactorsFinset`, with that for `k • g` -/ namespace Equiv.Perm open scoped Pointwise variable {α : Type*} [DecidableEq α] [Fintype α] /-- `a : α` belongs to the support of `k • g` iff `k⁻¹ * a` belongs to the support of `g` -/ theorem mem_conj_support (k : ConjAct (Perm α)) (g : Perm α) (a : α) : a ∈ (k • g).support ↔ ConjAct.ofConjAct k⁻¹ a ∈ g.support := by simp only [mem_support, ConjAct.smul_def, not_iff_not, coe_mul, Function.comp_apply, ConjAct.ofConjAct_inv] apply Equiv.apply_eq_iff_eq_symm_apply theorem cycleFactorsFinset_conj (g k : Perm α) : (ConjAct.toConjAct k • g).cycleFactorsFinset = Finset.map (MulAut.conj k).toEquiv.toEmbedding g.cycleFactorsFinset := by ext c rw [ConjAct.smul_def, ConjAct.ofConjAct_toConjAct, Finset.mem_map_equiv, ← mem_cycleFactorsFinset_conj g k] -- We avoid `group` here to minimize imports while low in the hierarchy; -- typically it would be better to invoke the tactic. simp [mul_assoc] /-- A permutation `c` is a cycle of `g` iff `k • c` is a cycle of `k • g` -/ @[simp] theorem mem_cycleFactorsFinset_conj' (k : ConjAct (Perm α)) (g c : Perm α) : k • c ∈ (k • g).cycleFactorsFinset ↔ c ∈ g.cycleFactorsFinset := by simp only [ConjAct.smul_def] apply mem_cycleFactorsFinset_conj g k theorem cycleFactorsFinset_conj_eq (k : ConjAct (Perm α)) (g : Perm α) : cycleFactorsFinset (k • g) = k • cycleFactorsFinset g := by ext c rw [← mem_cycleFactorsFinset_conj' k⁻¹ (k • g) c] simp only [inv_smul_smul] exact Finset.inv_smul_mem_iff end Equiv.Perm
Verschiebung.lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.RingTheory.WittVector.Basic import Mathlib.RingTheory.WittVector.IsPoly /-! ## The Verschiebung operator ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ namespace WittVector open MvPolynomial variable {p : ℕ} {R S : Type*} [CommRing R] [CommRing S] local notation "𝕎" => WittVector p -- type as `\bbW` noncomputable section /-- `verschiebungFun x` shifts the coefficients of `x` up by one, by inserting 0 as the 0th coefficient. `x.coeff i` then becomes `(verchiebungFun x).coeff (i + 1)`. `verschiebungFun` is the underlying function of the additive monoid hom `WittVector.verschiebung`. -/ def verschiebungFun (x : 𝕎 R) : 𝕎 R := @mk' p _ fun n => if n = 0 then 0 else x.coeff (n - 1) theorem verschiebungFun_coeff (x : 𝕎 R) (n : ℕ) : (verschiebungFun x).coeff n = if n = 0 then 0 else x.coeff (n - 1) := by simp only [verschiebungFun] theorem verschiebungFun_coeff_zero (x : 𝕎 R) : (verschiebungFun x).coeff 0 = 0 := by rw [verschiebungFun_coeff, if_pos rfl] @[simp] theorem verschiebungFun_coeff_succ (x : 𝕎 R) (n : ℕ) : (verschiebungFun x).coeff n.succ = x.coeff n := rfl @[ghost_simps] theorem ghostComponent_zero_verschiebungFun [hp : Fact p.Prime] (x : 𝕎 R) : ghostComponent 0 (verschiebungFun x) = 0 := by rw [ghostComponent_apply, aeval_wittPolynomial, Finset.range_one, Finset.sum_singleton, verschiebungFun_coeff_zero, pow_zero, pow_zero, pow_one, one_mul] @[ghost_simps] theorem ghostComponent_verschiebungFun [hp : Fact p.Prime] (x : 𝕎 R) (n : ℕ) : ghostComponent (n + 1) (verschiebungFun x) = p * ghostComponent n x := by simp only [ghostComponent_apply, aeval_wittPolynomial] rw [Finset.sum_range_succ', verschiebungFun_coeff, if_pos rfl, zero_pow (pow_ne_zero _ hp.1.ne_zero), mul_zero, add_zero, Finset.mul_sum, Finset.sum_congr rfl] rintro i - simp only [pow_succ', verschiebungFun_coeff_succ, Nat.succ_sub_succ_eq_sub, mul_assoc] /-- The 0th Verschiebung polynomial is 0. For `n > 0`, the `n`th Verschiebung polynomial is the variable `X (n-1)`. -/ def verschiebungPoly (n : ℕ) : MvPolynomial ℕ ℤ := if n = 0 then 0 else X (n - 1) @[simp] theorem verschiebungPoly_zero : verschiebungPoly 0 = 0 := rfl theorem aeval_verschiebung_poly' (x : 𝕎 R) (n : ℕ) : aeval x.coeff (verschiebungPoly n) = (verschiebungFun x).coeff n := by rcases n with - | n · simp only [verschiebungPoly, ite_true, map_zero, verschiebungFun_coeff_zero] · rw [verschiebungPoly, verschiebungFun_coeff_succ, if_neg n.succ_ne_zero, aeval_X, add_tsub_cancel_right] variable (p) /-- `WittVector.verschiebung` has polynomial structure given by `WittVector.verschiebungPoly`. -/ instance verschiebungFun_isPoly : IsPoly p fun R _Rcr => @verschiebungFun p R _Rcr := by use verschiebungPoly simp only [aeval_verschiebung_poly', forall₃_true_iff] -- We add this example as a verification that Lean 4's instance resolution can handle the `IsPoly` -- typeclass, whereas Lean 3 needed a bespoke `@[is_poly]` attribute. example (p : ℕ) (f : ⦃R : Type _⦄ → [CommRing R] → WittVector p R → WittVector p R) [IsPoly p f] : IsPoly p (fun (R : Type*) (I : CommRing R) ↦ verschiebungFun ∘ (@f R I)) := inferInstance variable {p} variable [hp : Fact p.Prime] /-- `verschiebung x` shifts the coefficients of `x` up by one, by inserting 0 as the 0th coefficient. `x.coeff i` then becomes `(verchiebung x).coeff (i + 1)`. This is an additive monoid hom with underlying function `verschiebung_fun`. -/ noncomputable def verschiebung : 𝕎 R →+ 𝕎 R where toFun := verschiebungFun map_zero' := by ext ⟨⟩ <;> rw [verschiebungFun_coeff] <;> simp only [zero_coeff, ite_self] map_add' := by ghost_calc _ _ rintro ⟨⟩ <;> ghost_simp /-- `WittVector.verschiebung` is a polynomial function. -/ @[is_poly] theorem verschiebung_isPoly : IsPoly p fun _ _ => verschiebung (p := p) := verschiebungFun_isPoly p /-- verschiebung is a natural transformation -/ @[simp] theorem map_verschiebung (f : R →+* S) (x : 𝕎 R) : map f (verschiebung x) = verschiebung (map f x) := by ext ⟨-, -⟩ · exact f.map_zero · rfl @[ghost_simps] theorem ghostComponent_zero_verschiebung (x : 𝕎 R) : ghostComponent 0 (verschiebung x) = 0 := ghostComponent_zero_verschiebungFun _ @[ghost_simps] theorem ghostComponent_verschiebung (x : 𝕎 R) (n : ℕ) : ghostComponent (n + 1) (verschiebung x) = p * ghostComponent n x := ghostComponent_verschiebungFun _ _ @[simp] theorem verschiebung_coeff_zero (x : 𝕎 R) : (verschiebung x).coeff 0 = 0 := rfl -- simp_nf complains if this is simp theorem verschiebung_coeff_add_one (x : 𝕎 R) (n : ℕ) : (verschiebung x).coeff (n + 1) = x.coeff n := rfl @[simp] theorem verschiebung_coeff_succ (x : 𝕎 R) (n : ℕ) : (verschiebung x).coeff n.succ = x.coeff n := rfl variable (p R) in theorem verschiebung_injective : Function.Injective (verschiebung : 𝕎 R → 𝕎 R) := by rw [injective_iff_map_eq_zero] intro w h ext n rw [← verschiebung_coeff_succ, h] simp only [zero_coeff] theorem aeval_verschiebungPoly (x : 𝕎 R) (n : ℕ) : aeval x.coeff (verschiebungPoly n) = (verschiebung x).coeff n := aeval_verschiebung_poly' x n @[simp] theorem bind₁_verschiebungPoly_wittPolynomial (n : ℕ) : bind₁ verschiebungPoly (wittPolynomial p ℤ n) = if n = 0 then 0 else p * wittPolynomial p ℤ (n - 1) := by apply MvPolynomial.funext intro x split_ifs with hn · simp only [hn, wittPolynomial_zero, bind₁_X_right, verschiebungPoly_zero, map_zero] · obtain ⟨n, rfl⟩ := Nat.exists_eq_succ_of_ne_zero hn rw [Nat.succ_eq_add_one, add_tsub_cancel_right] simp only [map_mul] rw [map_natCast, hom_bind₁] calc _ = ghostComponent (n + 1) (verschiebung <| mk p x) := by apply eval₂Hom_congr (RingHom.ext_int _ _) _ rfl funext k simp only [← aeval_verschiebungPoly] exact eval₂Hom_congr (RingHom.ext_int _ _) rfl rfl _ = _ := by rw [ghostComponent_verschiebung]; rfl end end WittVector
CompletelyMetrizable.lean
/- Copyright (c) 2025 Etienne Marion. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Etienne Marion -/ import Mathlib.Topology.MetricSpace.Gluing import Mathlib.Topology.Metrizable.Uniformity /-! # Completely metrizable spaces A topological space is completely metrizable if one can endow it mith a `MetricSpace` structure which makes it complete and gives the same topology. This typeclass allows to state theorems which do not require a `MetricSpace` structure to make sense without introducing such a structure. It is in particular useful in measure theory, where one often assumes that a space is a `PolishSpace`, i.e. a separable and completely metrizable space. Sometimes the separability hypothesis is not needed and the right assumption is then `IsCompletelyMetrizableSpace`. ## Main definition * `IsCompletelyMetrizableSpace X`: A topological space is completely metrizable if there exists a metric space structure compatible with the topology which makes the space complete. To endow such a space with a compatible distance, use `letI := upgradeIsCompletelyMetrizable X`. ## Implementation note Given a `IsCompletelyMetrizableSpace X` instance, one may want to endow `X` with a complete metric. This can be done by writing `letI := upgradeIsCompletelyMetrizable X`, which will endow `X` with an `UpgradedIsCompletelyMetrizableSpace X` instance. This class is a convenience class and no instance should be registered for it. -/ open Filter Function Set Topology variable {X Y : Type*} namespace TopologicalSpace /-- A topological space is completely metrizable if there exists a metric space structure compatible with the topology which makes the space complete. To endow such a space with a compatible distance, use `letI := upgradeIsCompletelyMetrizable X`. -/ class IsCompletelyMetrizableSpace (X : Type*) [t : TopologicalSpace X] : Prop where complete : ∃ m : MetricSpace X, m.toUniformSpace.toTopologicalSpace = t ∧ @CompleteSpace X m.toUniformSpace instance (priority := 100) _root_.MetricSpace.toIsCompletelyMetrizableSpace [MetricSpace X] [CompleteSpace X] : IsCompletelyMetrizableSpace X := ⟨⟨‹_›, rfl, ‹_›⟩⟩ /-- A convenience class, for a completely metrizable space endowed with a complete metric. No instance of this class should be registered: It should be used as `letI := upgradeIsCompletelyMetrizable X` to endow a completely metrizable space with a complete metric. -/ class UpgradedIsCompletelyMetrizableSpace (X : Type*) extends MetricSpace X, CompleteSpace X open scoped Uniformity in instance (priority := 100) IsCompletelyMetrizableSpace.of_completeSpace_metrizable [UniformSpace X] [CompleteSpace X] [(𝓤 X).IsCountablyGenerated] [T0Space X] : IsCompletelyMetrizableSpace X where complete := ⟨UniformSpace.metricSpace X, rfl, ‹_›⟩ /-- Construct on a completely metrizable space a metric (compatible with the topology) which is complete. -/ noncomputable def completelyMetrizableMetric (X : Type*) [TopologicalSpace X] [h : IsCompletelyMetrizableSpace X] : MetricSpace X := h.complete.choose.replaceTopology h.complete.choose_spec.1.symm theorem complete_completelyMetrizableMetric (X : Type*) [ht : TopologicalSpace X] [h : IsCompletelyMetrizableSpace X] : @CompleteSpace X (completelyMetrizableMetric X).toUniformSpace := by convert h.complete.choose_spec.2 exact MetricSpace.replaceTopology_eq _ _ /-- This definition endows a completely metrizable space with a complete metric. Use it as: `letI := upgradeIsCompletelyMetrizable X`. -/ noncomputable def upgradeIsCompletelyMetrizable (X : Type*) [TopologicalSpace X] [IsCompletelyMetrizableSpace X] : UpgradedIsCompletelyMetrizableSpace X := letI := completelyMetrizableMetric X { complete_completelyMetrizableMetric X with } namespace IsCompletelyMetrizableSpace /-- Note: the priority is set to 90 to ensure that this instance is only applied after `EMetricSpace.metrizableSpace`. This prevents unnecessary attempts to infer completeness. -/ instance (priority := 90) MetrizableSpace [TopologicalSpace X] [IsCompletelyMetrizableSpace X] : MetrizableSpace X := by letI := upgradeIsCompletelyMetrizable X infer_instance /-- A countable product of completely metrizable spaces is completely metrizable. -/ instance pi_countable {ι : Type*} [Countable ι] {X : ι → Type*} [∀ i, TopologicalSpace (X i)] [∀ i, IsCompletelyMetrizableSpace (X i)] : IsCompletelyMetrizableSpace (Π i, X i) := by letI := fun i ↦ upgradeIsCompletelyMetrizable (X i) infer_instance /-- A disjoint union of completely metrizable spaces is completely metrizable. -/ instance sigma {ι : Type*} {X : ι → Type*} [∀ n, TopologicalSpace (X n)] [∀ n, IsCompletelyMetrizableSpace (X n)] : IsCompletelyMetrizableSpace (Σ n, X n) := letI := fun n ↦ upgradeIsCompletelyMetrizable (X n) letI : MetricSpace (Σ n, X n) := Metric.Sigma.metricSpace haveI : CompleteSpace (Σ n, X n) := Metric.Sigma.completeSpace inferInstance /-- The product of two completely metrizable spaces is completely metrizable. -/ instance prod [TopologicalSpace X] [IsCompletelyMetrizableSpace X] [TopologicalSpace Y] [IsCompletelyMetrizableSpace Y] : IsCompletelyMetrizableSpace (X × Y) := letI := upgradeIsCompletelyMetrizable X letI := upgradeIsCompletelyMetrizable Y inferInstance /-- The disjoint union of two completely metrizable spaces is completely metrizable. -/ instance sum [TopologicalSpace X] [IsCompletelyMetrizableSpace X] [TopologicalSpace Y] [IsCompletelyMetrizableSpace Y] : IsCompletelyMetrizableSpace (X ⊕ Y) := letI := upgradeIsCompletelyMetrizable X letI := upgradeIsCompletelyMetrizable Y inferInstance /-- Given a closed embedding into a completely metrizable space, the source space is also completely metrizable. -/ theorem _root_.Topology.IsClosedEmbedding.IsCompletelyMetrizableSpace [TopologicalSpace X] [TopologicalSpace Y] [IsCompletelyMetrizableSpace Y] {f : X → Y} (hf : IsClosedEmbedding f) : IsCompletelyMetrizableSpace X := by letI := upgradeIsCompletelyMetrizable Y letI : MetricSpace X := hf.isEmbedding.comapMetricSpace f have : CompleteSpace X := by rw [completeSpace_iff_isComplete_range hf.isEmbedding.to_isometry.isUniformInducing] exact hf.isClosed_range.isComplete infer_instance /-- Any discrete space is completely metrizable. -/ instance (priority := 50) discrete [TopologicalSpace X] [DiscreteTopology X] : IsCompletelyMetrizableSpace X := by classical let m : MetricSpace X := { dist x y := if x = y then 0 else 1 dist_self x := by simp dist_comm x y := by obtain h | h := eq_or_ne x y · simp [h] · simp [h, h.symm] dist_triangle x y z := by by_cases x = y <;> by_cases x = z <;> by_cases y = z <;> simp_all eq_of_dist_eq_zero := by simp } refine ⟨m, ?_, ?_⟩ · rw [DiscreteTopology.eq_bot (α := X)] refine eq_bot_of_singletons_open fun x ↦ ?_ convert @Metric.isOpen_ball _ _ x 1 refine subset_antisymm (singleton_subset_iff.2 (Metric.mem_ball_self (by simp))) fun y hy ↦ ?_ simp only [Metric.mem_ball, mem_singleton_iff] at * by_contra change (if y = x then 0 else 1) < 1 at hy simp_all · refine Metric.complete_of_cauchySeq_tendsto fun u hu ↦ ?_ rw [Metric.cauchySeq_iff'] at hu obtain ⟨N, hN⟩ := hu 1 (by simp) refine ⟨u N, @tendsto_atTop_of_eventually_const X UniformSpace.toTopologicalSpace (u N) _ _ _ N fun n hn ↦ ?_⟩ specialize hN n hn by_contra change (if u n = u N then 0 else 1) < 1 at hN simp_all /-- A closed subset of a completely metrizable space is also completely metrizable. -/ theorem _root_.IsClosed.isCompletelyMetrizableSpace [TopologicalSpace X] [IsCompletelyMetrizableSpace X] {s : Set X} (hs : IsClosed s) : IsCompletelyMetrizableSpace s := hs.isClosedEmbedding_subtypeVal.IsCompletelyMetrizableSpace instance univ [TopologicalSpace X] [IsCompletelyMetrizableSpace X] : IsCompletelyMetrizableSpace (univ : Set X) := isClosed_univ.isCompletelyMetrizableSpace end IsCompletelyMetrizableSpace end TopologicalSpace
Spectrum.lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import Mathlib.Analysis.InnerProductSpace.Rayleigh import Mathlib.Analysis.InnerProductSpace.PiL2 import Mathlib.Algebra.DirectSum.Decomposition import Mathlib.LinearAlgebra.Eigenspace.Minpoly import Mathlib.Data.Fin.Tuple.Sort /-! # Spectral theory of self-adjoint operators This file covers the spectral theory of self-adjoint operators on an inner product space. The first part of the file covers general properties, true without any condition on boundedness or compactness of the operator or finite-dimensionality of the underlying space, notably: * `LinearMap.IsSymmetric.conj_eigenvalue_eq_self`: the eigenvalues are real * `LinearMap.IsSymmetric.orthogonalFamily_eigenspaces`: the eigenspaces are orthogonal * `LinearMap.IsSymmetric.orthogonalComplement_iSup_eigenspaces`: the restriction of the operator to the mutual orthogonal complement of the eigenspaces has, itself, no eigenvectors The second part of the file covers properties of self-adjoint operators in finite dimension. Letting `T` be a self-adjoint operator on a finite-dimensional inner product space `T`, * The definition `LinearMap.IsSymmetric.diagonalization` provides a linear isometry equivalence `E` to the direct sum of the eigenspaces of `T`. The theorem `LinearMap.IsSymmetric.diagonalization_apply_self_apply` states that, when `T` is transferred via this equivalence to an operator on the direct sum, it acts diagonally. * The definition `LinearMap.IsSymmetric.eigenvectorBasis` provides an orthonormal basis for `E` consisting of eigenvectors of `T`, with `LinearMap.IsSymmetric.eigenvalues` giving the corresponding list of eigenvalues, as real numbers. The definition `LinearMap.IsSymmetric.eigenvectorBasis` gives the associated linear isometry equivalence from `E` to Euclidean space, and the theorem `LinearMap.IsSymmetric.eigenvectorBasis_apply_self_apply` states that, when `T` is transferred via this equivalence to an operator on Euclidean space, it acts diagonally. * `LinearMap.IsSymmetric.eigenvalues` gives the eigenvalues in decreasing order. This is done for several reasons: (i) This agrees with the standard convention of listing singular values in decreasing order, with the operator norm as the first singular value (ii) For positive compact operators on an infinite dimensional space, one can list the nonzero eigenvalues in decreasing (but not increasing) order since they converge to zero. (iii) This simplifies several theorem statements. For example the Schur-Horn theorem states that the diagonal of the matrix representation of a selfadjoint linear map is majorized by the eigenvalue sequence listed in decreasing order. These are forms of the *diagonalization theorem* for self-adjoint operators on finite-dimensional inner product spaces. ## TODO Spectral theory for compact self-adjoint operators, bounded self-adjoint operators. ## Tags self-adjoint operator, spectral theorem, diagonalization theorem -/ variable {𝕜 : Type*} [RCLike 𝕜] variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace 𝕜 E] local notation "⟪" x ", " y "⟫" => inner 𝕜 x y open scoped ComplexConjugate open Module.End namespace LinearMap namespace IsSymmetric variable {T : E →ₗ[𝕜] E} /-- A self-adjoint operator preserves orthogonal complements of its eigenspaces. -/ theorem invariant_orthogonalComplement_eigenspace (hT : T.IsSymmetric) (μ : 𝕜) (v : E) (hv : v ∈ (eigenspace T μ)ᗮ) : T v ∈ (eigenspace T μ)ᗮ := by intro w hw have : T w = (μ : 𝕜) • w := by rwa [mem_eigenspace_iff] at hw simp [← hT w, this, inner_smul_left, hv w hw] /-- The eigenvalues of a self-adjoint operator are real. -/ theorem conj_eigenvalue_eq_self (hT : T.IsSymmetric) {μ : 𝕜} (hμ : HasEigenvalue T μ) : conj μ = μ := by obtain ⟨v, hv₁, hv₂⟩ := hμ.exists_hasEigenvector rw [mem_eigenspace_iff] at hv₁ simpa [hv₂, inner_smul_left, inner_smul_right, hv₁] using hT v v /-- The eigenspaces of a self-adjoint operator are mutually orthogonal. -/ theorem orthogonalFamily_eigenspaces (hT : T.IsSymmetric) : OrthogonalFamily 𝕜 (fun μ => eigenspace T μ) fun μ => (eigenspace T μ).subtypeₗᵢ := by rintro μ ν hμν ⟨v, hv⟩ ⟨w, hw⟩ by_cases hv' : v = 0 · simp [hv'] have H := hT.conj_eigenvalue_eq_self (hasEigenvalue_of_hasEigenvector ⟨hv, hv'⟩) rw [mem_eigenspace_iff] at hv hw refine Or.resolve_left ?_ hμν.symm simpa [inner_smul_left, inner_smul_right, hv, hw, H] using (hT v w).symm theorem orthogonalFamily_eigenspaces' (hT : T.IsSymmetric) : OrthogonalFamily 𝕜 (fun μ : Eigenvalues T => eigenspace T μ) fun μ => (eigenspace T μ).subtypeₗᵢ := hT.orthogonalFamily_eigenspaces.comp Subtype.coe_injective /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on an inner product space is an invariant subspace of the operator. -/ theorem orthogonalComplement_iSup_eigenspaces_invariant (hT : T.IsSymmetric) ⦃v : E⦄ (hv : v ∈ (⨆ μ, eigenspace T μ)ᗮ) : T v ∈ (⨆ μ, eigenspace T μ)ᗮ := by rw [← Submodule.iInf_orthogonal] at hv ⊢ exact T.iInf_invariant hT.invariant_orthogonalComplement_eigenspace v hv /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on an inner product space has no eigenvalues. -/ theorem orthogonalComplement_iSup_eigenspaces (hT : T.IsSymmetric) (μ : 𝕜) : eigenspace (T.restrict hT.orthogonalComplement_iSup_eigenspaces_invariant) μ = ⊥ := by set p : Submodule 𝕜 E := (⨆ μ, eigenspace T μ)ᗮ refine eigenspace_restrict_eq_bot hT.orthogonalComplement_iSup_eigenspaces_invariant ?_ have H₂ : eigenspace T μ ⟂ p := (Submodule.isOrtho_orthogonal_right _).mono_left (le_iSup _ _) exact H₂.disjoint /-! ### Finite-dimensional theory -/ variable [FiniteDimensional 𝕜 E] /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on a finite-dimensional inner product space is trivial. -/ theorem orthogonalComplement_iSup_eigenspaces_eq_bot (hT : T.IsSymmetric) : (⨆ μ, eigenspace T μ)ᗮ = ⊥ := by have hT' : IsSymmetric _ := hT.restrict_invariant hT.orthogonalComplement_iSup_eigenspaces_invariant -- a self-adjoint operator on a nontrivial inner product space has an eigenvalue haveI := hT'.subsingleton_of_no_eigenvalue_finiteDimensional hT.orthogonalComplement_iSup_eigenspaces exact Submodule.eq_bot_of_subsingleton theorem orthogonalComplement_iSup_eigenspaces_eq_bot' (hT : T.IsSymmetric) : (⨆ μ : Eigenvalues T, eigenspace T μ)ᗮ = ⊥ := show (⨆ μ : { μ // eigenspace T μ ≠ ⊥ }, eigenspace T μ)ᗮ = ⊥ by rw [iSup_ne_bot_subtype, hT.orthogonalComplement_iSup_eigenspaces_eq_bot] /-- The eigenspaces of a self-adjoint operator on a finite-dimensional inner product space `E` gives an internal direct sum decomposition of `E`. Note this takes `hT` as a `Fact` to allow it to be an instance. -/ noncomputable instance directSumDecomposition [hT : Fact T.IsSymmetric] : DirectSum.Decomposition fun μ : Eigenvalues T => eigenspace T μ := haveI h : ∀ μ : Eigenvalues T, CompleteSpace (eigenspace T μ) := fun μ => by infer_instance hT.out.orthogonalFamily_eigenspaces'.decomposition (Submodule.orthogonal_eq_bot_iff.mp hT.out.orthogonalComplement_iSup_eigenspaces_eq_bot') theorem directSum_decompose_apply [_hT : Fact T.IsSymmetric] (x : E) (μ : Eigenvalues T) : DirectSum.decompose (fun μ : Eigenvalues T => eigenspace T μ) x μ = (eigenspace T μ).orthogonalProjection x := rfl /-- The eigenspaces of a self-adjoint operator on a finite-dimensional inner product space `E` gives an internal direct sum decomposition of `E`. -/ theorem direct_sum_isInternal (hT : T.IsSymmetric) : DirectSum.IsInternal fun μ : Eigenvalues T => eigenspace T μ := hT.orthogonalFamily_eigenspaces'.isInternal_iff.mpr hT.orthogonalComplement_iSup_eigenspaces_eq_bot' section Version1 /-- Isometry from an inner product space `E` to the direct sum of the eigenspaces of some self-adjoint operator `T` on `E`. -/ noncomputable def diagonalization (hT : T.IsSymmetric) : E ≃ₗᵢ[𝕜] PiLp 2 fun μ : Eigenvalues T => eigenspace T μ := hT.direct_sum_isInternal.isometryL2OfOrthogonalFamily hT.orthogonalFamily_eigenspaces' @[simp] theorem diagonalization_symm_apply (hT : T.IsSymmetric) (w : PiLp 2 fun μ : Eigenvalues T => eigenspace T μ) : hT.diagonalization.symm w = ∑ μ, w μ := hT.direct_sum_isInternal.isometryL2OfOrthogonalFamily_symm_apply hT.orthogonalFamily_eigenspaces' w /-- *Diagonalization theorem*, *spectral theorem*; version 1: A self-adjoint operator `T` on a finite-dimensional inner product space `E` acts diagonally on the decomposition of `E` into the direct sum of the eigenspaces of `T`. -/ theorem diagonalization_apply_self_apply (hT : T.IsSymmetric) (v : E) (μ : Eigenvalues T) : hT.diagonalization (T v) μ = (μ : 𝕜) • hT.diagonalization v μ := by suffices ∀ w : PiLp 2 fun μ : Eigenvalues T => eigenspace T μ, T (hT.diagonalization.symm w) = hT.diagonalization.symm fun μ => (μ : 𝕜) • w μ by simpa only [LinearIsometryEquiv.symm_apply_apply, LinearIsometryEquiv.apply_symm_apply] using congr_arg (fun w => hT.diagonalization w μ) (this (hT.diagonalization v)) intro w have hwT : ∀ μ, T (w μ) = (μ : 𝕜) • w μ := fun μ => mem_eigenspace_iff.1 (w μ).2 simp only [hwT, diagonalization_symm_apply, map_sum, Submodule.coe_smul_of_tower] end Version1 section Version2 variable {n : ℕ} /-- Unsorted eigenvalues and eigenvectors. These private definitions should not be used directly. Instead use the functions eigenvalues and eigenvectorBasis defined below. -/ private noncomputable def unsortedEigenvalues (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (i : Fin n) : ℝ := @RCLike.re 𝕜 _ <| (hT.direct_sum_isInternal.subordinateOrthonormalBasisIndex hn i hT.orthogonalFamily_eigenspaces').val private noncomputable def unsortedEigenvectorBasis (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) : OrthonormalBasis (Fin n) 𝕜 E := hT.direct_sum_isInternal.subordinateOrthonormalBasis hn hT.orthogonalFamily_eigenspaces' private theorem hasEigenvector_eigenvectorBasis_helper (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (i : Fin n) : HasEigenvector T (hT.unsortedEigenvalues hn i) (hT.unsortedEigenvectorBasis hn i) := by let v : E := hT.unsortedEigenvectorBasis hn i let μ : 𝕜 := (hT.direct_sum_isInternal.subordinateOrthonormalBasisIndex hn i hT.orthogonalFamily_eigenspaces').val simp_rw [unsortedEigenvalues] change HasEigenvector T (RCLike.re μ) v have key : HasEigenvector T μ v := by have H₁ : v ∈ eigenspace T μ := by simp_rw [v, unsortedEigenvectorBasis] exact hT.direct_sum_isInternal.subordinateOrthonormalBasis_subordinate hn i hT.orthogonalFamily_eigenspaces' have H₂ : v ≠ 0 := by simpa using (hT.unsortedEigenvectorBasis hn).toBasis.ne_zero i exact ⟨H₁, H₂⟩ have re_μ : ↑(RCLike.re μ) = μ := by rw [← RCLike.conj_eq_iff_re] exact hT.conj_eigenvalue_eq_self (hasEigenvalue_of_hasEigenvector key) simpa [re_μ] using key /-- The eigenvalues for a self-adjoint operator `T` on a finite-dimensional inner product space `E`, sorted in decreasing order -/ noncomputable irreducible_def eigenvalues (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) : Fin n → ℝ := (hT.unsortedEigenvalues hn) ∘ Tuple.sort (hT.unsortedEigenvalues hn) ∘ @Fin.revPerm n /-- A choice of orthonormal basis of eigenvectors for self-adjoint operator `T` on a finite-dimensional inner product space `E`. Eigenvectors are sorted in decreasing order of their eigenvalues. -/ noncomputable irreducible_def eigenvectorBasis (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) : OrthonormalBasis (Fin n) 𝕜 E := (hT.direct_sum_isInternal.subordinateOrthonormalBasis hn hT.orthogonalFamily_eigenspaces').reindex (Tuple.sort (hT.unsortedEigenvalues hn) * @Fin.revPerm n).symm theorem hasEigenvector_eigenvectorBasis (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (i : Fin n) : HasEigenvector T (hT.eigenvalues hn i) (hT.eigenvectorBasis hn i) := by rw [eigenvalues_def, eigenvectorBasis_def, OrthonormalBasis.reindex_apply] apply hasEigenvector_eigenvectorBasis_helper /-- Eigenvalues are sorted in decreasing order. -/ theorem eigenvalues_antitone (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) : Antitone (hT.eigenvalues hn) := by rw [eigenvalues_def, ← Function.comp_assoc] refine Monotone.comp_antitone ?_ ?_ · apply Tuple.monotone_sort intro _ _ h exact Fin.rev_le_rev.mpr h theorem hasEigenvalue_eigenvalues (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (i : Fin n) : HasEigenvalue T (hT.eigenvalues hn i) := Module.End.hasEigenvalue_of_hasEigenvector (hT.hasEigenvector_eigenvectorBasis hn i) @[simp] theorem apply_eigenvectorBasis (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (i : Fin n) : T (hT.eigenvectorBasis hn i) = (hT.eigenvalues hn i : 𝕜) • hT.eigenvectorBasis hn i := mem_eigenspace_iff.mp (hT.hasEigenvector_eigenvectorBasis hn i).1 /-- *Diagonalization theorem*, *spectral theorem*; version 2: A self-adjoint operator `T` on a finite-dimensional inner product space `E` acts diagonally on the identification of `E` with Euclidean space induced by an orthonormal basis of eigenvectors of `T`. -/ theorem eigenvectorBasis_apply_self_apply (hT : T.IsSymmetric) (hn : Module.finrank 𝕜 E = n) (v : E) (i : Fin n) : (hT.eigenvectorBasis hn).repr (T v) i = hT.eigenvalues hn i * (hT.eigenvectorBasis hn).repr v i := by suffices ∀ w : EuclideanSpace 𝕜 (Fin n), T ((hT.eigenvectorBasis hn).repr.symm w) = (hT.eigenvectorBasis hn).repr.symm fun i => hT.eigenvalues hn i * w i by simpa [OrthonormalBasis.sum_repr_symm] using congr_arg (fun v => (hT.eigenvectorBasis hn).repr v i) (this ((hT.eigenvectorBasis hn).repr v)) intro w simp_rw [← OrthonormalBasis.sum_repr_symm, map_sum, map_smul, apply_eigenvectorBasis] apply Fintype.sum_congr intro a rw [smul_smul, mul_comm] end Version2 end IsSymmetric end LinearMap section Nonneg -- Cannot be @[simp] because the LHS is not in simp normal form theorem inner_product_apply_eigenvector {μ : 𝕜} {v : E} {T : E →ₗ[𝕜] E} (h : T v = μ • v) : ⟪v, T v⟫ = μ * (‖v‖ : 𝕜) ^ 2 := by simp only [h, inner_smul_right, inner_self_eq_norm_sq_to_K] theorem eigenvalue_nonneg_of_nonneg {μ : ℝ} {T : E →ₗ[𝕜] E} (hμ : HasEigenvalue T μ) (hnn : ∀ x : E, 0 ≤ RCLike.re ⟪x, T x⟫) : 0 ≤ μ := by obtain ⟨v, hv₁, hv₂⟩ := hμ.exists_hasEigenvector have hpos : (0 : ℝ) < ‖v‖ ^ 2 := by simpa only [sq_pos_iff, norm_ne_zero_iff] using hv₂ simp only [mem_genEigenspace_one] at hv₁ have : RCLike.re ⟪v, T v⟫ = μ * ‖v‖ ^ 2 := mod_cast congr_arg RCLike.re (inner_product_apply_eigenvector hv₁) exact (mul_nonneg_iff_of_pos_right hpos).mp (this ▸ hnn v) theorem eigenvalue_pos_of_pos {μ : ℝ} {T : E →ₗ[𝕜] E} (hμ : HasEigenvalue T μ) (hnn : ∀ x : E, 0 < RCLike.re ⟪x, T x⟫) : 0 < μ := by obtain ⟨v, hv₁, hv₂⟩ := hμ.exists_hasEigenvector have hpos : (0 : ℝ) < ‖v‖ ^ 2 := by simpa only [sq_pos_iff, norm_ne_zero_iff] using hv₂ simp only [mem_genEigenspace_one] at hv₁ have : RCLike.re ⟪v, T v⟫ = μ * ‖v‖ ^ 2 := mod_cast congr_arg RCLike.re (inner_product_apply_eigenvector hv₁) exact (mul_pos_iff_of_pos_right hpos).mp (this ▸ hnn v) end Nonneg
Indization.lean
/- Copyright (c) 2025 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import Mathlib.CategoryTheory.Preadditive.Indization import Mathlib.CategoryTheory.Abelian.FunctorCategory import Mathlib.CategoryTheory.Limits.Preserves.Shapes.AbelianImages /-! # The category of ind-objects is abelian We show that if `C` is a small abelian category, then `Ind C` is an abelian category. In the file `Mathlib/CategoryTheory/Abelian/GrothendieckAxioms/Indization.lean`, we show that in this situation `Ind C` is in fact Grothendieck abelian. -/ universe v open CategoryTheory.Abelian namespace CategoryTheory variable {C : Type v} [SmallCategory C] [Abelian C] instance {X Y : Ind C} (f : X ⟶ Y) : IsIso (Abelian.coimageImageComparison f) := by obtain ⟨I, _, _, F, G, ϕ, ⟨i⟩⟩ := Ind.exists_nonempty_arrow_mk_iso_ind_lim (f := f) let i' := coimageImageComparisonFunctor.mapIso i dsimp only [coimageImageComparisonFunctor_obj, Arrow.mk_left, Arrow.mk_right, Arrow.mk_hom] at i' have := Iso.isIso_hom i' rw [Arrow.isIso_iff_isIso_of_isIso i'.hom, Arrow.isIso_iff_isIso_of_isIso (PreservesCoimageImageComparison.iso (Ind.lim I) ϕ).inv] infer_instance noncomputable instance : Abelian (Ind C) := .ofCoimageImageComparisonIsIso end CategoryTheory
ProxyType.lean
/- Copyright (c) 2023 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import Mathlib.Tactic.Core import Mathlib.Logic.Equiv.Defs /-! # Generating "proxy types" This module gives tools to create an equivalence between a given inductive type and a "proxy type" constructed from `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. It works for any non-recursive inductive type without indices. The intended use case is for pulling typeclass instances across this equivalence. This reduces the problem of generating typeclass instances to that of writing typeclass instances for the above five types (and whichever additional types appear in the inductive type). The main interface is the `proxy_equiv%` elaborator, where `proxy_equiv% t` gives an equivalence between the proxy type for `t` and `t`. See the documentation for `proxy_equiv%` for an example. For debugging information, do `set_option Elab.ProxyType true`. It is possible to reconfigure the machinery to generate other types. See `ensureProxyEquiv` and look at how it is used in `proxy_equiv%`. ## Implementation notes For inductive types with `n` constructors, the `proxy_equiv%` elaborator creates a proxy type of the form `C₁ ⊕ (C₂ ⊕ (⋯ ⊕ Cₙ))`. The equivalence then needs to handle `n - 1` levels of `Sum` constructors, which is a source of quadratic complexity. An alternative design could be to generate a `C : Fin n → Type*` function for the proxy types for each constructor and then use `(i : Fin n) × ULift (C i)` for the total proxy type. However, typeclass inference is not good at finding instances for such a type even if there are instances for each `C i`. One seems to need to add, for example, an explicit `[∀ i, Fintype (C i)]` instance given `∀ i, Fintype (C i)`. -/ namespace Mathlib.ProxyType open Lean Elab Lean.Parser.Term open Meta Command initialize registerTraceClass `Elab.ProxyType /-- Configuration used by `mkProxyEquiv`. -/ structure ProxyEquivConfig where /-- Name to use for the declaration for a type that is `Equiv` to the given type. -/ proxyName : Name /-- Name to use for the declaration for the equivalence `proxyType ≃ type`. -/ proxyEquivName : Name /-- Returns a proxy type for a constructor and a pattern to use to match against it, given a list of fvars for the constructor arguments and pattern names to use for the arguments. The proxy type is expected to be a `Type*`. -/ mkCtorProxyType : List (Expr × Name) → TermElabM (Expr × Term) /-- Given (constructor name, proxy constructor type, proxy constructor pattern) triples constructed using `mkCtorProxyType`, return (1) the total proxy type (a `Type*`), (2) patterns to use for each constructor, and (3) a proof to use to prove `left_inv` for `proxy_type ≃ type` (this proof starts with `intro x`). -/ mkProxyType : Array (Name × Expr × Term) → TermElabM (Expr × Array Term × TSyntax `tactic) /-- Returns a proxy type for a constructor and a pattern to use to match against it. Input: a list of pairs associated to each argument of the constructor consisting of (1) an fvar for this argument and (2) a name to use for this argument in patterns. For example, given `#[(a, x), (b, y)]` with `x : Nat` and `y : Fin x`, then this function returns `Sigma (fun x => Fin x)` and `⟨a, b⟩`. Always returns a `Type*`. Uses `Unit`, `PLift`, and `Sigma`. Avoids using `PSigma` since the `Fintype` instances for it go through `Sigma`s anyway. The `decorateSigma` function is to wrap the `Sigma` a decorator such as `Lex`. It should yield a definitionally equal type. -/ def defaultMkCtorProxyType (xs : List (Expr × Name)) (decorateSigma : Expr → TermElabM Expr := pure) : TermElabM (Expr × Term) := match xs with | [] => return (mkConst ``Unit, ← `(term| ())) | [(x, a)] => do let xty ← inferType x if ← Meta.isProp xty then return (← mkAppM ``PLift #[xty], ← `(term| ⟨$(mkIdent a)⟩)) else return (xty, mkIdent a) | (x, a) :: xs => do let (xsty, patt) ← defaultMkCtorProxyType xs let xty ← inferType x if ← Meta.isProp xty then withLocalDeclD `x' (← mkAppM ``PLift #[xty]) fun x' => do let xsty' := xsty.replaceFVar x (← mkAppM ``PLift.down #[x']) let ty ← decorateSigma (← mkAppM ``Sigma #[← mkLambdaFVars #[x'] xsty']) return (ty, ← `(term| ⟨⟨$(mkIdent a)⟩, $patt⟩)) else let ty ← decorateSigma (← mkAppM ``Sigma #[← mkLambdaFVars #[x] xsty]) return (ty, ← `(term| ⟨$(mkIdent a), $patt⟩)) /-- Create a `Sum` of types, mildly optimized to not have a trailing `Empty`. The `decorateSum` function is to wrap the `Sum` with a function such as `Lex`. It should yield a definitionally equal type. -/ def defaultMkProxyType (ctors : Array (Name × Expr × Term)) (decorateSum : Expr → TermElabM Expr := pure) : TermElabM (Expr × Array Term × TSyntax `tactic) := do let mut types := #[] let mut patts := #[] for h : i in [0:ctors.size] do let (_ctorName, ty, patt) := ctors[i] types := types.push ty patts := patts.push <| ← wrapSumAccess i ctors.size patt let (type, pf) ← mkCType types.toList return (type, patts, pf) where /-- Construct the `Sum` expression, using `decorateSum` to adjust each `Sum`. -/ mkCType (ctypes : List Expr) : TermElabM (Expr × TSyntax `tactic) := match ctypes with | [] => return (mkConst ``Empty, ← `(tactic| cases x)) | [x] => return (x, ← `(tactic| rfl)) | x :: xs => do let (ty, pf) ← mkCType xs let pf ← `(tactic| cases x with | inl _ => rfl | inr x => $pf:tactic) return (← decorateSum (← mkAppM ``Sum #[x, ty]), pf) /-- Navigates into the sum type that we create in `mkCType` for the given constructor index. -/ wrapSumAccess (cidx nctors : Nat) (spatt : Term) : TermElabM Term := match cidx with | 0 => if nctors = 1 then return spatt else `(term| Sum.inl $spatt) | cidx' + 1 => do let spatt ← wrapSumAccess cidx' (nctors - 1) spatt `(term| Sum.inr $spatt) /-- Default configuration. Defines `proxyType` and `proxyTypeEquiv` in the namespace of the inductive type. Uses `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. -/ def ProxyEquivConfig.default (indVal : InductiveVal) : ProxyEquivConfig where proxyName := indVal.name.mkStr "proxyType" proxyEquivName := indVal.name.mkStr "proxyTypeEquiv" mkCtorProxyType := defaultMkCtorProxyType mkProxyType := defaultMkProxyType /-- Generates a proxy type for the inductive type and an equivalence from the proxy type to the type. If the declarations already exist, there is a check that they are correct. -/ def ensureProxyEquiv (config : ProxyEquivConfig) (indVal : InductiveVal) : TermElabM Unit := do if indVal.isRec then throwError "proxy equivalence: recursive inductive types are not supported (and are usually infinite)" if 0 < indVal.numIndices then throwError "proxy equivalence: inductive indices are not supported" let levels := indVal.levelParams.map Level.param forallBoundedTelescope indVal.type indVal.numParams fun params _sort => do let mut cdata := #[] for ctorName in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName let ctorType ← inferType <| mkAppN (mkConst ctorName levels) params cdata := cdata.push <| ← forallBoundedTelescope ctorType ctorInfo.numFields fun xs _itype => do let names ← xs.mapM (fun _ => mkFreshUserName `a) let (ty, ppatt) ← config.mkCtorProxyType (xs.zip names).toList let places := .replicate ctorInfo.numParams (← `(term| _)) let argNames := names.map mkIdent let cpatt ← `(term| @$(mkIdent ctorName) $places* $argNames*) return (ctorName, ty, ppatt, cpatt) let (ctype, ppatts, pf) ← config.mkProxyType <| cdata.map (fun (ctorName, ty, ppatt, _) => (ctorName, ty, ppatt)) let mut toFunAlts := #[] let mut invFunAlts := #[] for ppatt in ppatts, (_, _, _, cpatt) in cdata do toFunAlts := toFunAlts.push <| ← `(matchAltExpr| | $ppatt => $cpatt) invFunAlts := invFunAlts.push <| ← `(matchAltExpr| | $cpatt => $ppatt) -- Create the proxy type definition trace[Elab.ProxyType] "proxy type: {ctype}" let ctype' ← mkLambdaFVars params ctype if let some const := (← getEnv).find? config.proxyName then unless ← isDefEq const.value! ctype' do throwError "Declaration {config.proxyName} already exists and it is not the proxy type." trace[Elab.ProxyType] "proxy type already exists" else addAndCompile <| Declaration.defnDecl { name := config.proxyName levelParams := indVal.levelParams safety := DefinitionSafety.safe hints := ReducibilityHints.abbrev type := ← inferType ctype' value := ctype' } -- Set to be reducible so that typeclass inference can see it's a Fintype setReducibleAttribute config.proxyName setProtected config.proxyName -- Add a docstring addDocStringCore config.proxyName s!"A \"proxy type\" equivalent to `{indVal.name}` that is \ constructed from `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. \ See `{config.proxyEquivName}` for the equivalence. \ (Generated by the `proxy_equiv%` elaborator.)" trace[Elab.ProxyType] "defined {config.proxyName}" -- Create the `Equiv` let equivType ← mkAppM ``Equiv #[ctype, mkAppN (mkConst indVal.name levels) params] if let some const := (← getEnv).find? config.proxyEquivName then unless ← isDefEq const.type (← mkForallFVars params equivType) do throwError "Declaration {config.proxyEquivName} already exists and has the wrong type." trace[Elab.ProxyType] "proxy equivalence already exists" else trace[Elab.ProxyType] "constructing proxy equivalence" let mut toFun ← `(term| fun $toFunAlts:matchAlt*) let mut invFun ← `(term| fun $invFunAlts:matchAlt*) if indVal.numCtors == 0 then -- Empty matches don't elaborate, so use `nomatch` here. toFun ← `(term| fun x => nomatch x) invFun ← `(term| fun x => nomatch x) let equivBody ← `(term| { toFun := $toFun, invFun := $invFun, right_inv := by intro x; cases x <;> rfl left_inv := by intro x; $pf:tactic }) let equiv ← Term.elabTerm equivBody equivType Term.synthesizeSyntheticMVarsNoPostponing trace[Elab.ProxyType] "elaborated equivalence{indentExpr equiv}" let equiv' ← mkLambdaFVars params (← instantiateMVars equiv) addAndCompile <| Declaration.defnDecl { name := config.proxyEquivName levelParams := indVal.levelParams safety := DefinitionSafety.safe hints := ReducibilityHints.abbrev type := ← inferType equiv' value := equiv' } setProtected config.proxyEquivName addDocStringCore config.proxyEquivName s!"An equivalence between the \"proxy type\" \ `{config.proxyName}` and `{indVal.name}`. The proxy type is a reducible definition \ that represents the inductive type using `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum` \ (and whatever other inductive types appear within the inductive type), and the \ intended use is to define typeclass instances uses pre-existing instances on these. \ (Generated by the `proxy_equiv%` elaborator.)" trace[Elab.ProxyType] "defined {config.proxyEquivName}" /-- Helper function for `proxy_equiv% type : expectedType` elaborators. Elaborate `type` and get its `InductiveVal`. Uses the `expectedType`, where the expected type should be of the form `_ ≃ type`. -/ def elabProxyEquiv (type : Term) (expectedType? : Option Expr) : TermElabM (Expr × InductiveVal) := do let type ← Term.elabType type if let some expectedType := expectedType? then let equivType ← Term.elabType (← `(_ ≃ $(← Term.exprToSyntax type))) unless ← isDefEq expectedType equivType do throwError "Could not unify expected type{indentExpr expectedType}\nwith{indentExpr equivType}" let type ← Term.tryPostponeIfHasMVars type "In proxy_equiv% elaborator" let type ← whnf type let .const declName _ := type.getAppFn | throwError "{type} is not a constant or constant application" return (type, ← getConstInfoInduct declName) /-- The term elaborator `proxy_equiv% α` for a type `α` elaborates to an equivalence `β ≃ α` for a "proxy type" `β` composed out of basic type constructors `Unit`, `PLift`, `Sigma`, `Empty`, and `Sum`. This only works for inductive types `α` that are neither recursive nor have indices. If `α` is an inductive type with name `I`, then as a side effect this elaborator defines `I.proxyType` and `I.proxyTypeEquiv`. The elaborator makes use of the expected type, so `(proxy_equiv% _ : _ ≃ α)` works. For example, given this inductive type ``` inductive foo (n : Nat) (α : Type) | a | b : Bool → foo n α | c (x : Fin n) : Fin x → foo n α | d : Bool → α → foo n α ``` the proxy type it generates is `Unit ⊕ Bool ⊕ (x : Fin n) × Fin x ⊕ (_ : Bool) × α` and in particular we have that ``` proxy_equiv% (foo n α) : Unit ⊕ Bool ⊕ (x : Fin n) × Fin x ⊕ (_ : Bool) × α ≃ foo n α ``` -/ syntax (name := proxy_equiv) "proxy_equiv% " term : term /-- Elaborator for `proxy_equiv%`. -/ @[term_elab proxy_equiv] def elab_proxy_equiv : Elab.Term.TermElab := fun stx expectedType? => match stx with | `(proxy_equiv% $t) => do let (type, indVal) ← elabProxyEquiv t expectedType? let config : ProxyEquivConfig := ProxyEquivConfig.default indVal ensureProxyEquiv config indVal mkAppOptM config.proxyEquivName (type.getAppArgs.map .some) | _ => throwUnsupportedSyntax end Mathlib.ProxyType
Representability.lean
/- Copyright (c) 2024 Calle Sönne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne, Joël Riou, Ravi Vakil -/ import Mathlib.CategoryTheory.MorphismProperty.Representable import Mathlib.AlgebraicGeometry.Sites.BigZariski import Mathlib.AlgebraicGeometry.OpenImmersion import Mathlib.AlgebraicGeometry.GluingOneHypercover import Mathlib.CategoryTheory.Sites.LocallyBijective import Mathlib.CategoryTheory.Limits.Shapes.Products import Mathlib.CategoryTheory.Limits.Shapes.Pullback.Iso /-! # Representability of schemes is a local property In this file we prove that a sheaf of types `F` on `Sch` is representable if it is locally representable. ## Main result - `AlgebraicGeometry.Scheme.LocalRepresentability.isRepresentable`: Suppose * F is a `Type u`-valued sheaf on `Sch` with respect to the Zariski topology * X : ι → Sch is a family of schemes * f : Π i, yoneda.obj (X i) ⟶ F is a family of relatively representable open immersions * f is jointly surjective Then `F` is representable. ## References * https://stacks.math.columbia.edu/tag/01JJ -/ namespace AlgebraicGeometry open CategoryTheory Category Limits Opposite attribute [local instance] Types.instFunLike Types.instConcreteCategory universe u namespace Scheme /- Consider the following setup: * F is `Type u`-valued a sheaf on `Sch` with respect to the Zariski topology * X : ι → Sch is a family of schemes * f : Π i, yoneda.obj (X i) ⟶ F is a family of relatively representable open immersions Later, we will also assume: * The family f is locally surjective with respect to the Zariski topology -/ variable (F : Sheaf Scheme.zariskiTopology.{u} (Type u)) {ι : Type u} {X : ι → Scheme.{u}} (f : (i : ι) → yoneda.obj (X i) ⟶ F.1) (hf : ∀ i, IsOpenImmersion.presheaf (f i)) namespace LocalRepresentability variable {F f} (i j k : ι) open Functor.relativelyRepresentable in /-- We get a family of gluing data by taking `U i = X i` and `V i j = (hf i).rep.pullback (f j)`. -/ @[simps] noncomputable def glueData : GlueData where J := ι U := X V := fun (i, j) ↦ (hf i).rep.pullback (f j) f i j := (hf i).rep.fst' (f j) f_mono i j := have := (hf j).property _ _ _ ((hf i).1.isPullback' (f j)).flip IsOpenImmersion.mono _ f_id i := IsOpenImmersion.isIso_fst'_self IsOpenImmersion.le_monomorphisms (hf i) t i j := (hf i).rep.symmetry (hf j).rep t_id i := by apply (hf i).rep.hom_ext' <;> simp [IsOpenImmersion.fst'_self_eq_snd IsOpenImmersion.le_monomorphisms (hf i)] t' i j k := lift₃ _ _ _ (pullback₃.p₂ _ _ _) (pullback₃.p₃ _ _ _) (pullback₃.p₁ _ _ _) (by simp) (by simp) t_fac i j k := (hf j).rep.hom_ext' (by simp) (by simp) cocycle i j k := pullback₃.hom_ext (by simp) (by simp) (by simp) f_open i j := (hf j).property _ _ _ ((hf i).1.isPullback' (f j)).flip /-- The map from `X i` to the glued scheme `(glueData hf).glued` -/ noncomputable def toGlued (i : ι) : X i ⟶ (glueData hf).glued := (glueData hf).ι i instance : IsOpenImmersion (toGlued hf i) := inferInstanceAs (IsOpenImmersion ((glueData hf).ι i)) /-- The map from the glued scheme `(glueData hf).glued`, treated as a sheaf, to `F`. -/ noncomputable def yonedaGluedToSheaf : zariskiTopology.yoneda.obj (glueData hf).glued ⟶ F where -- The map is obtained by finding an object of `F((glueData hf).glued)`. val := yonedaEquiv.symm -- This section is obtained from gluing the section corresponding to `f i : Hom(-, X i) ⟶ F`. ((glueData hf).sheafValGluedMk (fun i ↦ yonedaEquiv (f i)) (by intro i j apply yonedaEquiv.symm.injective dsimp only [glueData_V, glueData_J, glueData_U, glueData_f, glueData_t] rw [yonedaEquiv_naturality, Equiv.symm_apply_apply, FunctorToTypes.map_comp_apply, yonedaEquiv_naturality, yonedaEquiv_naturality, Equiv.symm_apply_apply, ← Functor.map_comp_assoc, Functor.relativelyRepresentable.symmetry_fst, ((hf i).rep.isPullback' (f j)).w])) @[reassoc (attr := simp)] lemma yoneda_toGlued_yonedaGluedToSheaf (i : ι) : yoneda.map (toGlued hf i) ≫ (yonedaGluedToSheaf hf).val = f i := by apply yonedaEquiv.injective rw [yonedaGluedToSheaf, yonedaEquiv_apply, yonedaEquiv_apply, FunctorToTypes.comp, yoneda_map_app, id_comp, yonedaEquiv_symm_app_apply] apply GlueData.sheafValGluedMk_val @[simp] lemma yonedaGluedToSheaf_app_toGlued {i : ι} : (yonedaGluedToSheaf hf).val.app _ (toGlued hf i) = yonedaEquiv (f i) := by rw [← yoneda_toGlued_yonedaGluedToSheaf hf i, yonedaEquiv_comp, yonedaEquiv_yoneda_map] @[simp] lemma yonedaGluedToSheaf_app_comp {V U : Scheme.{u}} (γ : V ⟶ U) (α : U ⟶ (glueData hf).glued) : (yonedaGluedToSheaf hf).val.app (op V) (γ ≫ α) = F.val.map γ.op ((yonedaGluedToSheaf hf).val.app (op U) α) := congr_fun ((yonedaGluedToSheaf hf).val.naturality γ.op) α instance [Presheaf.IsLocallySurjective Scheme.zariskiTopology (Sigma.desc f)] : Sheaf.IsLocallySurjective (yonedaGluedToSheaf hf) := Presheaf.isLocallySurjective_of_isLocallySurjective_fac _ (show Sigma.desc (fun i ↦ yoneda.map (toGlued hf i)) ≫ (yonedaGluedToSheaf hf).val = Sigma.desc f by cat_disch) lemma comp_toGlued_eq {U : Scheme} {i j : ι} (a : U ⟶ X i) (b : U ⟶ X j) (h : yoneda.map a ≫ f i = yoneda.map b ≫ f j) : a ≫ toGlued hf i = b ≫ toGlued hf j := by rw [← (hf i).rep.lift'_fst a b h, assoc] conv_rhs => rw [← (hf i).rep.lift'_snd a b h, assoc] congr 1 exact ((glueData hf).glue_condition i j).symm.trans (by simp [toGlued]) @[simp] lemma glueData_openCover_map : (glueData hf).openCover.map j = toGlued hf j := rfl instance : Sheaf.IsLocallyInjective (yonedaGluedToSheaf hf) where equalizerSieve_mem := by rintro ⟨U⟩ (α β : U ⟶ _) h replace h : (yonedaGluedToSheaf hf).val.app _ α = (yonedaGluedToSheaf hf).val.app _ β := h have mem := grothendieckTopology_cover (glueData hf).openCover refine GrothendieckTopology.superset_covering _ ?_ (zariskiTopology.intersection_covering (zariskiTopology.pullback_stable α mem) (zariskiTopology.pullback_stable β mem)) rintro V (γ : _ ⟶ U) ⟨⟨W₁, a, _, ⟨i⟩, fac₁⟩, ⟨W₂, b, _, ⟨j⟩, fac₂⟩⟩ change γ ≫ α = γ ≫ β replace h : (yonedaGluedToSheaf hf).val.app _ (γ ≫ α) = (yonedaGluedToSheaf hf).val.app _ (γ ≫ β) := by simp [h] rw [← fac₁, ← fac₂] at h ⊢ apply comp_toGlued_eq simpa [Scheme.GlueData.openCover_obj, yonedaEquiv_naturality] using h variable [Presheaf.IsLocallySurjective Scheme.zariskiTopology (Sigma.desc f)] instance : IsIso (yonedaGluedToSheaf hf) := by rw [← Sheaf.isLocallyBijective_iff_isIso (yonedaGluedToSheaf hf)] constructor <;> infer_instance /-- The isomorphism between `yoneda.obj (glueData hf).glued` and `F`. This implies that `F` is representable. -/ noncomputable def yonedaIsoSheaf : zariskiTopology.yoneda.obj (glueData hf).glued ≅ F := asIso (yonedaGluedToSheaf hf) /-- Suppose * F is a `Type u`-valued sheaf on `Sch` with respect to the Zariski topology * X : ι → Sch is a family of schemes * f : Π i, yoneda.obj (X i) ⟶ F is a family of relatively representable open immersions * f is jointly surjective Then `F` is representable, and the representing object is glued from the `X i`s -/ noncomputable def representableBy : F.1.RepresentableBy (glueData hf).glued := Functor.representableByEquiv.symm ((sheafToPresheaf _ _).mapIso (yonedaIsoSheaf hf)) include hf in /-- Suppose * F is a `Type u`-valued sheaf on `Sch` with respect to the Zariski topology * X : ι → Sch is a family of schemes * f : Π i, yoneda.obj (X i) ⟶ F is a family of relatively representable open immersions * f is jointly surjective Then `F` is representable. -/ @[stacks 01JJ] theorem isRepresentable : F.1.IsRepresentable := ⟨_, ⟨representableBy hf⟩⟩ end LocalRepresentability end Scheme end AlgebraicGeometry
Clean.lean
import Mathlib.Tactic.Clean namespace Tests def x : Id Nat := by dsimp [Id]; exact 1 def x' : Id Nat := clean% by dsimp [Id]; exact 1 /-- info: def Tests.x : Id Nat := id 1 -/ #guard_msgs in #print x /-- info: def Tests.x' : Id Nat := 1 -/ #guard_msgs in #print x' -- def x : Id Nat := 1 theorem withClean : 2 + 2 = 4 := clean% by exact id rfl theorem withoutClean : 2 + 2 = 4 := by exact id rfl /-- info: theorem Tests.withClean : 2 + 2 = 4 := rfl -/ #guard_msgs in #print Tests.withClean /-- info: theorem Tests.withoutClean : 2 + 2 = 4 := id rfl -/ #guard_msgs in #print Tests.withoutClean example : True := by let x : id Nat := by dsimp; exact 1 guard_hyp x :ₛ id Nat := id (1 : Nat) let x' : id Nat := clean% by dsimp; exact 1 guard_hyp x' :ₛ id Nat := (1 : Nat) let y := show Nat from 1 guard_hyp y :ₛ Nat := have this := 1; this let y' := clean% show Nat from 1 guard_hyp y' :ₛ Nat := 1 -- Not a tautological have: let z := clean% have x := 1; x + x guard_hyp z :ₛ Nat := have x := 1; x + x trivial end Tests
bigop.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 fintype tuple finfun. (******************************************************************************) (* Finitely iterated operators *) (* *) (* NB: See CONTRIBUTING.md for an introduction to HB concepts and commands. *) (* *) (* This file provides a generic definition for iterating an operator over a *) (* set of indices (bigop); this big operator is parameterized by the return *) (* type (R), the type of indices (I), the operator (op), the default value on *) (* empty lists (idx), the range of indices (r), the filter applied on this *) (* range (P) and the expression we are iterating (F). The definition is not *) (* to be used directly, but via the wide range of notations provided and *) (* which support a natural use of big operators. *) (* To improve performance of the Coq typechecker on large expressions, the *) (* bigop constant is OPAQUE. It can however be unlocked to reveal the *) (* transparent constant reducebig, to let Coq expand summation on an explicit *) (* sequence with an explicit test. *) (* The lemmas can be classified according to the operator being iterated: *) (* 1. Results independent of the operator: extensionality with respect to *) (* the range of indices, to the filtering predicate or to the expression *) (* being iterated; reindexing, widening or narrowing of the range of *) (* indices; we provide lemmas for the special cases where indices are *) (* natural numbers or bounded natural numbers ("ordinals"). We supply *) (* several "functional" induction principles that can be used with the *) (* ssreflect 1.3 "elim" tactic to do induction over the index range for *) (* up to 3 bigops simultaneously. *) (* 2. Results depending on the properties of the operator: *) (* We distinguish: *) (* - semigroup laws (op is associative) *) (* - commutative semigroup laws (semigroup laws, op is commutative) *) (* - monoid laws (semigroup laws, idx is an identity element) *) (* - abelian monoid laws (op is also commutative) *) (* - laws with a distributive operation (semirings) *) (* Examples of such results are splitting, permuting, and exchanging *) (* bigops. *) (* A special section is dedicated to big operators on natural numbers. *) (******************************************************************************) (* Notations: *) (* The general form for iterated operators is *) (* <bigop>_<range> <general_term> *) (* - <bigop> is one of \big[op/idx], \sum, \prod, or \max (see below). *) (* - <general_term> can be any expression. *) (* - <range> binds an index variable in <general_term>; <range> is one of *) (* (i <- s) i ranges over the sequence s. *) (* (m <= i < n) i ranges over the nat interval m, m+1, ..., n-1. *) (* (i < n) i ranges over the (finite) type 'I_n (i.e., ordinal n). *) (* (i : T) i ranges over the finite type T. *) (* i or (i) i ranges over its (inferred) finite type. *) (* (i in A) i ranges over the elements that satisfy the collective *) (* predicate A (the domain of A must be a finite type). *) (* (i <- s | <condition>) limits the range to the i for which <condition> *) (* holds. <condition> can be any expression that coerces to *) (* bool, and may mention the bound index i. All six kinds of *) (* ranges above can have a <condition> part. *) (* - One can use the "\big[op/idx]" notations for any operator. *) (* - BIG_F and BIG_P are pattern abbreviations for the <general_term> and *) (* <condition> part of a \big ... expression; for (i in A) and (i in A | C) *) (* ranges the term matched by BIG_P will include the i \in A condition. *) (* - The (locked) head constant of a \big notation is bigop. *) (* - The "\sum", "\prod" and "\max" notations in the %N scope are used for *) (* natural numbers with addition, multiplication and maximum (and their *) (* corresponding neutral elements), respectively. *) (* - The "\sum" and "\prod" reserved notations are overloaded in ssralg in *) (* the %R scope; in mxalgebra, vector & falgebra in the %MS and %VS scopes; *) (* "\prod" is also overloaded in fingroup, in the %g and %G scopes. *) (* - We reserve "\bigcup" and "\bigcap" notations for iterated union and *) (* intersection (of sets, groups, vector spaces, etc.). *) (******************************************************************************) (* Tips for using lemmas in this file: *) (* To apply a lemma for a specific operator: if no special property is *) (* required for the operator, simply apply the lemma; if the lemma needs *) (* certain properties for the operator, make sure the appropriate instances *) (* are declared using, e.g., Check addn : Monoid.law _. to check that addn *) (* is equipped with the monoid laws. *) (******************************************************************************) (* Interfaces for operator properties are packaged in the SemiGroup and *) (* Monoid submodules: *) (* SemiGroup.law == interface (keyed on the operator) for associative *) (* operators *) (* The HB class is SemiGroup. *) (* SemiGroup.com_law == interface for associative and commutative operators *) (* The HB class is SemiGroup.ComLaw. *) (* Monoid.law idx == interface for associative operators with identity *) (* element idx *) (* The HB class is Monoid.Law. *) (* Monoid.com_law idx == extension of Monoid.law for operators that are also *) (* commutative *) (* The HB class is Monoid.ComLaw. *) (* Monoid.mul_law abz == interface for operators with absorbing (zero) *) (* element abz *) (* The HB class is Monoid.MulLaw. *) (* Monoid.add_law idx mop == extension of Monoid.com_law for operators over *) (* which operation mop distributes (mop will often also *) (* have a Monoid.mul_law idx structure) *) (* The HB class is Monoid.AddLaw. *) (* SemiGroup.Theory == submodule containing basic generic algebra lemmas *) (* for operators satisfying the SemiGroup interfaces *) (* Monoid.Theory == submodule containing basic generic algebra lemmas *) (* for operators satisfying the Monoid interfaces, *) (* exports SemiGroup.Theory *) (* Monoid.simpm == generic monoid simplification rewrite multirule *) (* oAC op == convert an AC operator op : T -> T -> T *) (* to a Monoid.com_law on option T *) (* Monoid structures are predeclared for many basic operators: (_ && _)%B, *) (* (_ || _)%B, (_ (+) _)%B (exclusive or), (_ + _)%N, (_ * _)%N, maxn, *) (* gcdn, lcmn and (_ ++ _)%SEQ (list concatenation) *) (******************************************************************************) (* Reference: Y. Bertot, G. Gonthier, S. Ould Biha, I. Pasca, Canonical Big *) (* Operators, TPHOLs 2008, LNCS vol. 5170, Springer, available at: *) (* http://hal.inria.fr/docs/00/33/11/93/PDF/main.pdf *) (******************************************************************************) (* Examples of use in: poly.v, matrix.v *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Declare Scope big_scope. Reserved Notation "\big [ op / idx ]_ i F" (at level 36, F at level 36, op, idx at level 10, i at level 0, right associativity, format "'[' \big [ op / idx ]_ i '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i <- r | P ) F" (F at level 36, i, r at level 60, format "'[' \big [ op / idx ]_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i <- r ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( m <= i < n | P ) F" (F at level 36, i, n at level 60, format "'[' \big [ op / idx ]_ ( m <= i < n | P ) F ']'"). Reserved Notation "\big [ op / idx ]_ ( m <= i < n ) F" (at level 36, F at level 36, format "'[' \big [ op / idx ]_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i | P ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i | P ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i : t | P ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i : t | P ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i : t ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i : t ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i < n | P ) F" (F at level 36, n at level 60, format "'[' \big [ op / idx ]_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i < n ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i < n ) F ']'"). Reserved Notation "\big [ op / idx ]_ ( i 'in' A | P ) F" (F at level 36, A at level 60, format "'[' \big [ op / idx ]_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\big [ op / idx ]_ ( i 'in' A ) F" (F at level 36, format "'[' \big [ op / idx ]_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\sum_ i F" (at level 34, F at level 41, i at level 0, right associativity, format "'[' \sum_ i '/ ' F ']'"). Reserved Notation "\sum_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \sum_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\sum_ ( i <- r ) F" (F at level 41, format "'[' \sum_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\sum_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \sum_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\sum_ ( m <= i < n ) F" (F at level 41, format "'[' \sum_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\sum_ ( i | P ) F" (F at level 41, format "'[' \sum_ ( i | P ) '/ ' F ']'"). Reserved Notation "\sum_ ( i : t | P ) F" (F at level 41). (* only parsing *) Reserved Notation "\sum_ ( i : t ) F" (F at level 41). (* only parsing *) Reserved Notation "\sum_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \sum_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\sum_ ( i < n ) F" (F at level 41, format "'[' \sum_ ( i < n ) '/ ' F ']'"). Reserved Notation "\sum_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \sum_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\sum_ ( i 'in' A ) F" (F at level 41, format "'[' \sum_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\max_ i F" (at level 34, F at level 41, i at level 0, format "'[' \max_ i '/ ' F ']'"). Reserved Notation "\max_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \max_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i <- r ) F" (F at level 41, format "'[' \max_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\max_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \max_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\max_ ( m <= i < n ) F" (F at level 41, format "'[' \max_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\max_ ( i | P ) F" (F at level 41, format "'[' \max_ ( i | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i : t | P ) F" (F at level 41). (* only parsing *) Reserved Notation "\max_ ( i : t ) F" (F at level 41). (* only parsing *) Reserved Notation "\max_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \max_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i < n ) F" (F at level 41, n at level 60, format "'[' \max_ ( i < n ) F ']'"). Reserved Notation "\max_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \max_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\max_ ( i 'in' A ) F" (F at level 41, format "'[' \max_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\prod_ i F" (at level 34, F at level 36, i at level 0, format "'[' \prod_ i '/ ' F ']'"). Reserved Notation "\prod_ ( i <- r | P ) F" (F at level 36, i, r at level 60, format "'[' \prod_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\prod_ ( i <- r ) F" (F at level 36, format "'[' \prod_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\prod_ ( m <= i < n | P ) F" (F at level 36, i, n at level 60, format "'[' \prod_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\prod_ ( m <= i < n ) F" (F at level 36, format "'[' \prod_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\prod_ ( i | P ) F" (F at level 36, format "'[' \prod_ ( i | P ) '/ ' F ']'"). Reserved Notation "\prod_ ( i : t | P ) F" (F at level 36). (* only parsing *) Reserved Notation "\prod_ ( i : t ) F" (F at level 36). (* only parsing *) Reserved Notation "\prod_ ( i < n | P ) F" (F at level 36, n at level 60, format "'[' \prod_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\prod_ ( i < n ) F" (F at level 36, format "'[' \prod_ ( i < n ) '/ ' F ']'"). Reserved Notation "\prod_ ( i 'in' A | P ) F" (F at level 36, A at level 60, format "'[' \prod_ ( i 'in' A | P ) F ']'"). Reserved Notation "\prod_ ( i 'in' A ) F" (F at level 36, format "'[' \prod_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\bigcup_ i F" (at level 41, F at level 41, i at level 0, format "'[' \bigcup_ i '/ ' F ']'"). Reserved Notation "\bigcup_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \bigcup_ ( i <- r | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i <- r ) F" (F at level 41, format "'[' \bigcup_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \bigcup_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( m <= i < n ) F" (F at level 41, format "'[' \bigcup_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i | P ) F" (F at level 41, format "'[' \bigcup_ ( i | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i : t | P ) F" (F at level 41, format "'[' \bigcup_ ( i : t | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i : t ) F" (F at level 41, format "'[' \bigcup_ ( i : t ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \bigcup_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i < n ) F" (F at level 41, format "'[' \bigcup_ ( i < n ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \bigcup_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\bigcup_ ( i 'in' A ) F" (F at level 41, format "'[' \bigcup_ ( i 'in' A ) '/ ' F ']'"). Reserved Notation "\bigcap_ i F" (at level 41, F at level 41, i at level 0, format "'[' \bigcap_ i '/ ' F ']'"). Reserved Notation "\bigcap_ ( i <- r | P ) F" (F at level 41, i, r at level 60, format "'[' \bigcap_ ( i <- r | P ) F ']'"). Reserved Notation "\bigcap_ ( i <- r ) F" (F at level 41, format "'[' \bigcap_ ( i <- r ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( m <= i < n | P ) F" (F at level 41, i, n at level 60, format "'[' \bigcap_ ( m <= i < n | P ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( m <= i < n ) F" (F at level 41, format "'[' \bigcap_ ( m <= i < n ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i | P ) F" (F at level 41, format "'[' \bigcap_ ( i | P ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i : t | P ) F" (F at level 41, format "'[' \bigcap_ ( i : t | P ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i : t ) F" (F at level 41, format "'[' \bigcap_ ( i : t ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i < n | P ) F" (F at level 41, n at level 60, format "'[' \bigcap_ ( i < n | P ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i < n ) F" (F at level 41, format "'[' \bigcap_ ( i < n ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i 'in' A | P ) F" (F at level 41, A at level 60, format "'[' \bigcap_ ( i 'in' A | P ) '/ ' F ']'"). Reserved Notation "\bigcap_ ( i 'in' A ) F" (F at level 41, format "'[' \bigcap_ ( i 'in' A ) '/ ' F ']'"). Module SemiGroup. HB.mixin Record isLaw T (op : T -> T -> T) := { opA : associative op; }. #[export] HB.structure Definition Law T := {op of isLaw T op}. Notation law := Law.type. HB.mixin Record isCommutativeLaw T (op : T -> T -> T) := { opC : commutative op; }. #[export] HB.structure Definition ComLaw T := {op of Law T op & isCommutativeLaw T op}. Notation com_law := ComLaw.type. HB.factory Record isComLaw T (op : T -> T -> T) := { opA : associative op; opC : commutative op; }. HB.builders Context T op of isComLaw T op. HB.instance Definition _ := isLaw.Build T op opA. HB.instance Definition _ := isCommutativeLaw.Build T op opC. HB.end. Module Import Exports. HB.reexport. End Exports. Module Theory. Section Theory. Variables (T : Type). Section Plain. Variable mul : law T. Lemma mulmA : associative mul. Proof. exact: opA. Qed. End Plain. Section Commutative. Variable mul : com_law T. Lemma mulmC : commutative mul. Proof. exact: opC. Qed. Lemma mulmCA : left_commutative mul. Proof. by move=> x y z; rewrite !mulmA [_ x _]mulmC. Qed. Lemma mulmAC : right_commutative mul. Proof. by move=> x y z; rewrite -!mulmA [_ y _]mulmC. Qed. Lemma mulmACA : interchange mul mul. Proof. by move=> x y z t; rewrite -!mulmA [_ y _]mulmCA. Qed. End Commutative. End Theory. End Theory. Include Theory. End SemiGroup. Export SemiGroup.Exports. Module Monoid. Export SemiGroup. HB.mixin Record isMonoidLaw T (idm : T) (op : T -> T -> T) := { op1m : left_id idm op; opm1 : right_id idm op; }. #[export] HB.structure Definition Law T idm := {op of SemiGroup.Law T op & isMonoidLaw T idm op}. Notation law := Law.type. HB.factory Record isLaw T (idm : T) (op : T -> T -> T) := { opA : associative op; op1m : left_id idm op; opm1 : right_id idm op; }. HB.builders Context T idm op of isLaw T idm op. HB.instance Definition _ := SemiGroup.isLaw.Build T op opA. HB.instance Definition _ := isMonoidLaw.Build T idm op op1m opm1. HB.end. #[export] HB.structure Definition ComLaw T idm := {op of Law T idm op & isCommutativeLaw T op}. Notation com_law := ComLaw.type. HB.factory Record isComLaw T (idm : T) (op : T -> T -> T) := { opA : associative op; opC : commutative op; op1m : left_id idm op; }. HB.builders Context T idm op of isComLaw T idm op. Lemma opm1 : right_id idm op. Proof. by move=> x; rewrite opC op1m. Qed. HB.instance Definition _ := isLaw.Build T idm op opA op1m opm1. HB.instance Definition _ := isCommutativeLaw.Build T op opC. HB.end. HB.mixin Record isMulLaw T (zero : T) (mul : T -> T -> T) := { mul_zerol : left_zero zero mul; mul_zeror : right_zero zero mul; }. #[export] HB.structure Definition MulLaw T zero := {mul of isMulLaw T zero mul}. Notation mul_law := MulLaw.type. HB.mixin Record isAddLaw T (mul : T -> T -> T) (op : T -> T -> T) := { mul_op_Dl : left_distributive mul op; mul_op_Dr : right_distributive mul op; }. #[export] HB.structure Definition AddLaw T zero mul := {add of ComLaw T zero add & isAddLaw T mul add}. Notation add_law := AddLaw.type. Module Import Exports. HB.reexport. End Exports. Section CommutativeAxioms. Variable (T : Type) (zero one : T) (mul add : T -> T -> T). Hypothesis mulC : commutative mul. Lemma mulC_id : left_id one mul -> right_id one mul. Proof. by move=> mul1x x; rewrite mulC. Qed. Lemma mulC_zero : left_zero zero mul -> right_zero zero mul. Proof. by move=> mul0x x; rewrite mulC. Qed. Lemma mulC_dist : left_distributive mul add -> right_distributive mul add. Proof. by move=> mul_addl x y z; rewrite !(mulC x). Qed. End CommutativeAxioms. Module Theory. Export SemiGroup.Theory. Section Theory. Variables (T : Type) (idm : T). Section Plain. Variable mul : law idm. Lemma mul1m : left_id idm mul. Proof. exact: op1m. Qed. Lemma mulm1 : right_id idm mul. Proof. exact: opm1. Qed. Lemma iteropE n x : iterop n mul x idm = iter n (mul x) idm. Proof. by case: n => // n; rewrite iterSr mulm1 iteropS. Qed. End Plain. Section Mul. Variable mul : mul_law idm. Lemma mul0m : left_zero idm mul. Proof. exact: mul_zerol. Qed. Lemma mulm0 : right_zero idm mul. Proof. exact: mul_zeror. Qed. End Mul. Section Add. Variables (mul : T -> T -> T) (add : add_law idm mul). Lemma addmA : associative add. Proof. exact: mulmA. Qed. Lemma addmC : commutative add. Proof. exact: mulmC. Qed. Lemma addmCA : left_commutative add. Proof. exact: mulmCA. Qed. Lemma addmAC : right_commutative add. Proof. exact: mulmAC. Qed. Lemma add0m : left_id idm add. Proof. exact: mul1m. Qed. Lemma addm0 : right_id idm add. Proof. exact: mulm1. Qed. Lemma mulmDl : left_distributive mul add. Proof. exact: mul_op_Dl. Qed. Lemma mulmDr : right_distributive mul add. Proof. exact: mul_op_Dr. Qed. End Add. Definition simpm := (mulm1, mulm0, mul1m, mul0m, mulmA). End Theory. End Theory. Include SemiGroup.Theory. Include Theory. End Monoid. Export Monoid.Exports. Section PervasiveMonoids. Import Monoid. HB.instance Definition _ := isComLaw.Build bool true andb andbA andbC andTb. HB.instance Definition _ := isMulLaw.Build bool false andb andFb andbF. HB.instance Definition _ := isComLaw.Build bool false orb orbA orbC orFb. HB.instance Definition _ := isMulLaw.Build bool true orb orTb orbT. HB.instance Definition _ := isComLaw.Build bool false addb addbA addbC addFb. HB.instance Definition _ := isAddLaw.Build bool andb orb andb_orl andb_orr. HB.instance Definition _ := isAddLaw.Build bool orb andb orb_andl orb_andr. HB.instance Definition _ := isAddLaw.Build bool andb addb andb_addl andb_addr. HB.instance Definition _ := isComLaw.Build nat 0 addn addnA addnC add0n. HB.instance Definition _ := isComLaw.Build nat 1 muln mulnA mulnC mul1n. HB.instance Definition _ := isMulLaw.Build nat 0 muln mul0n muln0. HB.instance Definition _ := isAddLaw.Build nat muln addn mulnDl mulnDr. HB.instance Definition _ := isComLaw.Build nat 0 maxn maxnA maxnC max0n. HB.instance Definition _ := isAddLaw.Build nat muln maxn maxnMl maxnMr. HB.instance Definition _ := isComLaw.Build nat 0 gcdn gcdnA gcdnC gcd0n. HB.instance Definition _ := isAddLaw.Build nat muln gcdn muln_gcdl muln_gcdr. HB.instance Definition _ := isComLaw.Build nat 1 lcmn lcmnA lcmnC lcm1n. HB.instance Definition _ := isAddLaw.Build nat muln lcmn muln_lcml muln_lcmr. HB.instance Definition _ T := isLaw.Build (seq T) nil cat (@catA T) (@cat0s T) (@cats0 T). End PervasiveMonoids. (* Unit test for the [...law of ...] Notations Definition myp := addn. Definition mym := muln. Canonical myp_mon := [law of myp]. Canonical myp_cmon := [com_law of myp]. Canonical mym_mul := [mul_law of mym]. Canonical myp_add := [add_law _ of myp]. Print myp_add. Print Canonical Projections. *) Delimit Scope big_scope with BIG. Open Scope big_scope. (* The bigbody wrapper is a workaround for a quirk of the Coq pretty-printer, *) (* which would fail to redisplay the \big notation when the <general_term> or *) (* <condition> do not depend on the bound index. The BigBody constructor *) (* packages both in in a term in which i occurs; it also depends on the *) (* iterated <op>, as this can give more information on the expected type of *) (* the <general_term>, thus allowing for the insertion of coercions. *) Variant bigbody R I := BigBody of I & (R -> R -> R) & bool & R. Definition applybig {R I} (body : bigbody R I) x := let: BigBody _ op b v := body in if b then op v x else x. Definition reducebig R I idx r (body : I -> bigbody R I) := foldr (applybig \o body) idx r. HB.lock Definition bigop := reducebig. Canonical bigop_unlock := Unlockable bigop.unlock. Definition index_iota m n := iota m (n - m). Lemma mem_index_iota m n i : i \in index_iota m n = (m <= i < n). Proof. rewrite mem_iota; case le_m_i: (m <= i) => //=. by rewrite -leq_subLR subSn // -subn_gt0 -subnDA subnKC // subn_gt0. Qed. (* Legacy mathcomp scripts have been relying on the fact that enum A and *) (* filter A (index_enum T) are convertible. This is likely to change in the *) (* next mathcomp release when enum, pick, subset and card are generalised to *) (* predicates with finite support in a choiceType - in fact the two will only *) (* be equal up to permutation in this new theory. *) (* It is therefore advisable to stop relying on this, and use the new *) (* facilities provided in this library: lemmas big_enumP, big_enum, big_image *) (* and such. Users wishing to test compliance should change the Defined in *) (* index_enum_key to Qed, and comment out the filter_index_enum compatibility *) (* definition below. *) Fact index_enum_key : unit. Proof. split. Defined. (* Qed. *) Definition index_enum (T : finType) := locked_with index_enum_key (Finite.enum T). Lemma deprecated_filter_index_enum T P : filter P (index_enum T) = enum P. Proof. by rewrite [index_enum T]unlock. Qed. Lemma mem_index_enum T i : i \in index_enum T. Proof. by rewrite [index_enum T]unlock -enumT mem_enum. Qed. #[global] Hint Resolve mem_index_enum : core. Lemma index_enum_uniq T : uniq (index_enum T). Proof. by rewrite [index_enum T]unlock -enumT enum_uniq. Qed. Notation "\big [ op / idx ]_ ( i <- r | P ) F" := (bigop idx r (fun i => BigBody i op P%B F)) : big_scope. Notation "\big [ op / idx ]_ ( i <- r ) F" := (bigop idx r (fun i => BigBody i op true F)) : big_scope. Notation "\big [ op / idx ]_ ( m <= i < n | P ) F" := (bigop idx (index_iota m n) (fun i : nat => BigBody i op P%B F)) : big_scope. Notation "\big [ op / idx ]_ ( m <= i < n ) F" := (bigop idx (index_iota m n) (fun i : nat => BigBody i op true F)) : big_scope. Notation "\big [ op / idx ]_ ( i | P ) F" := (bigop idx (index_enum _) (fun i => BigBody i op P%B F)) : big_scope. Notation "\big [ op / idx ]_ i F" := (bigop idx (index_enum _) (fun i => BigBody i op true F)) : big_scope. Notation "\big [ op / idx ]_ ( i : t | P ) F" := (bigop idx (index_enum _) (fun i : t => BigBody i op P%B F)) (only parsing) : big_scope. Notation "\big [ op / idx ]_ ( i : t ) F" := (bigop idx (index_enum _) (fun i : t => BigBody i op true F)) (only parsing) : big_scope. Notation "\big [ op / idx ]_ ( i < n | P ) F" := (\big[op/idx]_(i : ordinal n | P%B) F) : big_scope. Notation "\big [ op / idx ]_ ( i < n ) F" := (\big[op/idx]_(i : ordinal n) F) : big_scope. Notation "\big [ op / idx ]_ ( i 'in' A | P ) F" := (\big[op/idx]_(i | (i \in A) && P) F) : big_scope. Notation "\big [ op / idx ]_ ( i 'in' A ) F" := (\big[op/idx]_(i | i \in A) F) : big_scope. Notation BIG_F := (F in \big[_/_]_(i <- _ | _) F i)%pattern. Notation BIG_P := (P in \big[_/_]_(i <- _ | P i) _)%pattern. Local Notation "+%N" := addn (only parsing). Notation "\sum_ ( i <- r | P ) F" := (\big[+%N/0%N]_(i <- r | P%B) F%N) : nat_scope. Notation "\sum_ ( i <- r ) F" := (\big[+%N/0%N]_(i <- r) F%N) : nat_scope. Notation "\sum_ ( m <= i < n | P ) F" := (\big[+%N/0%N]_(m <= i < n | P%B) F%N) : nat_scope. Notation "\sum_ ( m <= i < n ) F" := (\big[+%N/0%N]_(m <= i < n) F%N) : nat_scope. Notation "\sum_ ( i | P ) F" := (\big[+%N/0%N]_(i | P%B) F%N) : nat_scope. Notation "\sum_ i F" := (\big[+%N/0%N]_i F%N) : nat_scope. Notation "\sum_ ( i : t | P ) F" := (\big[+%N/0%N]_(i : t | P%B) F%N) (only parsing) : nat_scope. Notation "\sum_ ( i : t ) F" := (\big[+%N/0%N]_(i : t) F%N) (only parsing) : nat_scope. Notation "\sum_ ( i < n | P ) F" := (\big[+%N/0%N]_(i < n | P%B) F%N) : nat_scope. Notation "\sum_ ( i < n ) F" := (\big[+%N/0%N]_(i < n) F%N) : nat_scope. Notation "\sum_ ( i 'in' A | P ) F" := (\big[+%N/0%N]_(i in A | P%B) F%N) : nat_scope. Notation "\sum_ ( i 'in' A ) F" := (\big[+%N/0%N]_(i in A) F%N) : nat_scope. Local Notation "*%N" := muln (only parsing). Notation "\prod_ ( i <- r | P ) F" := (\big[*%N/1%N]_(i <- r | P%B) F%N) : nat_scope. Notation "\prod_ ( i <- r ) F" := (\big[*%N/1%N]_(i <- r) F%N) : nat_scope. Notation "\prod_ ( m <= i < n | P ) F" := (\big[*%N/1%N]_(m <= i < n | P%B) F%N) : nat_scope. Notation "\prod_ ( m <= i < n ) F" := (\big[*%N/1%N]_(m <= i < n) F%N) : nat_scope. Notation "\prod_ ( i | P ) F" := (\big[*%N/1%N]_(i | P%B) F%N) : nat_scope. Notation "\prod_ i F" := (\big[*%N/1%N]_i F%N) : nat_scope. Notation "\prod_ ( i : t | P ) F" := (\big[*%N/1%N]_(i : t | P%B) F%N) (only parsing) : nat_scope. Notation "\prod_ ( i : t ) F" := (\big[*%N/1%N]_(i : t) F%N) (only parsing) : nat_scope. Notation "\prod_ ( i < n | P ) F" := (\big[*%N/1%N]_(i < n | P%B) F%N) : nat_scope. Notation "\prod_ ( i < n ) F" := (\big[*%N/1%N]_(i < n) F%N) : nat_scope. Notation "\prod_ ( i 'in' A | P ) F" := (\big[*%N/1%N]_(i in A | P%B) F%N) : nat_scope. Notation "\prod_ ( i 'in' A ) F" := (\big[*%N/1%N]_(i in A) F%N) : nat_scope. Notation "\max_ ( i <- r | P ) F" := (\big[maxn/0%N]_(i <- r | P%B) F%N) : nat_scope. Notation "\max_ ( i <- r ) F" := (\big[maxn/0%N]_(i <- r) F%N) : nat_scope. Notation "\max_ ( i | P ) F" := (\big[maxn/0%N]_(i | P%B) F%N) : nat_scope. Notation "\max_ i F" := (\big[maxn/0%N]_i F%N) : nat_scope. Notation "\max_ ( i : I | P ) F" := (\big[maxn/0%N]_(i : I | P%B) F%N) (only parsing) : nat_scope. Notation "\max_ ( i : I ) F" := (\big[maxn/0%N]_(i : I) F%N) (only parsing) : nat_scope. Notation "\max_ ( m <= i < n | P ) F" := (\big[maxn/0%N]_(m <= i < n | P%B) F%N) : nat_scope. Notation "\max_ ( m <= i < n ) F" := (\big[maxn/0%N]_(m <= i < n) F%N) : nat_scope. Notation "\max_ ( i < n | P ) F" := (\big[maxn/0%N]_(i < n | P%B) F%N) : nat_scope. Notation "\max_ ( i < n ) F" := (\big[maxn/0%N]_(i < n) F%N) : nat_scope. Notation "\max_ ( i 'in' A | P ) F" := (\big[maxn/0%N]_(i in A | P%B) F%N) : nat_scope. Notation "\max_ ( i 'in' A ) F" := (\big[maxn/0%N]_(i in A) F%N) : nat_scope. (* Induction loading *) Lemma big_load R (K K' : R -> Type) idx op I r (P : pred I) F : K (\big[op/idx]_(i <- r | P i) F i) * K' (\big[op/idx]_(i <- r | P i) F i) -> K' (\big[op/idx]_(i <- r | P i) F i). Proof. by case. Qed. Arguments big_load [R] K [K'] idx op [I]. Section Elim3. Variables (R1 R2 R3 : Type) (K : R1 -> R2 -> R3 -> Type). Variables (id1 : R1) (op1 : R1 -> R1 -> R1). Variables (id2 : R2) (op2 : R2 -> R2 -> R2). Variables (id3 : R3) (op3 : R3 -> R3 -> R3). Hypothesis Kid : K id1 id2 id3. Lemma big_rec3 I r (P : pred I) F1 F2 F3 (K_F : forall i y1 y2 y3, P i -> K y1 y2 y3 -> K (op1 (F1 i) y1) (op2 (F2 i) y2) (op3 (F3 i) y3)) : K (\big[op1/id1]_(i <- r | P i) F1 i) (\big[op2/id2]_(i <- r | P i) F2 i) (\big[op3/id3]_(i <- r | P i) F3 i). Proof. by rewrite unlock; elim: r => //= i r; case: ifP => //; apply: K_F. Qed. Hypothesis Kop : forall x1 x2 x3 y1 y2 y3, K x1 x2 x3 -> K y1 y2 y3-> K (op1 x1 y1) (op2 x2 y2) (op3 x3 y3). Lemma big_ind3 I r (P : pred I) F1 F2 F3 (K_F : forall i, P i -> K (F1 i) (F2 i) (F3 i)) : K (\big[op1/id1]_(i <- r | P i) F1 i) (\big[op2/id2]_(i <- r | P i) F2 i) (\big[op3/id3]_(i <- r | P i) F3 i). Proof. by apply: big_rec3 => i x1 x2 x3 /K_F; apply: Kop. Qed. End Elim3. Arguments big_rec3 [R1 R2 R3] K [id1 op1 id2 op2 id3 op3] _ [I r P F1 F2 F3]. Arguments big_ind3 [R1 R2 R3] K [id1 op1 id2 op2 id3 op3] _ _ [I r P F1 F2 F3]. Section Elim2. Variables (R1 R2 : Type) (K : R1 -> R2 -> Type) (f : R2 -> R1). Variables (id1 : R1) (op1 : R1 -> R1 -> R1). Variables (id2 : R2) (op2 : R2 -> R2 -> R2). Hypothesis Kid : K id1 id2. Lemma big_rec2 I r (P : pred I) F1 F2 (K_F : forall i y1 y2, P i -> K y1 y2 -> K (op1 (F1 i) y1) (op2 (F2 i) y2)) : K (\big[op1/id1]_(i <- r | P i) F1 i) (\big[op2/id2]_(i <- r | P i) F2 i). Proof. by rewrite unlock; elim: r => //= i r; case: ifP => //; apply: K_F. Qed. Hypothesis Kop : forall x1 x2 y1 y2, K x1 x2 -> K y1 y2 -> K (op1 x1 y1) (op2 x2 y2). Lemma big_ind2 I r (P : pred I) F1 F2 (K_F : forall i, P i -> K (F1 i) (F2 i)) : K (\big[op1/id1]_(i <- r | P i) F1 i) (\big[op2/id2]_(i <- r | P i) F2 i). Proof. by apply: big_rec2 => i x1 x2 /K_F; apply: Kop. Qed. Hypotheses (f_op : {morph f : x y / op2 x y >-> op1 x y}) (f_id : f id2 = id1). Lemma big_morph I r (P : pred I) F : f (\big[op2/id2]_(i <- r | P i) F i) = \big[op1/id1]_(i <- r | P i) f (F i). Proof. by rewrite unlock; elim: r => //= i r <-; rewrite -f_op -fun_if. Qed. End Elim2. Arguments big_rec2 [R1 R2] K [id1 op1 id2 op2] _ [I r P F1 F2]. Arguments big_ind2 [R1 R2] K [id1 op1 id2 op2] _ _ [I r P F1 F2]. Arguments big_morph [R1 R2] f [id1 op1 id2 op2] _ _ [I]. Section Elim1. Variables (R : Type) (K : R -> Type) (f : R -> R). Variables (idx : R) (op op' : R -> R -> R). Hypothesis Kid : K idx. Lemma big_rec I r (P : pred I) F (Kop : forall i x, P i -> K x -> K (op (F i) x)) : K (\big[op/idx]_(i <- r | P i) F i). Proof. by rewrite unlock; elim: r => //= i r; case: ifP => //; apply: Kop. Qed. Hypothesis Kop : forall x y, K x -> K y -> K (op x y). Lemma big_ind I r (P : pred I) F (K_F : forall i, P i -> K (F i)) : K (\big[op/idx]_(i <- r | P i) F i). Proof. by apply: big_rec => // i x /K_F /Kop; apply. Qed. Hypothesis Kop' : forall x y, K x -> K y -> op x y = op' x y. Lemma eq_big_op I r (P : pred I) F (K_F : forall i, P i -> K (F i)) : \big[op/idx]_(i <- r | P i) F i = \big[op'/idx]_(i <- r | P i) F i. Proof. by elim/(big_load K): _; elim/big_rec2: _ => // i _ y Pi [Ky <-]; auto. Qed. Hypotheses (fM : {morph f : x y / op x y}) (f_id : f idx = idx). Lemma big_endo I r (P : pred I) F : f (\big[op/idx]_(i <- r | P i) F i) = \big[op/idx]_(i <- r | P i) f (F i). Proof. exact: big_morph. Qed. End Elim1. Arguments big_rec [R] K [idx op] _ [I r P F]. Arguments big_ind [R] K [idx op] _ _ [I r P F]. Arguments eq_big_op [R] K [idx op] op' _ _ _ [I]. Arguments big_endo [R] f [idx op] _ _ [I]. Lemma big_morph_in (R1 R2 : Type) (Q : {pred R2}) (f : R2 -> R1) (id1 : R1) (op1 : R1 -> R1 -> R1) (id2 : R2) (op2 : R2 -> R2 -> R2) : {in Q &, forall x y, op2 x y \in Q} -> id2 \in Q -> {in Q &, {morph f : x y / op2 x y >-> op1 x y}} -> f id2 = id1 -> forall [I : Type] (r : seq I) (P : pred I) (F : I -> R2), (forall i, P i -> F i \in Q) -> f (\big[op2/id2]_(i <- r | P i) F i) = \big[op1/id1]_(i <- r | P i) f (F i). Proof. move=> Qop Qid fop fid I r P F QF; elim/(big_load Q): _. by elim/big_rec2: _ => // j x y Pj [Qx <-]; rewrite [Q _]Qop ?fop ?QF. Qed. Arguments big_morph_in [R1 R2] Q f [id1 op1 id2 op2]. Section oAC. Variables (T : Type) (op : T -> T -> T). Definition oAC of associative op & commutative op := fun x => oapp (fun y => Some (oapp (op^~ y) y x)) x. Arguments oAC : simpl never. Hypothesis (opA : associative op) (opC : commutative op). Local Notation oop := (oAC opA opC). Lemma oACE x y : oop (Some x) (Some y) = some (op x y). Proof. by []. Qed. Lemma oopA_subdef : associative oop. Proof. by move=> [x|] [y|] [z|]//; rewrite /oAC/= opA. Qed. Lemma oopx1_subdef : left_id None oop. Proof. by case. Qed. Lemma oop1x_subdef : right_id None oop. Proof. by []. Qed. Lemma oopC_subdef : commutative oop. Proof. by move=> [x|] [y|]//; rewrite /oAC/= opC. Qed. HB.instance Definition _ := Monoid.isComLaw.Build (option T) None oop oopA_subdef oopC_subdef oopx1_subdef. Context [x : T]. Lemma some_big_AC_mk_monoid [I : Type] r P (F : I -> T) : Some (\big[op/x]_(i <- r | P i) F i) = oop (\big[oop/None]_(i <- r | P i) Some (F i)) (Some x). Proof. by elim/big_rec2 : _ => //= i [y|] _ Pi [] -> //=; rewrite opA. Qed. Lemma big_AC_mk_monoid [I : Type] r P (F : I -> T) : \big[op/x]_(i <- r | P i) F i = odflt x (oop (\big[oop/None]_(i <- r | P i) Some (F i)) (Some x)). Proof. by apply: Some_inj; rewrite some_big_AC_mk_monoid. Qed. End oAC. Arguments oAC : simpl never. Section Extensionality. Variables (R : Type) (idx : R) (op : R -> R -> R). Section SeqExtension. Variable I : Type. Lemma foldrE r : foldr op idx r = \big[op/idx]_(x <- r) x. Proof. by rewrite unlock. Qed. Lemma big_filter r (P : pred I) F : \big[op/idx]_(i <- filter P r) F i = \big[op/idx]_(i <- r | P i) F i. Proof. by rewrite unlock; elim: r => //= i r <-; case (P i). Qed. Lemma big_filter_cond r (P1 P2 : pred I) F : \big[op/idx]_(i <- filter P1 r | P2 i) F i = \big[op/idx]_(i <- r | P1 i && P2 i) F i. Proof. rewrite -big_filter -(big_filter r); congr bigop. by rewrite -filter_predI; apply: eq_filter => i; apply: andbC. Qed. Lemma eq_bigl r (P1 P2 : pred I) F : P1 =1 P2 -> \big[op/idx]_(i <- r | P1 i) F i = \big[op/idx]_(i <- r | P2 i) F i. Proof. by move=> eqP12; rewrite -!(big_filter r) (eq_filter eqP12). Qed. (* A lemma to permute aggregate conditions. *) Lemma big_andbC r (P Q : pred I) F : \big[op/idx]_(i <- r | P i && Q i) F i = \big[op/idx]_(i <- r | Q i && P i) F i. Proof. by apply: eq_bigl => i; apply: andbC. Qed. Lemma eq_bigr r (P : pred I) F1 F2 : (forall i, P i -> F1 i = F2 i) -> \big[op/idx]_(i <- r | P i) F1 i = \big[op/idx]_(i <- r | P i) F2 i. Proof. by move=> eqF12; elim/big_rec2: _ => // i x _ /eqF12-> ->. Qed. Lemma eq_big r (P1 P2 : pred I) F1 F2 : P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) -> \big[op/idx]_(i <- r | P1 i) F1 i = \big[op/idx]_(i <- r | P2 i) F2 i. Proof. by move/eq_bigl <-; move/eq_bigr->. Qed. Lemma congr_big r1 r2 (P1 P2 : pred I) F1 F2 : r1 = r2 -> P1 =1 P2 -> (forall i, P1 i -> F1 i = F2 i) -> \big[op/idx]_(i <- r1 | P1 i) F1 i = \big[op/idx]_(i <- r2 | P2 i) F2 i. Proof. by move=> <-{r2}; apply: eq_big. Qed. Lemma big_nil (P : pred I) F : \big[op/idx]_(i <- [::] | P i) F i = idx. Proof. by rewrite unlock. Qed. Lemma big_cons i r (P : pred I) F : let x := \big[op/idx]_(j <- r | P j) F j in \big[op/idx]_(j <- i :: r | P j) F j = if P i then op (F i) x else x. Proof. by rewrite unlock. Qed. Lemma big_rcons_op i r (P : pred I) F : let idx' := if P i then op (F i) idx else idx in \big[op/idx]_(j <- rcons r i | P j) F j = \big[op/idx']_(j <- r | P j) F j. Proof. by elim: r => /= [|j r]; rewrite !(big_nil, big_cons, unlock)// => ->. Qed. Lemma big_map J (h : J -> I) r (P : pred I) F : \big[op/idx]_(i <- map h r | P i) F i = \big[op/idx]_(j <- r | P (h j)) F (h j). Proof. by rewrite unlock; elim: r => //= j r ->. Qed. Lemma big_nth x0 r (P : pred I) F : \big[op/idx]_(i <- r | P i) F i = \big[op/idx]_(0 <= i < size r | P (nth x0 r i)) (F (nth x0 r i)). Proof. by rewrite -[r in LHS](mkseq_nth x0) big_map /index_iota subn0. Qed. Lemma big_hasC r (P : pred I) F : ~~ has P r -> \big[op/idx]_(i <- r | P i) F i = idx. Proof. by rewrite -big_filter has_count -size_filter -eqn0Ngt unlock => /nilP->. Qed. Lemma big_pred0_eq (r : seq I) F : \big[op/idx]_(i <- r | false) F i = idx. Proof. by rewrite big_hasC // has_pred0. Qed. Lemma big_pred0 r (P : pred I) F : P =1 xpred0 -> \big[op/idx]_(i <- r | P i) F i = idx. Proof. by move/eq_bigl->; apply: big_pred0_eq. Qed. Lemma big_cat_nested r1 r2 (P : pred I) F : let x := \big[op/idx]_(i <- r2 | P i) F i in \big[op/idx]_(i <- r1 ++ r2 | P i) F i = \big[op/x]_(i <- r1 | P i) F i. Proof. by rewrite unlock /reducebig foldr_cat. Qed. Lemma big_catl r1 r2 (P : pred I) F : ~~ has P r2 -> \big[op/idx]_(i <- r1 ++ r2 | P i) F i = \big[op/idx]_(i <- r1 | P i) F i. Proof. by rewrite big_cat_nested => /big_hasC->. Qed. Lemma big_catr r1 r2 (P : pred I) F : ~~ has P r1 -> \big[op/idx]_(i <- r1 ++ r2 | P i) F i = \big[op/idx]_(i <- r2 | P i) F i. Proof. rewrite -big_filter -(big_filter r2) filter_cat. by rewrite has_count -size_filter; case: filter. Qed. End SeqExtension. Lemma big_map_id J (h : J -> R) r (P : pred R) : \big[op/idx]_(i <- map h r | P i) i = \big[op/idx]_(j <- r | P (h j)) h j. Proof. exact: big_map. Qed. Lemma big_condT (J : finType) (A : {pred J}) F : \big[op/idx]_(i in A | true) F i = \big[op/idx]_(i in A) F i. Proof. by apply: eq_bigl => i; exact: andbT. Qed. (* The following lemmas can be used to localise extensionality to a specific *) (* index sequence. This is done by ssreflect rewriting, before applying *) (* congruence or induction lemmas. *) Lemma big_seq_cond (I : eqType) r (P : pred I) F : \big[op/idx]_(i <- r | P i) F i = \big[op/idx]_(i <- r | (i \in r) && P i) F i. Proof. by rewrite -!(big_filter r); congr bigop; apply: eq_in_filter => i ->. Qed. Lemma big_seq (I : eqType) (r : seq I) F : \big[op/idx]_(i <- r) F i = \big[op/idx]_(i <- r | i \in r) F i. Proof. by rewrite big_seq_cond big_andbC. Qed. Lemma eq_big_seq (I : eqType) (r : seq I) F1 F2 : {in r, F1 =1 F2} -> \big[op/idx]_(i <- r) F1 i = \big[op/idx]_(i <- r) F2 i. Proof. by move=> eqF; rewrite !big_seq (eq_bigr _ eqF). Qed. (* Similar lemmas for exposing integer indexing in the predicate. *) Lemma big_nat_cond m n (P : pred nat) F : \big[op/idx]_(m <= i < n | P i) F i = \big[op/idx]_(m <= i < n | (m <= i < n) && P i) F i. Proof. by rewrite big_seq_cond; apply: eq_bigl => i; rewrite mem_index_iota. Qed. Lemma big_nat m n F : \big[op/idx]_(m <= i < n) F i = \big[op/idx]_(m <= i < n | m <= i < n) F i. Proof. by rewrite big_nat_cond big_andbC. Qed. Lemma congr_big_nat m1 n1 m2 n2 P1 P2 F1 F2 : m1 = m2 -> n1 = n2 -> (forall i, m1 <= i < n2 -> P1 i = P2 i) -> (forall i, P1 i && (m1 <= i < n2) -> F1 i = F2 i) -> \big[op/idx]_(m1 <= i < n1 | P1 i) F1 i = \big[op/idx]_(m2 <= i < n2 | P2 i) F2 i. Proof. move=> <- <- eqP12 eqF12; rewrite big_seq_cond (big_seq_cond _ P2). apply: eq_big => i; rewrite ?inE /= !mem_index_iota. by apply: andb_id2l; apply: eqP12. by rewrite andbC; apply: eqF12. Qed. Lemma eq_big_nat m n F1 F2 : (forall i, m <= i < n -> F1 i = F2 i) -> \big[op/idx]_(m <= i < n) F1 i = \big[op/idx]_(m <= i < n) F2 i. Proof. by move=> eqF; apply: congr_big_nat. Qed. Lemma big_geq m n (P : pred nat) F : m >= n -> \big[op/idx]_(m <= i < n | P i) F i = idx. Proof. by move=> ge_m_n; rewrite /index_iota (eqnP ge_m_n) big_nil. Qed. Lemma big_ltn_cond m n (P : pred nat) F : m < n -> let x := \big[op/idx]_(m.+1 <= i < n | P i) F i in \big[op/idx]_(m <= i < n | P i) F i = if P m then op (F m) x else x. Proof. by case: n => [//|n] le_m_n; rewrite /index_iota subSn // big_cons. Qed. Lemma big_ltn m n F : m < n -> \big[op/idx]_(m <= i < n) F i = op (F m) (\big[op/idx]_(m.+1 <= i < n) F i). Proof. by move=> lt_mn; apply: big_ltn_cond. Qed. Lemma big_addn m n a (P : pred nat) F : \big[op/idx]_(m + a <= i < n | P i) F i = \big[op/idx]_(m <= i < n - a | P (i + a)) F (i + a). Proof. rewrite /index_iota -subnDA addnC iotaDl big_map. by apply: eq_big => ? *; rewrite addnC. Qed. Lemma big_add1 m n (P : pred nat) F : \big[op/idx]_(m.+1 <= i < n | P i) F i = \big[op/idx]_(m <= i < n.-1 | P (i.+1)) F (i.+1). Proof. by rewrite -addn1 big_addn subn1; apply: eq_big => ? *; rewrite addn1. Qed. Lemma big_nat_recl n m F : m <= n -> \big[op/idx]_(m <= i < n.+1) F i = op (F m) (\big[op/idx]_(m <= i < n) F i.+1). Proof. by move=> lemn; rewrite big_ltn // big_add1. Qed. Lemma big_mkord n (P : pred nat) F : \big[op/idx]_(0 <= i < n | P i) F i = \big[op/idx]_(i < n | P i) F i. Proof. rewrite /index_iota subn0 -(big_map (@nat_of_ord n)). by congr bigop; rewrite /index_enum 2!unlock val_ord_enum. Qed. Lemma big_mknat n (P : pred 'I_n.+1) F : \big[op/idx]_(i < n.+1 | P i) F i = \big[op/idx]_(0 <= i < n.+1 | P (inord i)) F (inord i). Proof. by rewrite big_mkord; apply: eq_big => ?; rewrite inord_val. Qed. Lemma big_nat_widen m n1 n2 (P : pred nat) F : n1 <= n2 -> \big[op/idx]_(m <= i < n1 | P i) F i = \big[op/idx]_(m <= i < n2 | P i && (i < n1)) F i. Proof. move=> len12; symmetry; rewrite -big_filter filter_predI big_filter. have [ltn_trans eq_by_mem] := (ltn_trans, irr_sorted_eq ltn_trans ltnn). congr bigop; apply: eq_by_mem; rewrite ?sorted_filter ?iota_ltn_sorted // => i. rewrite mem_filter !mem_index_iota andbCA andbA andb_idr => // /andP[_]. by move/leq_trans->. Qed. Lemma big_ord_widen_cond n1 n2 (P : pred nat) (F : nat -> R) : n1 <= n2 -> \big[op/idx]_(i < n1 | P i) F i = \big[op/idx]_(i < n2 | P i && (i < n1)) F i. Proof. by move/big_nat_widen=> len12; rewrite -big_mkord len12 big_mkord. Qed. Lemma big_ord_widen n1 n2 (F : nat -> R) : n1 <= n2 -> \big[op/idx]_(i < n1) F i = \big[op/idx]_(i < n2 | i < n1) F i. Proof. by move=> le_n12; apply: (big_ord_widen_cond (predT)). Qed. Lemma big_ord_widen_leq n1 n2 (P : pred 'I_(n1.+1)) F : n1 < n2 -> \big[op/idx]_(i < n1.+1 | P i) F i = \big[op/idx]_(i < n2 | P (inord i) && (i <= n1)) F (inord i). Proof. move=> len12; pose g G i := G (inord i : 'I_(n1.+1)). rewrite -(big_ord_widen_cond (g _ P) (g _ F) len12) {}/g. by apply: eq_big => i *; rewrite inord_val. Qed. Lemma big_ord0 P F : \big[op/idx]_(i < 0 | P i) F i = idx. Proof. by rewrite big_pred0 => [|[]]. Qed. Lemma big_mask_tuple I n m (t : n.-tuple I) (P : pred I) F : \big[op/idx]_(i <- mask m t | P i) F i = \big[op/idx]_(i < n | nth false m i && P (tnth t i)) F (tnth t i). Proof. rewrite [t in LHS]tuple_map_ord/= -map_mask big_map. by rewrite mask_enum_ord big_filter_cond/= enumT. Qed. Lemma big_mask I r m (P : pred I) (F : I -> R) (r_ := tnth (in_tuple r)) : \big[op/idx]_(i <- mask m r | P i) F i = \big[op/idx]_(i < size r | nth false m i && P (r_ i)) F (r_ i). Proof. exact: (big_mask_tuple _ (in_tuple r)). Qed. Lemma big_tnth I r (P : pred I) F (r_ := tnth (in_tuple r)) : \big[op/idx]_(i <- r | P i) F i = \big[op/idx]_(i < size r | P (r_ i)) (F (r_ i)). Proof. rewrite /= -[r in LHS](mask_true (leqnn (size r))) big_mask//. by apply: eq_bigl => i /=; rewrite nth_nseq ltn_ord. Qed. Lemma big_index_uniq (I : eqType) (r : seq I) (E : 'I_(size r) -> R) : uniq r -> \big[op/idx]_i E i = \big[op/idx]_(x <- r) oapp E idx (insub (index x r)). Proof. move=> Ur; apply/esym; rewrite big_tnth. by under [LHS]eq_bigr do rewrite index_uniq// valK. Qed. Lemma big_tuple I n (t : n.-tuple I) (P : pred I) F : \big[op/idx]_(i <- t | P i) F i = \big[op/idx]_(i < n | P (tnth t i)) F (tnth t i). Proof. by rewrite big_tnth tvalK; case: _ / (esym _). Qed. Lemma big_ord_narrow_cond n1 n2 (P : pred 'I_n2) F (le_n12 : n1 <= n2) : let w := widen_ord le_n12 in \big[op/idx]_(i < n2 | P i && (i < n1)) F i = \big[op/idx]_(i < n1 | P (w i)) F (w i). Proof. case: n1 => [|n1] /= in le_n12 *. by rewrite big_ord0 big_pred0 // => i; rewrite andbF. rewrite (big_ord_widen_leq _ _ le_n12); apply: eq_big => i. by apply: andb_id2r => le_i_n1; congr P; apply: val_inj; rewrite /= inordK. by case/andP=> _ le_i_n1; congr F; apply: val_inj; rewrite /= inordK. Qed. Lemma big_ord_narrow_cond_leq n1 n2 (P : pred _) F (le_n12 : n1 <= n2) : let w := @widen_ord n1.+1 n2.+1 le_n12 in \big[op/idx]_(i < n2.+1 | P i && (i <= n1)) F i = \big[op/idx]_(i < n1.+1 | P (w i)) F (w i). Proof. exact: (@big_ord_narrow_cond n1.+1 n2.+1). Qed. Lemma big_ord_narrow n1 n2 F (le_n12 : n1 <= n2) : let w := widen_ord le_n12 in \big[op/idx]_(i < n2 | i < n1) F i = \big[op/idx]_(i < n1) F (w i). Proof. exact: (big_ord_narrow_cond (predT)). Qed. Lemma big_ord_narrow_leq n1 n2 F (le_n12 : n1 <= n2) : let w := @widen_ord n1.+1 n2.+1 le_n12 in \big[op/idx]_(i < n2.+1 | i <= n1) F i = \big[op/idx]_(i < n1.+1) F (w i). Proof. exact: (big_ord_narrow_cond_leq (predT)). Qed. Lemma big_ord_recl n F : \big[op/idx]_(i < n.+1) F i = op (F ord0) (\big[op/idx]_(i < n) F (@lift n.+1 ord0 i)). Proof. pose G i := F (inord i); have eqFG i: F i = G i by rewrite /G inord_val. under eq_bigr do rewrite eqFG; under [in RHS]eq_bigr do rewrite eqFG. by rewrite -(big_mkord _ (fun _ => _) G) eqFG big_ltn // big_add1 /= big_mkord. Qed. Lemma big_nseq_cond I n a (P : pred I) F : \big[op/idx]_(i <- nseq n a | P i) F i = if P a then iter n (op (F a)) idx else idx. Proof. by rewrite unlock; elim: n => /= [|n ->]; case: (P a). Qed. Lemma big_nseq I n a (F : I -> R): \big[op/idx]_(i <- nseq n a) F i = iter n (op (F a)) idx. Proof. exact: big_nseq_cond. Qed. End Extensionality. Variant big_enum_spec (I : finType) (P : pred I) : seq I -> Type := BigEnumSpec e of forall R idx op (F : I -> R), \big[op/idx]_(i <- e) F i = \big[op/idx]_(i | P i) F i & uniq e /\ (forall i, i \in e = P i) & (let cP := [pred i | P i] in perm_eq e (enum cP) /\ size e = #|cP|) : big_enum_spec P e. (* This lemma can be used to introduce an enumeration into a non-abelian *) (* bigop, in one of three ways: *) (* have [e big_e [Ue mem_e] [e_enum size_e]] := big_enumP P. *) (* gives a permutation e of enum P alongside a equation big_e for converting *) (* between bigops iterating on (i <- e) and ones on (i | P i). Usually not *) (* all properties of e are needed, but see below the big_distr_big_dep proof *) (* where most are. *) (* rewrite -big_filter; have [e ...] := big_enumP. *) (* uses big_filter to do this conversion first, and then abstracts the *) (* resulting filter P (index_enum T) enumeration as an e with the same *) (* properties (see big_enum_cond below for an example of this usage). *) (* Finally *) (* rewrite -big_filter; case def_e: _ / big_enumP => [e ...] *) (* does the same while remembering the definition of e. *) Lemma big_enumP I P : big_enum_spec P (filter P (index_enum I)). Proof. set e := filter P _; have Ue: uniq e by apply/filter_uniq/index_enum_uniq. have mem_e i: i \in e = P i by rewrite mem_filter mem_index_enum andbT. split=> // [R idx op F | cP]; first by rewrite big_filter. suffices De: perm_eq e (enum cP) by rewrite (perm_size De) cardE. by apply/uniq_perm=> // [|i]; rewrite ?enum_uniq ?mem_enum ?mem_e. Qed. Section BigConst. Variables (R : Type) (idx : R) (op : R -> R -> R). Lemma big_const_seq I r (P : pred I) x : \big[op/idx]_(i <- r | P i) x = iter (count P r) (op x) idx. Proof. by rewrite unlock; elim: r => //= i r ->; case: (P i). Qed. Lemma big_const (I : finType) (A : {pred I}) x : \big[op/idx]_(i in A) x = iter #|A| (op x) idx. Proof. by have [e <- _ [_ <-]] := big_enumP A; rewrite big_const_seq count_predT. Qed. Lemma big_const_nat m n x : \big[op/idx]_(m <= i < n) x = iter (n - m) (op x) idx. Proof. by rewrite big_const_seq count_predT size_iota. Qed. Lemma big_const_ord n x : \big[op/idx]_(i < n) x = iter n (op x) idx. Proof. by rewrite big_const card_ord. Qed. End BigConst. Section Plain. Variable R : Type. Variable op : R -> R -> R. Variable x : R. Lemma big_seq1_id I (i : I) (F : I -> R) : \big[op/x]_(j <- [:: i]) F j = op (F i) x. Proof. by rewrite big_cons big_nil. Qed. Lemma big_nat1_id n F : \big[op/x]_(n <= i < n.+1) F i = op (F n) x. Proof. by rewrite big_ltn // big_geq // mulm1. Qed. Lemma big_pred1_eq_id (I : finType) (i : I) F : \big[op/x]_(j | j == i) F j = op (F i) x. Proof. have [e1 <- _ [e_enum _]] := big_enumP (pred1 i). by rewrite (perm_small_eq _ e_enum) enum1 ?big_seq1_id. Qed. Lemma big_pred1_id (I : finType) i (P : pred I) F : P =1 pred1 i -> \big[op/x]_(j | P j) F j = op (F i) x. Proof. by move/(eq_bigl _ _)->; apply: big_pred1_eq_id. Qed. End Plain. Section SemiGroupProperties. Variable R : Type. #[local] Notation opA := SemiGroup.opA. #[local] Notation opC := SemiGroup.opC. Section Id. Variable op : SemiGroup.law R. Variable x : R. Hypothesis opxx : op x x = x. Lemma big_const_idem I (r : seq I) P : \big[op/x]_(i <- r | P i) x = x. Proof. by elim/big_ind : _ => // _ _ -> ->. Qed. Lemma big1_idem I r (P : pred I) F : (forall i, P i -> F i = x) -> \big[op/x]_(i <- r | P i) F i = x. Proof. move=> Fix; under eq_bigr => ? ? do rewrite Fix//; exact: big_const_idem. Qed. Lemma big_id_idem I (r : seq I) P F : op (\big[op/x]_(i <- r | P i) F i) x = \big[op/x]_(i <- r | P i) F i. Proof. by elim/big_rec : _ => // ? ? ?; rewrite -opA => ->. Qed. End Id. Section Abelian. Variable op : SemiGroup.com_law R. Let opCA : left_commutative op. Proof. by move=> x *; rewrite !opA /= (opC x). Qed. Variable x : R. Lemma big_rem_AC (I : eqType) (r : seq I) z (P : pred I) F : z \in r -> \big[op/x]_(y <- r | P y) F y = if P z then op (F z) (\big[op/x]_(y <- rem z r | P y) F y) else \big[op/x]_(y <- rem z r | P y) F y. Proof. elim: r =>// i r ih; rewrite big_cons rem_cons inE =>/predU1P[-> /[!eqxx]//|zr]. by case: eqP => [-> //|]; rewrite ih// big_cons; case: ifPn; case: ifPn. Qed. Lemma big_undup (I : eqType) (r : seq I) (P : pred I) F : idempotent_op op -> \big[op/x]_(i <- undup r | P i) F i = \big[op/x]_(i <- r | P i) F i. Proof. move=> opxx; rewrite -!(big_filter _ _ _ P) filter_undup. elim: {P r}(filter P r) => //= i r IHr. case: ifP => [r_i | _]; rewrite !big_cons {}IHr //. by rewrite (big_rem_AC _ _ r_i) opA /= opxx. Qed. Lemma perm_big (I : eqType) r1 r2 (P : pred I) F : perm_eq r1 r2 -> \big[op/x]_(i <- r1 | P i) F i = \big[op/x]_(i <- r2 | P i) F i. Proof. elim: r1 r2 => [|i r1 IHr1] r2 eq_r12. by case: r2 eq_r12 => [//|i r2] /[1!perm_sym] /perm_nilP. have r2i: i \in r2 by rewrite -has_pred1 has_count -(permP eq_r12) /= eqxx. rewrite big_cons (IHr1 (rem i r2)) -?big_rem_AC// -(perm_cons i). exact: perm_trans (perm_to_rem _). Qed. Lemma big_enum_cond (I : finType) (A : {pred I}) (P : pred I) F : \big[op/x]_(i <- enum A | P i) F i = \big[op/x]_(i in A | P i) F i. Proof. by rewrite -big_filter_cond; have [e _ _ [/perm_big->]] := big_enumP. Qed. Lemma big_enum (I : finType) (A : {pred I}) F : \big[op/x]_(i <- enum A) F i = \big[op/x]_(i in A) F i. Proof. by rewrite big_enum_cond big_andbC. Qed. Lemma big_uniq (I : finType) (r : seq I) F : uniq r -> \big[op/x]_(i <- r) F i = \big[op/x]_(i in r) F i. Proof. move=> uniq_r; rewrite -big_enum; apply: perm_big. by rewrite uniq_perm ?enum_uniq // => i; rewrite mem_enum. Qed. Lemma bigD1 (I : finType) j (P : pred I) F : P j -> \big[op/x]_(i | P i) F i = op (F j) (\big[op/x]_(i | P i && (i != j)) F i). Proof. rewrite (big_rem_AC _ _ (mem_index_enum j)) => ->. by rewrite rem_filter ?index_enum_uniq// big_filter_cond big_andbC. Qed. Arguments bigD1 [I] j [P F]. Lemma bigD1_seq (I : eqType) (r : seq I) j F : j \in r -> uniq r -> \big[op/x]_(i <- r) F i = op (F j) (\big[op/x]_(i <- r | i != j) F i). Proof. by move=> /big_rem_AC-> /rem_filter->; rewrite big_filter. Qed. Lemma big_image_cond I (J : finType) (h : J -> I) (A : pred J) (P : pred I) F : \big[op/x]_(i <- [seq h j | j in A] | P i) F i = \big[op/x]_(j in A | P (h j)) F (h j). Proof. by rewrite big_map big_enum_cond. Qed. Lemma big_image I (J : finType) (h : J -> I) (A : pred J) F : \big[op/x]_(i <- [seq h j | j in A]) F i = \big[op/x]_(j in A) F (h j). Proof. by rewrite big_map big_enum. Qed. Lemma cardD1x (I : finType) (A : pred I) j : A j -> #|SimplPred A| = 1 + #|[pred i | A i & i != j]|. Proof. move=> Aj; rewrite (cardD1 j) [j \in A]Aj; congr (_ + _). by apply: eq_card => i; rewrite inE /= andbC. Qed. Arguments cardD1x [I A]. Lemma reindex_omap (I J : finType) (h : J -> I) h' (P : pred I) F : (forall i, P i -> omap h (h' i) = some i) -> \big[op/x]_(i | P i) F i = \big[op/x]_(j | P (h j) && (h' (h j) == some j)) F (h j). Proof. move=> h'K; have [n lePn] := ubnP #|P|; elim: n => // n IHn in P h'K lePn *. case: (pickP P) => [i Pi | P0]; last first. by rewrite !big_pred0 // => j; rewrite P0. have := h'K i Pi; case h'i_eq : (h' i) => [/= j|//] [hj_eq]. rewrite (bigD1 i Pi) (bigD1 j) hj_eq ?Pi ?h'i_eq ?eqxx //=; congr (op : _ -> _). rewrite {}IHn => [|k /andP[]|]; [|by auto | by rewrite (cardD1x i) in lePn]. apply: eq_bigl => k; rewrite andbC -andbA (andbCA (P _)); case: eqP => //= hK. congr (_ && ~~ _); apply/eqP/eqP => [|->//]. by move=> /(congr1 h'); rewrite h'i_eq hK => -[]. Qed. Arguments reindex_omap [I J] h h' [P F]. Lemma reindex_onto (I J : finType) (h : J -> I) h' (P : pred I) F : (forall i, P i -> h (h' i) = i) -> \big[op/x]_(i | P i) F i = \big[op/x]_(j | P (h j) && (h' (h j) == j)) F (h j). Proof. by move=> h'K; rewrite (reindex_omap h (some \o h'))//= => i Pi; rewrite h'K. Qed. Arguments reindex_onto [I J] h h' [P F]. Lemma reindex (I J : finType) (h : J -> I) (P : pred I) F : {on [pred i | P i], bijective h} -> \big[op/x]_(i | P i) F i = \big[op/x]_(j | P (h j)) F (h j). Proof. case=> h' hK h'K; rewrite (reindex_onto h h' h'K). by apply: eq_bigl => j /[!inE]; case Pi: (P _); rewrite //= hK ?eqxx. Qed. Arguments reindex [I J] h [P F]. Lemma reindex_inj (I : finType) (h : I -> I) (P : pred I) F : injective h -> \big[op/x]_(i | P i) F i = \big[op/x]_(j | P (h j)) F (h j). Proof. by move=> injh; apply: reindex (onW_bij _ (injF_bij injh)). Qed. Arguments reindex_inj [I h P F]. Lemma bigD1_ord n j (P : pred 'I_n) F : P j -> \big[op/x]_(i < n | P i) F i = op (F j) (\big[op/x]_(i < n.-1 | P (lift j i)) F (lift j i)). Proof. move=> Pj; rewrite (bigD1 j Pj) (reindex_omap (lift j) (unlift j))/=. by under eq_bigl do rewrite liftK eq_sym eqxx neq_lift ?andbT. by move=> i; case: unliftP => [k ->|->]; rewrite ?eqxx ?andbF. Qed. Lemma big_enum_val_cond (I : finType) (A : pred I) (P : pred I) F : \big[op/x]_(x in A | P x) F x = \big[op/x]_(i < #|A| | P (enum_val i)) F (enum_val i). Proof. have [A_eq0|/card_gt0P[x0 x0A]] := posnP #|A|. rewrite !big_pred0 // => i; last by rewrite card0_eq. by have: false by move: i => []; rewrite A_eq0. rewrite (reindex (enum_val : 'I_#|A| -> I)). by apply: eq_big => [y|y Py]; rewrite ?enum_valP. by apply: subon_bij (enum_val_bij_in x0A) => y /andP[]. Qed. Arguments big_enum_val_cond [I A] P F. Lemma big_enum_rank_cond (I : finType) (A : pred I) z (zA : z \in A) P F (h := enum_rank_in zA) : \big[op/x]_(i < #|A| | P i) F i = \big[op/x]_(s in A | P (h s)) F (h s). Proof. rewrite big_enum_val_cond {}/h. by apply: eq_big => [i|i Pi]; rewrite ?enum_valK_in. Qed. Arguments big_enum_rank_cond [I A z] zA P F. Lemma big_nat_rev m n P F : \big[op/x]_(m <= i < n | P i) F i = \big[op/x]_(m <= i < n | P (m + n - i.+1)) F (m + n - i.+1). Proof. case: (ltnP m n) => ltmn; last by rewrite !big_geq. rewrite -{3 4}(subnK (ltnW ltmn)) addnA. do 2!rewrite (big_addn _ _ 0) big_mkord; rewrite (reindex_inj rev_ord_inj)/=. by apply: eq_big => [i | i _]; rewrite /= -addSn subnDr addnC addnBA. Qed. Lemma big_rev_mkord m n P F : \big[op/x]_(m <= k < n | P k) F k = \big[op/x]_(k < n - m | P (n - k.+1)) F (n - k.+1). Proof. rewrite big_nat_rev (big_addn _ _ 0) big_mkord. by apply: eq_big => [i|i _]; rewrite -addSn addnC subnDr. Qed. Section Id. Hypothesis opxx : op x x = x. Lemma big_mkcond_idem I r (P : pred I) F : \big[op/x]_(i <- r | P i) F i = \big[op/x]_(i <- r) (if P i then F i else x). Proof. elim: r => [|i r]; rewrite ?(big_nil, big_cons)//. by case: ifPn => Pi ->//; rewrite -[in LHS]big_id_idem // opC. Qed. Lemma big_mkcondr_idem I r (P Q : pred I) F : \big[op/x]_(i <- r | P i && Q i) F i = \big[op/x]_(i <- r | P i) (if Q i then F i else x). Proof. by rewrite -big_filter_cond big_mkcond_idem big_filter. Qed. Lemma big_mkcondl_idem I r (P Q : pred I) F : \big[op/x]_(i <- r | P i && Q i) F i = \big[op/x]_(i <- r | Q i) (if P i then F i else x). Proof. by rewrite big_andbC big_mkcondr_idem. Qed. Lemma big_rmcond_idem I (r : seq I) (P : pred I) F : (forall i, ~~ P i -> F i = x) -> \big[op/x]_(i <- r | P i) F i = \big[op/x]_(i <- r) F i. Proof. move=> F_eq1; rewrite big_mkcond_idem; apply: eq_bigr => i. by case: (P i) (F_eq1 i) => // ->. Qed. Lemma big_rmcond_in_idem (I : eqType) (r : seq I) (P : pred I) F : (forall i, i \in r -> ~~ P i -> F i = x) -> \big[op/x]_(i <- r | P i) F i = \big[op/x]_(i <- r) F i. Proof. move=> F_eq1; rewrite big_seq_cond [RHS]big_seq_cond !big_mkcondl_idem. by rewrite big_rmcond_idem => // i /F_eq1; case: ifP => // _ ->. Qed. Lemma big_cat_idem I r1 r2 (P : pred I) F : \big[op/x]_(i <- r1 ++ r2 | P i) F i = op (\big[op/x]_(i <- r1 | P i) F i) (\big[op/x]_(i <- r2 | P i) F i). Proof. elim: r1 => [/=|i r1 IHr1]; first by rewrite big_nil opC big_id_idem. by rewrite /= big_cons IHr1 big_cons; case: (P i); rewrite // opA. Qed. Lemma big_allpairs_dep_idem I1 (I2 : I1 -> Type) J (h : forall i1, I2 i1 -> J) (r1 : seq I1) (r2 : forall i1, seq (I2 i1)) (F : J -> R) : \big[op/x]_(i <- [seq h i1 i2 | i1 <- r1, i2 <- r2 i1]) F i = \big[op/x]_(i1 <- r1) \big[op/x]_(i2 <- r2 i1) F (h i1 i2). Proof. elim: r1 => [|i1 r1 IHr1]; first by rewrite !big_nil. by rewrite big_cat_idem IHr1 big_cons big_map. Qed. Lemma big_allpairs_idem I1 I2 (r1 : seq I1) (r2 : seq I2) F : \big[op/x]_(i <- [seq (i1, i2) | i1 <- r1, i2 <- r2]) F i = \big[op/x]_(i1 <- r1) \big[op/x]_(i2 <- r2) F (i1, i2). Proof. exact: big_allpairs_dep_idem. Qed. Lemma big_cat_nat_idem n m p (P : pred nat) F : m <= n -> n <= p -> \big[op/x]_(m <= i < p | P i) F i = op (\big[op/x]_(m <= i < n | P i) F i) (\big[op/x]_(n <= i < p | P i) F i). Proof. move=> le_mn le_np; rewrite -big_cat_idem -{2}(subnKC le_mn) -iotaD subnDA. by rewrite subnKC // leq_sub. Qed. Lemma big_split_idem I r (P : pred I) F1 F2 : \big[op/x]_(i <- r | P i) op (F1 i) (F2 i) = op (\big[op/x]_(i <- r | P i) F1 i) (\big[op/x]_(i <- r | P i) F2 i). Proof. by elim/big_rec3: _ => [|i x' y _ _ ->]; rewrite ?opxx// opCA -!opA opCA. Qed. Lemma big_id_idem_AC I (r : seq I) P F : \big[op/x]_(i <- r | P i) op (F i) x = \big[op/x]_(i <- r | P i) F i. Proof. by rewrite big_split_idem big_const_idem ?big_id_idem. Qed. Lemma bigID_idem I r (a P : pred I) F : \big[op/x]_(i <- r | P i) F i = op (\big[op/x]_(i <- r | P i && a i) F i) (\big[op/x]_(i <- r | P i && ~~ a i) F i). Proof. rewrite -big_id_idem_AC big_mkcond_idem !(big_mkcond_idem _ _ F) -big_split_idem. by apply: eq_bigr => i; case: ifPn => //=; case: ifPn; rewrite // opC. Qed. Arguments bigID_idem [I r]. Lemma bigU_idem (I : finType) (A B : pred I) F : [disjoint A & B] -> \big[op/x]_(i in [predU A & B]) F i = op (\big[op/x]_(i in A) F i) (\big[op/x]_(i in B) F i). Proof. move=> dAB; rewrite (bigID_idem (mem A)). congr (op : _ -> _); apply: eq_bigl => i; first by rewrite orbK. by have:= pred0P dAB i; rewrite andbC /= !inE; case: (i \in A). Qed. Lemma partition_big_idem I (s : seq I) (J : finType) (P : pred I) (p : I -> J) (Q : pred J) F : (forall i, P i -> Q (p i)) -> \big[op/x]_(i <- s | P i) F i = \big[op/x]_(j : J | Q j) \big[op/x]_(i <- s | (P i) && (p i == j)) F i. Proof. move=> Qp; transitivity (\big[op/x]_(i <- s | P i && Q (p i)) F i). by apply: eq_bigl => i; case Pi: (P i); rewrite // Qp. have [n leQn] := ubnP #|Q|; elim: n => // n IHn in Q {Qp} leQn *. case: (pickP Q) => [j Qj | Q0]; last first. by rewrite !big_pred0 // => i; rewrite Q0 andbF. rewrite (bigD1 j) // -IHn; last by rewrite ltnS (cardD1x j Qj) in leQn. rewrite (bigID_idem (fun i => p i == j)). congr (op : _ -> _); apply: eq_bigl => i; last by rewrite andbA. by case: eqP => [->|_]; rewrite !(Qj, andbT, andbF). Qed. Arguments partition_big_idem [I s J P] p Q [F]. Lemma sig_big_dep_idem (I : finType) (J : I -> finType) (P : pred I) (Q : forall {i}, pred (J i)) (F : forall {i}, J i -> R) : \big[op/x]_(i | P i) \big[op/x]_(j : J i | Q j) F j = \big[op/x]_(p : {i : I & J i} | P (tag p) && Q (tagged p)) F (tagged p). Proof. pose s := [seq Tagged J j | i <- index_enum I, j <- index_enum (J i)]. rewrite [LHS]big_mkcond_idem big_mkcondl_idem. rewrite [RHS]big_mkcond_idem -[RHS](@perm_big _ s). rewrite big_allpairs_dep_idem/=; apply: eq_bigr => i _. by rewrite -big_mkcond_idem/=; case: P; rewrite // big1_idem. rewrite uniq_perm ?index_enum_uniq//. by rewrite allpairs_uniq_dep// => [|i|[i j] []]; rewrite ?index_enum_uniq. by move=> [i j]; rewrite ?mem_index_enum; apply/allpairsPdep; exists i, j. Qed. Lemma pair_big_dep_idem (I J : finType) (P : pred I) (Q : I -> pred J) F : \big[op/x]_(i | P i) \big[op/x]_(j | Q i j) F i j = \big[op/x]_(p | P p.1 && Q p.1 p.2) F p.1 p.2. Proof. rewrite sig_big_dep_idem; apply: (reindex (fun x => Tagged (fun=> J) x.2)). by exists (fun x => (projT1 x, projT2 x)) => -[]. Qed. Lemma pair_big_idem (I J : finType) (P : pred I) (Q : pred J) F : \big[op/x]_(i | P i) \big[op/x]_(j | Q j) F i j = \big[op/x]_(p | P p.1 && Q p.2) F p.1 p.2. Proof. exact: pair_big_dep_idem. Qed. Lemma pair_bigA_idem (I J : finType) (F : I -> J -> R) : \big[op/x]_i \big[op/x]_j F i j = \big[op/x]_p F p.1 p.2. Proof. exact: pair_big_dep_idem. Qed. Lemma exchange_big_dep_idem I J rI rJ (P : pred I) (Q : I -> pred J) (xQ : pred J) F : (forall i j, P i -> Q i j -> xQ j) -> \big[op/x]_(i <- rI | P i) \big[op/x]_(j <- rJ | Q i j) F i j = \big[op/x]_(j <- rJ | xQ j) \big[op/x]_(i <- rI | P i && Q i j) F i j. Proof. move=> PQxQ; pose p u := (u.2, u.1). under [LHS]eq_bigr do rewrite big_tnth; rewrite [LHS]big_tnth. under [RHS]eq_bigr do rewrite big_tnth; rewrite [RHS]big_tnth. rewrite !pair_big_dep_idem (reindex_onto (p _ _) (p _ _)) => [|[]] //=. apply: eq_big => [] [j i] //=; symmetry; rewrite eqxx andbT andb_idl //. by case/andP; apply: PQxQ. Qed. Arguments exchange_big_dep_idem [I J rI rJ P Q] xQ [F]. Lemma exchange_big_idem I J rI rJ (P : pred I) (Q : pred J) F : \big[op/x]_(i <- rI | P i) \big[op/x]_(j <- rJ | Q j) F i j = \big[op/x]_(j <- rJ | Q j) \big[op/x]_(i <- rI | P i) F i j. Proof. rewrite (exchange_big_dep_idem Q) //. by under eq_bigr => i Qi do under eq_bigl do rewrite Qi andbT. Qed. Lemma exchange_big_dep_nat_idem m1 n1 m2 n2 (P : pred nat) (Q : rel nat) (xQ : pred nat) F : (forall i j, m1 <= i < n1 -> m2 <= j < n2 -> P i -> Q i j -> xQ j) -> \big[op/x]_(m1 <= i < n1 | P i) \big[op/x]_(m2 <= j < n2 | Q i j) F i j = \big[op/x]_(m2 <= j < n2 | xQ j) \big[op/x]_(m1 <= i < n1 | P i && Q i j) F i j. Proof. move=> PQxQ; under eq_bigr do rewrite big_seq_cond. rewrite big_seq_cond /= (exchange_big_dep_idem xQ) => [|i j]; last first. by rewrite !mem_index_iota => /andP[mn_i Pi] /andP[mn_j /PQxQ->]. rewrite 2!(big_seq_cond _ _ _ xQ); apply: eq_bigr => j /andP[-> _] /=. by rewrite [rhs in _ = rhs]big_seq_cond; apply: eq_bigl => i; rewrite -andbA. Qed. Arguments exchange_big_dep_nat_idem [m1 n1 m2 n2 P Q] xQ [F]. Lemma exchange_big_nat_idem m1 n1 m2 n2 (P Q : pred nat) F : \big[op/x]_(m1 <= i < n1 | P i) \big[op/x]_(m2 <= j < n2 | Q j) F i j = \big[op/x]_(m2 <= j < n2 | Q j) \big[op/x]_(m1 <= i < n1 | P i) F i j. Proof. rewrite (exchange_big_dep_nat_idem Q) //. by under eq_bigr => i Qi do under eq_bigl do rewrite Qi andbT. Qed. End Id. End Abelian. End SemiGroupProperties. Arguments big_undup [R op x I]. Arguments perm_big [R op x I r1 r2]. Arguments bigD1 [R op x I] j [P F]. Arguments reindex_omap [R op x I J] h h' [P F]. Arguments reindex_onto [R op x I J] h h' [P F]. Arguments reindex [R op x I J] h [P F]. Arguments reindex_inj [R op x I h P F]. Arguments big_enum_val_cond [R op x I A] P F. Arguments big_enum_rank_cond [R op x I A z] zA P F. Section MonoidProperties. Import Monoid.Theory. Variable R : Type. Variable idx : R. Local Notation "1" := idx. Section Plain. Variable op : Monoid.law 1. Local Notation "*%M" := op. Local Notation "x * y" := (op x y). Lemma foldlE x r : foldl *%M x r = \big[*%M/1]_(y <- x :: r) y. Proof. by rewrite -foldrE; elim: r => [|y r IHr]/= in x *; rewrite ?mulm1 ?mulmA ?IHr. Qed. Lemma foldl_idx r : foldl *%M 1 r = \big[*%M/1]_(x <- r) x. Proof. by rewrite foldlE big_cons mul1m. Qed. Lemma eq_big_idx_seq idx' I r (P : pred I) F : right_id idx' *%M -> has P r -> \big[*%M/idx']_(i <- r | P i) F i = \big[*%M/1]_(i <- r | P i) F i. Proof. move=> op_idx'; rewrite -!(big_filter _ _ r) has_count -size_filter. case/lastP: (filter P r) => {r}// r i _. by rewrite -cats1 !(big_cat_nested, big_cons, big_nil) op_idx' mulm1. Qed. Lemma eq_big_idx idx' (I : finType) i0 (P : pred I) F : P i0 -> right_id idx' *%M -> \big[*%M/idx']_(i | P i) F i = \big[*%M/1]_(i | P i) F i. Proof. by move=> Pi0 op_idx'; apply: eq_big_idx_seq => //; apply/hasP; exists i0. Qed. Lemma big_change_idx I x r (P : pred I) F : \big[*%M/x]_(j <- r | P j) F j = (\big[*%M/1]_(j <- r | P j) F j) * x. Proof. elim: r => [|i r]; rewrite ?(big_nil, big_cons, mul1m)// => ->. by case: ifP => // Pi; rewrite mulmA. Qed. Lemma big1_eq I r (P : pred I) : \big[*%M/1]_(i <- r | P i) 1 = 1. Proof. by rewrite big1_idem //= mul1m. Qed. Lemma big1 I r (P : pred I) F : (forall i, P i -> F i = 1) -> \big[*%M/1]_(i <- r | P i) F i = 1. Proof. by move/(eq_bigr _)->; apply: big1_eq. Qed. Lemma big1_seq (I : eqType) r (P : pred I) F : (forall i, P i && (i \in r) -> F i = 1) -> \big[*%M/1]_(i <- r | P i) F i = 1. Proof. by move=> eqF1; rewrite big_seq_cond big_andbC big1. Qed. Lemma big_seq1 I (i : I) F : \big[*%M/1]_(j <- [:: i]) F j = F i. Proof. by rewrite big_seq1_id mulm1. Qed. Lemma big_rcons I i r (P : pred I) F : \big[*%M/1]_(j <- rcons r i | P j) F j = (\big[*%M/1]_(j <- r | P j) F j) * (if P i then F i else idx). Proof. by rewrite big_rcons_op big_change_idx mulm1. Qed. Lemma big_mkcond I r (P : pred I) F : \big[*%M/1]_(i <- r | P i) F i = \big[*%M/1]_(i <- r) (if P i then F i else 1). Proof. by rewrite unlock; elim: r => //= i r ->; case P; rewrite ?mul1m. Qed. Lemma big_mkcondr I r (P Q : pred I) F : \big[*%M/1]_(i <- r | P i && Q i) F i = \big[*%M/1]_(i <- r | P i) (if Q i then F i else 1). Proof. by rewrite -big_filter_cond big_mkcond big_filter. Qed. Lemma big_mkcondl I r (P Q : pred I) F : \big[*%M/1]_(i <- r | P i && Q i) F i = \big[*%M/1]_(i <- r | Q i) (if P i then F i else 1). Proof. by rewrite big_andbC big_mkcondr. Qed. Lemma big_rmcond I (r : seq I) (P : pred I) F : (forall i, ~~ P i -> F i = 1) -> \big[*%M/1]_(i <- r | P i) F i = \big[*%M/1]_(i <- r) F i. Proof. move=> F_eq1; rewrite big_mkcond; apply: eq_bigr => i. by case: (P i) (F_eq1 i) => // ->. Qed. Lemma big_rmcond_in (I : eqType) (r : seq I) (P : pred I) F : (forall i, i \in r -> ~~ P i -> F i = 1) -> \big[*%M/1]_(i <- r | P i) F i = \big[*%M/1]_(i <- r) F i. Proof. move=> F_eq1; rewrite big_seq_cond [RHS]big_seq_cond !big_mkcondl big_rmcond//. by move=> i /F_eq1; case: ifP => // _ ->. Qed. Lemma big_cat I r1 r2 (P : pred I) F : \big[*%M/1]_(i <- r1 ++ r2 | P i) F i = \big[*%M/1]_(i <- r1 | P i) F i * \big[*%M/1]_(i <- r2 | P i) F i. Proof. rewrite !(big_mkcond _ P) unlock. by elim: r1 => /= [|i r1 ->]; rewrite (mul1m, mulmA). Qed. Lemma big_allpairs_dep I1 (I2 : I1 -> Type) J (h : forall i1, I2 i1 -> J) (r1 : seq I1) (r2 : forall i1, seq (I2 i1)) (F : J -> R) : \big[*%M/1]_(i <- [seq h i1 i2 | i1 <- r1, i2 <- r2 i1]) F i = \big[*%M/1]_(i1 <- r1) \big[*%M/1]_(i2 <- r2 i1) F (h i1 i2). Proof. elim: r1 => [|i1 r1 IHr1]; first by rewrite !big_nil. by rewrite big_cat IHr1 big_cons big_map. Qed. Lemma big_allpairs I1 I2 (r1 : seq I1) (r2 : seq I2) F : \big[*%M/1]_(i <- [seq (i1, i2) | i1 <- r1, i2 <- r2]) F i = \big[*%M/1]_(i1 <- r1) \big[op/idx]_(i2 <- r2) F (i1, i2). Proof. exact: big_allpairs_dep. Qed. Lemma rev_big_rev I (r : seq I) P F : \big[*%M/1]_(i <- rev r | P i) F i = \big[(fun x y => y * x)/1]_(i <- r | P i) F i. Proof. elim: r => [|i r IHr]; rewrite ?big_nil// big_cons rev_cons big_rcons IHr. by case: (P i); rewrite ?mulm1. Qed. Lemma big_only1 (I : finType) (i : I) (P : pred I) (F : I -> R) : P i -> (forall j, j != i -> P j -> F j = idx) -> \big[op/idx]_(j | P j) F j = F i. Proof. move=> Pi Fisx; have := index_enum_uniq I. have : i \in index_enum I by rewrite mem_index_enum. elim: index_enum => //= j r IHr /[!inE]; case: eqVneq => [<-|nij]//=. move=> _ /andP[iNr runiq]; rewrite big_cons/= Pi big1_seq ?Monoid.mulm1//. by move=> {}j /andP[/Fisx + jr] => ->//; apply: contraNneq iNr => <-. move=> ir /andP[jNr runiq]; rewrite big_cons IHr//. by case: ifPn => // /Fisx->; rewrite 1?eq_sym// Monoid.mul1m. Qed. Lemma big_pred1_eq (I : finType) (i : I) F : \big[*%M/1]_(j | j == i) F j = F i. Proof. by rewrite (@big_only1 _ i)// => j /negPf->. Qed. Lemma big_pred1 (I : finType) i (P : pred I) F : P =1 pred1 i -> \big[*%M/1]_(j | P j) F j = F i. Proof. by move/(eq_bigl _ _)->; apply: big_pred1_eq. Qed. Lemma big_ord1 F : \big[op/idx]_(i < 1) F i = F ord0. Proof. by rewrite big_ord_recl big_ord0 Monoid.mulm1. Qed. Lemma big_ord1_cond P F : \big[op/idx]_(i < 1 | P i) F i = if P ord0 then F ord0 else idx. Proof. by rewrite big_mkcond big_ord1. Qed. Lemma big_ord1_eq (F : nat -> R) i n : \big[op/idx]_(j < n | j == i :> nat) F j = if i < n then F i else idx. Proof. case: ltnP => [i_lt|i_ge]; first by rewrite (big_pred1_eq (Ordinal _)). by rewrite big_pred0// => j; apply: contra_leqF i_ge => /eqP <-. Qed. Lemma big_ord1_cond_eq (F : nat -> R) (P : pred nat) i n : \big[op/idx]_(j < n | P j && (j == i :> nat)) F j = if (i < n) && P i then F i else idx. Proof. by rewrite big_mkcondl if_and (big_ord1_eq (fun j => if P j then F j else _)). Qed. Lemma big_cat_nat n m p (P : pred nat) F : m <= n -> n <= p -> \big[*%M/1]_(m <= i < p | P i) F i = (\big[*%M/1]_(m <= i < n | P i) F i) * (\big[*%M/1]_(n <= i < p | P i) F i). Proof. move=> le_mn le_np; rewrite -big_cat -{2}(subnKC le_mn) -iotaD subnDA. by rewrite subnKC // leq_sub. Qed. Lemma big_nat_widenl (m1 m2 n : nat) (P : pred nat) F : m2 <= m1 -> \big[op/idx]_(m1 <= i < n | P i) F i = \big[op/idx]_(m2 <= i < n | P i && (m1 <= i)) F i. Proof. move=> le_m21; have [le_nm1|lt_m1n] := leqP n m1. rewrite big_geq// big_nat_cond big1//. by move=> i /and3P[/andP[_ /leq_trans/(_ le_nm1)/ltn_geF->]]. rewrite big_mkcond big_mkcondl (big_cat_nat _ _ le_m21) 1?ltnW//. rewrite [X in op X]big_nat_cond [X in op X]big_pred0; last first. by move=> k; case: ltnP; rewrite andbF. by rewrite Monoid.mul1m; apply: congr_big_nat => // k /andP[]. Qed. Lemma big_geq_mkord (m n : nat) (P : pred nat) F : \big[op/idx]_(m <= i < n | P i) F i = \big[op/idx]_(i < n | P i && (m <= i)) F i. Proof. by rewrite (@big_nat_widenl _ 0)// big_mkord. Qed. Lemma big_nat1_eq (F : nat -> R) i m n : \big[op/idx]_(m <= j < n | j == i) F j = if m <= i < n then F i else idx. Proof. by rewrite big_geq_mkord big_andbC big_ord1_cond_eq andbC. Qed. Lemma big_nat1_cond_eq (F : nat -> R) (P : pred nat) i m n : \big[op/idx]_(m <= j < n | P j && (j == i)) F j = if (m <= i < n) && P i then F i else idx. Proof. by rewrite big_mkcondl big_nat1_eq -if_and. Qed. Lemma big_nat1 n F : \big[*%M/1]_(n <= i < n.+1) F i = F n. Proof. by rewrite big_ltn // big_geq // mulm1. Qed. Lemma big_nat_recr n m F : m <= n -> \big[*%M/1]_(m <= i < n.+1) F i = (\big[*%M/1]_(m <= i < n) F i) * F n. Proof. by move=> lemn; rewrite (@big_cat_nat n) ?leqnSn // big_nat1. Qed. Lemma big_nat_mul n k F : \big[*%M/1]_(0 <= i < n * k) F i = \big[*%M/1]_(0 <= i < n) \big[*%M/1]_(i * k <= j < i.+1 * k) F j. Proof. elim: n => [|n ih]; first by rewrite mul0n 2!big_nil. rewrite [in RHS]big_nat_recr//= -ih mulSn addnC [in LHS]/index_iota subn0 iotaD. rewrite big_cat /= [in X in _ = X * _]/index_iota subn0; congr (_ * _). by rewrite add0n /index_iota (addnC _ k) addnK. Qed. Lemma big_ord_recr n F : \big[*%M/1]_(i < n.+1) F i = (\big[*%M/1]_(i < n) F (widen_ord (leqnSn n) i)) * F ord_max. Proof. transitivity (\big[*%M/1]_(0 <= i < n.+1) F (inord i)). by rewrite big_mkord; apply: eq_bigr=> i _; rewrite inord_val. rewrite big_nat_recr // big_mkord; congr (_ * F _); last first. by apply: val_inj; rewrite /= inordK. by apply: eq_bigr => [] i _; congr F; apply: ord_inj; rewrite inordK //= leqW. Qed. Lemma big_sumType (I1 I2 : finType) (P : pred (I1 + I2)) F : \big[*%M/1]_(i | P i) F i = (\big[*%M/1]_(i | P (inl _ i)) F (inl _ i)) * (\big[*%M/1]_(i | P (inr _ i)) F (inr _ i)). Proof. by rewrite ![index_enum _]unlock [@Finite.enum in LHS]unlock/= big_cat !big_map. Qed. Lemma big_split_ord m n (P : pred 'I_(m + n)) F : \big[*%M/1]_(i | P i) F i = (\big[*%M/1]_(i | P (lshift n i)) F (lshift n i)) * (\big[*%M/1]_(i | P (rshift m i)) F (rshift m i)). Proof. rewrite -(big_map _ _ (lshift n) _ P F) -(big_map _ _ (@rshift m _) _ P F). rewrite -big_cat; congr bigop; apply: (inj_map val_inj). rewrite map_cat -!map_comp (map_comp (addn m)) /=. by rewrite ![index_enum _]unlock unlock !val_ord_enum -iotaDl addn0 iotaD. Qed. Lemma big_flatten I rr (P : pred I) F : \big[*%M/1]_(i <- flatten rr | P i) F i = \big[*%M/1]_(r <- rr) \big[*%M/1]_(i <- r | P i) F i. Proof. by elim: rr => [|r rr IHrr]; rewrite ?big_nil //= big_cat big_cons -IHrr. Qed. Lemma big_pmap J I (h : J -> option I) (r : seq J) F : \big[op/idx]_(i <- pmap h r) F i = \big[op/idx]_(j <- r) oapp F idx (h j). Proof. elim: r => [| r0 r IHr]/=; first by rewrite !big_nil. rewrite /= big_cons; case: (h r0) => [i|] /=; last by rewrite mul1m. by rewrite big_cons IHr. Qed. Lemma telescope_big (f : nat -> nat -> R) (n m : nat) : (forall k, n < k < m -> op (f n k) (f k k.+1) = f n k.+1) -> \big[op/idx]_(n <= i < m) f i i.+1 = if n < m then f n m else idx. Proof. elim: m => [//| m IHm]; first by rewrite ltn0 big_geq. move=> tm; rewrite ltnS; case: ltnP=> // mn; first by rewrite big_geq. rewrite big_nat_recr// IHm//; last first. by move=> k /andP[nk /ltnW nm]; rewrite tm// nk. by case: ltngtP mn=> //= [nm|<-]; rewrite ?mul1m// tm// nm leqnn. Qed. End Plain. Section Abelian. Variable op : Monoid.com_law 1. Local Notation "'*%M'" := op. Local Notation "x * y" := (op x y). Lemma big_rem (I : eqType) r x (P : pred I) F : x \in r -> \big[*%M/1]_(y <- r | P y) F y = (if P x then F x else 1) * \big[*%M/1]_(y <- rem x r | P y) F y. Proof. by move/perm_to_rem/(perm_big _)->; rewrite !(big_mkcond _ _ P) big_cons. Qed. Lemma big_rev I (r : seq I) P F : \big[*%M/1]_(i <- rev r | P i) F i = \big[*%M/1]_(i <- r | P i) F i. Proof. by rewrite rev_big_rev; apply: (eq_big_op (fun=> True)) => // *; apply: mulmC. Qed. Lemma eq_big_idem (I : eqType) (r1 r2 : seq I) (P : pred I) F : idempotent_op *%M -> r1 =i r2 -> \big[*%M/1]_(i <- r1 | P i) F i = \big[*%M/1]_(i <- r2 | P i) F i. Proof. move=> idM eq_r; rewrite -big_undup // -(big_undup r2) //; apply/perm_big. by rewrite uniq_perm ?undup_uniq // => i; rewrite !mem_undup eq_r. Qed. Lemma big_undup_iterop_count (I : eqType) (r : seq I) (P : pred I) F : \big[*%M/1]_(i <- undup r | P i) iterop (count_mem i r) *%M (F i) 1 = \big[*%M/1]_(i <- r | P i) F i. Proof. rewrite -[RHS](perm_big _ F (perm_count_undup _)) big_flatten big_map. by rewrite [LHS]big_mkcond; apply: eq_bigr=> i _; rewrite big_nseq_cond iteropE. Qed. Lemma big_split I r (P : pred I) F1 F2 : \big[*%M/1]_(i <- r | P i) (F1 i * F2 i) = \big[*%M/1]_(i <- r | P i) F1 i * \big[*%M/1]_(i <- r | P i) F2 i. Proof. exact/big_split_idem/mul1m. Qed. Lemma bigID I r (a P : pred I) F : \big[*%M/1]_(i <- r | P i) F i = \big[*%M/1]_(i <- r | P i && a i) F i * \big[*%M/1]_(i <- r | P i && ~~ a i) F i. Proof. exact/bigID_idem/mul1m. Qed. Arguments bigID [I r]. Lemma big_if I r (P Q : pred I) F G : \big[*%M/1]_(i <- r | P i) (if Q i then F i else G i) = \big[*%M/1]_(i <- r | P i && Q i) F i * \big[*%M/1]_(i <- r | P i && ~~ Q i) G i. Proof. rewrite (bigID Q); congr (_ * _); apply: eq_bigr => i /andP[_]. by move=> ->. by move=> /negPf ->. Qed. Lemma bigU (I : finType) (A B : pred I) F : [disjoint A & B] -> \big[*%M/1]_(i in [predU A & B]) F i = (\big[*%M/1]_(i in A) F i) * (\big[*%M/1]_(i in B) F i). Proof. exact/bigU_idem/mul1m. Qed. Lemma partition_big I (s : seq I) (J : finType) (P : pred I) (p : I -> J) (Q : pred J) F : (forall i, P i -> Q (p i)) -> \big[*%M/1]_(i <- s | P i) F i = \big[*%M/1]_(j : J | Q j) \big[*%M/1]_(i <- s | (P i) && (p i == j)) F i. Proof. move=> Qp; transitivity (\big[*%M/1]_(i <- s | P i && Q (p i)) F i). by apply: eq_bigl => i; case Pi: (P i); rewrite // Qp. have [n leQn] := ubnP #|Q|; elim: n => // n IHn in Q {Qp} leQn *. case: (pickP Q) => [j Qj | Q0]; last first. by rewrite !big_pred0 // => i; rewrite Q0 andbF. rewrite (bigD1 j) // -IHn; last by rewrite ltnS (cardD1x Qj) in leQn. rewrite (bigID (fun i => p i == j)); congr (_ * _); apply: eq_bigl => i. by case: eqP => [-> | _]; rewrite !(Qj, simpm). by rewrite andbA. Qed. Arguments partition_big [I s J P] p Q [F]. Lemma big_enum_val (I : finType) (A : pred I) F : \big[op/idx]_(x in A) F x = \big[op/idx]_(i < #|A|) F (enum_val i). Proof. by rewrite -(big_enum_val_cond predT) big_mkcondr. Qed. Arguments big_enum_val [I A] F. Lemma big_enum_rank (I : finType) (A : pred I) x (xA : x \in A) F (h := enum_rank_in xA) : \big[op/idx]_(i < #|A|) F i = \big[op/idx]_(s in A) F (h s). Proof. by rewrite (big_enum_rank_cond xA) big_mkcondr. Qed. Arguments big_enum_rank [I A x] xA F. Lemma big_sub_cond (I : finType) (A P : {pred I}) (F : I -> R) : \big[*%M/1]_(i in A | P i) F i = \big[*%M/1]_(x : {x in A} | P (val x)) F (val x). Proof. rewrite (reindex_omap (val : {x in A} -> I) insub); last first. by move=> i /andP[iA Pi]; rewrite insubT. by apply: eq_bigl=> -[i iA]/=; rewrite insubT ?iA /= eqxx andbT. Qed. Lemma big_sub (I : finType) (A : {pred I}) (F : I -> R) : \big[*%M/1]_(i in A) F i = \big[*%M/1]_(x : {x in A}) F (val x). Proof. by rewrite -(big_sub_cond A xpredT) big_mkcondr. Qed. Lemma sig_big_dep (I : finType) (J : I -> finType) (P : pred I) (Q : forall {i}, pred (J i)) (F : forall {i}, J i -> R) : \big[op/idx]_(i | P i) \big[op/idx]_(j : J i | Q j) F j = \big[op/idx]_(p : {i : I & J i} | P (tag p) && Q (tagged p)) F (tagged p). Proof. exact/sig_big_dep_idem/mul1m. Qed. Lemma pair_big_dep (I J : finType) (P : pred I) (Q : I -> pred J) F : \big[*%M/1]_(i | P i) \big[*%M/1]_(j | Q i j) F i j = \big[*%M/1]_(p | P p.1 && Q p.1 p.2) F p.1 p.2. Proof. exact/pair_big_dep_idem/mul1m. Qed. Lemma pair_big (I J : finType) (P : pred I) (Q : pred J) F : \big[*%M/1]_(i | P i) \big[*%M/1]_(j | Q j) F i j = \big[*%M/1]_(p | P p.1 && Q p.2) F p.1 p.2. Proof. exact/pair_big_idem/mul1m. Qed. Lemma pair_bigA (I J : finType) (F : I -> J -> R) : \big[*%M/1]_i \big[*%M/1]_j F i j = \big[*%M/1]_p F p.1 p.2. Proof. exact/pair_bigA_idem/mul1m. Qed. Lemma exchange_big_dep I J rI rJ (P : pred I) (Q : I -> pred J) (xQ : pred J) F : (forall i j, P i -> Q i j -> xQ j) -> \big[*%M/1]_(i <- rI | P i) \big[*%M/1]_(j <- rJ | Q i j) F i j = \big[*%M/1]_(j <- rJ | xQ j) \big[*%M/1]_(i <- rI | P i && Q i j) F i j. Proof. exact/exchange_big_dep_idem/mul1m. Qed. Arguments exchange_big_dep [I J rI rJ P Q] xQ [F]. Lemma exchange_big I J rI rJ (P : pred I) (Q : pred J) F : \big[*%M/1]_(i <- rI | P i) \big[*%M/1]_(j <- rJ | Q j) F i j = \big[*%M/1]_(j <- rJ | Q j) \big[*%M/1]_(i <- rI | P i) F i j. Proof. exact/exchange_big_idem/mul1m. Qed. Lemma exchange_big_dep_nat m1 n1 m2 n2 (P : pred nat) (Q : rel nat) (xQ : pred nat) F : (forall i j, m1 <= i < n1 -> m2 <= j < n2 -> P i -> Q i j -> xQ j) -> \big[*%M/1]_(m1 <= i < n1 | P i) \big[*%M/1]_(m2 <= j < n2 | Q i j) F i j = \big[*%M/1]_(m2 <= j < n2 | xQ j) \big[*%M/1]_(m1 <= i < n1 | P i && Q i j) F i j. Proof. exact/exchange_big_dep_nat_idem/mul1m. Qed. Arguments exchange_big_dep_nat [m1 n1 m2 n2 P Q] xQ [F]. Lemma exchange_big_nat m1 n1 m2 n2 (P Q : pred nat) F : \big[*%M/1]_(m1 <= i < n1 | P i) \big[*%M/1]_(m2 <= j < n2 | Q j) F i j = \big[*%M/1]_(m2 <= j < n2 | Q j) \big[*%M/1]_(m1 <= i < n1 | P i) F i j. Proof. exact/exchange_big_nat_idem/mul1m. Qed. End Abelian. End MonoidProperties. Arguments big_filter [R idx op I]. Arguments big_filter_cond [R idx op I]. Arguments congr_big [R idx op I r1] r2 [P1] P2 [F1] F2. Arguments eq_big [R idx op I r P1] P2 [F1] F2. Arguments eq_bigl [R idx op I r P1] P2. Arguments eq_bigr [R idx op I r P F1] F2. Arguments eq_big_idx [R idx op idx' I] i0 [P F]. Arguments big_seq_cond [R idx op I r]. Arguments eq_big_seq [R idx op I r F1] F2. Arguments congr_big_nat [R idx op m1 n1] m2 n2 [P1] P2 [F1] F2. Arguments big_map [R idx op I J] h [r]. Arguments big_nth [R idx op I] x0 [r]. Arguments big_catl [R idx op I r1 r2 P F]. Arguments big_catr [R idx op I r1 r2 P F]. Arguments big_geq [R idx op m n P F]. Arguments big_ltn_cond [R idx op m n P F]. Arguments big_ltn [R idx op m n F]. Arguments big_addn [R idx op]. Arguments big_mkord [R idx op n]. Arguments big_nat_widen [R idx op]. Arguments big_nat_widenl [R idx op]. Arguments big_geq_mkord [R idx op]. Arguments big_ord_widen_cond [R idx op n1]. Arguments big_ord_widen [R idx op n1]. Arguments big_ord_widen_leq [R idx op n1]. Arguments big_ord_narrow_cond [R idx op n1 n2 P F]. Arguments big_ord_narrow_cond_leq [R idx op n1 n2 P F]. Arguments big_ord_narrow [R idx op n1 n2 F]. Arguments big_ord_narrow_leq [R idx op n1 n2 F]. Arguments big_mkcond [R idx op I r]. Arguments big1_eq [R idx op I]. Arguments big1_seq [R idx op I]. Arguments big1 [R idx op I]. Arguments big_only1 {R idx op I} i [P F]. Arguments big_pred1 [R idx op I] i [P F]. Arguments perm_big [R op x I r1] r2 [P F]. Arguments big_uniq [R op x I] r [F]. Arguments big_rem [R idx op I r] x [P F]. Arguments bigID [R idx op I r]. Arguments bigU [R idx op I]. Arguments bigD1 [R op x I] j [P F]. Arguments bigD1_seq [R op x I r] j [F]. Arguments bigD1_ord [R op x n] j [P F]. Arguments partition_big [R idx op I s J P] p Q [F]. Arguments reindex_omap [R op x I J] h h' [P F]. Arguments reindex_onto [R op x I J] h h' [P F]. Arguments reindex [R op x I J] h [P F]. Arguments reindex_inj [R op x I h P F]. Arguments big_enum_val_cond [R op x I A] P F. Arguments big_enum_rank_cond [R op x I A z] zA P F. Arguments big_enum_val [R idx op I A] F. Arguments big_enum_rank [R idx op I A x] xA F. Arguments big_sub_cond [R idx op I]. Arguments big_sub [R idx op I]. Arguments sig_big_dep [R idx op I J]. Arguments pair_big_dep [R idx op I J]. Arguments pair_big [R idx op I J]. Arguments big_allpairs_dep {R idx op I1 I2 J h r1 r2 F}. Arguments big_allpairs {R idx op I1 I2 r1 r2 F}. Arguments exchange_big_dep [R idx op I J rI rJ P Q] xQ [F]. Arguments exchange_big_dep_nat [R idx op m1 n1 m2 n2 P Q] xQ [F]. Arguments big_ord_recl [R idx op]. Arguments big_ord_recr [R idx op]. Arguments big_nat_recl [R idx op]. Arguments big_nat_recr [R idx op]. Arguments big_cat_nat_idem [R op x] opxx [n m p P F]. Arguments big_cat_nat [R idx op n m p P F]. Arguments big_pmap [R idx op J I] h [r]. Arguments telescope_big [R idx op] f [n m]. Section IncreasingSemiGroup. Variables (R : Type) (op : SemiGroup.com_law R). Variable le : rel R. Hypothesis le_refl : reflexive le. Hypothesis op_incr : forall x y, le x (op x y). Context [x : R]. Local Notation opA := SemiGroup.opA. Local Notation opC := SemiGroup.opC. Lemma sub_le_big I [s] (P P' : {pred I}) (F : I -> R) : (forall i, P i -> P' i) -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s | P' i) F i). Proof. move=> PP'; rewrite [X in le _ X](big_AC_mk_monoid opA opC) (bigID P P') /=. under [in X in le _ X]eq_bigl do rewrite (andb_idl (PP' _)). rewrite [X in le X _](big_AC_mk_monoid opA opC). case: (bigop _ _ _) (bigop _ _ _) => [y|] [z|]//=. by rewrite -opA [_ y x]opC opA op_incr. by rewrite opC op_incr. Qed. Lemma sub_le_big_seq (I : eqType) s s' P (F : I -> R) : (forall i, count_mem i s <= count_mem i s')%N -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P i) F i). Proof. rewrite (big_AC_mk_monoid opA opC) => /count_subseqP[_ /subseqP[m sm ->]]. move/(perm_big _)->; rewrite big_mask [X in le _ X]big_tnth. by rewrite -!(big_AC_mk_monoid opA opC) sub_le_big // => j /andP[]. Qed. Lemma sub_le_big_seq_cond (I : eqType) s s' P P' (F : I -> R) : (forall i, count_mem i (filter P s) <= count_mem i (filter P' s'))%N -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P' i) F i). Proof. by move=> /(sub_le_big_seq xpredT F); rewrite !big_filter. Qed. Lemma uniq_sub_le_big (I : eqType) s s' P (F : I -> R) : uniq s -> uniq s' -> {subset s <= s'} -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P i) F i). Proof. move=> us us' ss'; rewrite sub_le_big_seq => // i; rewrite !count_uniq_mem//. by have /implyP := ss' i; case: (_ \in s) (_ \in s') => [] []. Qed. Lemma uniq_sub_le_big_cond (I : eqType) s s' P P' (F : I -> R) : uniq (filter P s) -> uniq (filter P' s') -> {subset [seq i <- s | P i] <= [seq i <- s' | P' i]} -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P' i) F i). Proof. by move=> u v /(uniq_sub_le_big xpredT F u v); rewrite !big_filter. Qed. Section Id. Hypothesis opK : idempotent_op op. Lemma idem_sub_le_big (I : eqType) s s' P (F : I -> R) : {subset s <= s'} -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P i) F i). Proof. move=> ss'; rewrite -big_undup// -[X in le _ X]big_undup//. by rewrite uniq_sub_le_big ?undup_uniq// => i; rewrite !mem_undup; apply: ss'. Qed. Lemma idem_sub_le_big_cond (I : eqType) s s' P P' (F : I -> R) : {subset [seq i <- s | P i] <= [seq i <- s' | P' i]} -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s' | P' i) F i). Proof. by move=> /(idem_sub_le_big xpredT F); rewrite !big_filter. Qed. End Id. Lemma sub_in_le_big [I : eqType] (s : seq I) (P P' : {pred I}) (F : I -> R) : {in s, forall i, P i -> P' i} -> le (\big[op/x]_(i <- s | P i) F i) (\big[op/x]_(i <- s | P' i) F i). Proof. move=> PP'; apply: sub_le_big_seq_cond => i; rewrite leq_count_subseq//. rewrite subseq_filter filter_subseq andbT; apply/allP => j. by rewrite !mem_filter => /andP[/PP'/[apply]->]. Qed. Lemma le_big_ord n m [P : {pred nat}] [F : nat -> R] : (n <= m)%N -> le (\big[op/x]_(i < n | P i) F i) (\big[op/x]_(i < m | P i) F i). Proof. by move=> nm; rewrite (big_ord_widen_cond m)// sub_le_big => //= ? /andP[]. Qed. Lemma subset_le_big [I : finType] [A A' P : {pred I}] (F : I -> R) : A \subset A' -> le (\big[op/x]_(i in A | P i) F i) (\big[op/x]_(i in A' | P i) F i). Proof. move=> AA'; apply: sub_le_big => y /andP[yA yP]; apply/andP; split => //. exact: subsetP yA. Qed. Lemma le_big_nat_cond n m n' m' (P P' : {pred nat}) (F : nat -> R) : (n' <= n)%N -> (m <= m')%N -> (forall i, (n <= i < m)%N -> P i -> P' i) -> le (\big[op/x]_(n <= i < m | P i) F i) (\big[op/x]_(n' <= i < m' | P' i) F i). Proof. move=> len'n lemm' PP'i; rewrite uniq_sub_le_big_cond ?filter_uniq ?iota_uniq//. move=> i; rewrite !mem_filter !mem_index_iota => /and3P[Pi ni im]. by rewrite PP'i ?ni//= (leq_trans _ ni)// (leq_trans im). Qed. Lemma le_big_nat n m n' m' [P] [F : nat -> R] : (n' <= n)%N -> (m <= m')%N -> le (\big[op/x]_(n <= i < m | P i) F i) (\big[op/x]_(n' <= i < m' | P i) F i). Proof. by move=> len'n lemm'; rewrite le_big_nat_cond. Qed. Lemma le_big_ord_cond n m (P P' : {pred nat}) (F : nat -> R) : (n <= m)%N -> (forall i : 'I_n, P i -> P' i) -> le (\big[op/x]_(i < n | P i) F i) (\big[op/x]_(i < m | P' i) F i). Proof. move=> nm PP'; rewrite -!big_mkord le_big_nat_cond//= => i ni. by have := PP' (Ordinal ni). Qed. End IncreasingSemiGroup. Section EqSupport. Variables (R : eqType) (idx : R). Section MonoidSupport. Variables (op : Monoid.law idx) (I : Type). Lemma eq_bigl_supp (r : seq I) (P1 : pred I) (P2 : pred I) (F : I -> R) : {in [pred x | F x != idx], P1 =1 P2} -> \big[op/idx]_(i <- r | P1 i) F i = \big[op/idx]_(i <- r | P2 i) F i. Proof. move=> P12; rewrite big_mkcond [RHS]big_mkcond; apply: eq_bigr => i _. by case: (eqVneq (F i) idx) => [->|/P12->]; rewrite ?if_same. Qed. End MonoidSupport. Section ComoidSupport. Variables (op : Monoid.com_law idx) (I : eqType). Lemma perm_big_supp_cond [r s : seq I] [P : pred I] (F : I -> R) : perm_eq [seq i <- r | P i && (F i != idx)] [seq i <- s | P i && (F i != idx)] -> \big[op/idx]_(i <- r | P i) F i = \big[op/idx]_(i <- s | P i) F i. Proof. move=> prs; rewrite !(bigID [pred i | F i == idx] P F)/=. rewrite big1 ?Monoid.mul1m; last by move=> i /andP[_ /eqP->]. rewrite [in RHS]big1 ?Monoid.mul1m; last by move=> i /andP[_ /eqP->]. by rewrite -[in LHS]big_filter -[in RHS]big_filter; apply perm_big. Qed. Lemma perm_big_supp [r s : seq I] [P : pred I] (F : I -> R) : perm_eq [seq i <- r | F i != idx] [seq i <- s | F i != idx] -> \big[op/idx]_(i <- r | P i) F i = \big[op/idx]_(i <- s | P i) F i. Proof. by move=> ?; apply: perm_big_supp_cond; rewrite !filter_predI perm_filter. Qed. End ComoidSupport. End EqSupport. Arguments eq_bigl_supp [R idx op I r P1]. Arguments perm_big_supp_cond [R idx op I r s P]. Arguments perm_big_supp [R idx op I r s P]. Section Distributivity. Import Monoid.Theory. Variable R : Type. Variables zero one : R. Local Notation "0" := zero. Local Notation "1" := one. Variable times : Monoid.mul_law 0. Local Notation "*%M" := times. Local Notation "x * y" := (times x y). Variable plus : Monoid.add_law 0 *%M. Local Notation "+%M" := plus. Local Notation "x + y" := (plus x y). Lemma big_distrl I r a (P : pred I) F : \big[+%M/0]_(i <- r | P i) F i * a = \big[+%M/0]_(i <- r | P i) (F i * a). Proof. by rewrite (big_endo ( *%M^~ a)) ?mul0m // => x y; apply: mulmDl. Qed. Lemma big_distrr I r a (P : pred I) F : a * \big[+%M/0]_(i <- r | P i) F i = \big[+%M/0]_(i <- r | P i) (a * F i). Proof. by rewrite big_endo ?mulm0 // => x y; apply: mulmDr. Qed. Lemma big_distrlr I J rI rJ (pI : pred I) (pJ : pred J) F G : (\big[+%M/0]_(i <- rI | pI i) F i) * (\big[+%M/0]_(j <- rJ | pJ j) G j) = \big[+%M/0]_(i <- rI | pI i) \big[+%M/0]_(j <- rJ | pJ j) (F i * G j). Proof. by rewrite big_distrl; under eq_bigr do rewrite big_distrr. Qed. Lemma big_distr_big_dep (I J : finType) j0 (P : pred I) (Q : I -> pred J) F : \big[*%M/1]_(i | P i) \big[+%M/0]_(j | Q i j) F i j = \big[+%M/0]_(f in pfamily j0 P Q) \big[*%M/1]_(i | P i) F i (f i). Proof. pose fIJ := {ffun I -> J}; pose Pf := pfamily j0 (_ : seq I) Q. have [r big_r [Ur mem_r] _] := big_enumP P. symmetry; transitivity (\big[+%M/0]_(f in Pf r) \big[*%M/1]_(i <- r) F i (f i)). by apply: eq_big => // f; apply: eq_forallb => i; rewrite /= mem_r. rewrite -{P mem_r}big_r; elim: r Ur => /= [_ | i r IHr]. rewrite (big_pred1 [ffun=> j0]) ?big_nil //= => f. apply/familyP/eqP=> /= [Df |->{f} i]; last by rewrite ffunE !inE. by apply/ffunP=> i; rewrite ffunE; apply/eqP/Df. case/andP=> /negbTE nri; rewrite big_cons big_distrl => {}/IHr<-. rewrite (partition_big (fun f : fIJ => f i) (Q i)) => [|f]; last first. by move/familyP/(_ i); rewrite /= inE /= eqxx. pose seti j (f : fIJ) := [ffun k => if k == i then j else f k]. apply: eq_bigr => j Qij. rewrite (reindex_onto (seti j) (seti j0)) => [|f /andP[_ /eqP fi]]; last first. by apply/ffunP=> k; rewrite !ffunE; case: eqP => // ->. rewrite big_distrr; apply: eq_big => [f | f eq_f]; last first. rewrite big_cons ffunE eqxx !big_seq; congr (_ * _). by apply: eq_bigr => k; rewrite ffunE; case: eqP nri => // -> ->. rewrite !ffunE !eqxx andbT; apply/andP/familyP=> /= [[Pjf fij0] k | Pff]. have /[!(ffunE, inE)] := familyP Pjf k; case: eqP => // -> _. by rewrite nri -(eqP fij0) !ffunE !inE !eqxx. (split; [apply/familyP | apply/eqP/ffunP]) => k; have /[!(ffunE, inE)]:= Pff k. by case: eqP => // ->. by case: eqP => // ->; rewrite nri /= => /eqP. Qed. Lemma big_distr_big (I J : finType) j0 (P : pred I) (Q : pred J) F : \big[*%M/1]_(i | P i) \big[+%M/0]_(j | Q j) F i j = \big[+%M/0]_(f in pffun_on j0 P Q) \big[*%M/1]_(i | P i) F i (f i). Proof. rewrite (big_distr_big_dep j0); apply: eq_bigl => f. by apply/familyP/familyP=> Pf i; case: ifP (Pf i). Qed. Lemma bigA_distr_big_dep (I J : finType) (Q : I -> pred J) F : \big[*%M/1]_i \big[+%M/0]_(j | Q i j) F i j = \big[+%M/0]_(f in family Q) \big[*%M/1]_i F i (f i). Proof. have [j _ | J0] := pickP J; first by rewrite (big_distr_big_dep j). have Q0 i: Q i =i pred0 by move=> /J0/esym/notF[]. transitivity (iter #|I| ( *%M 0) 1). by rewrite -big_const; apply/eq_bigr=> i; have /(big_pred0 _)-> := Q0 i. have [i _ | I0] := pickP I. rewrite (cardD1 i) //= mul0m big_pred0 // => f. by apply/familyP=> /(_ i); rewrite Q0. have f: I -> J by move=> /I0/esym/notF[]. rewrite eq_card0 // (big_pred1 (finfun f)) ?big_pred0 // => g. by apply/familyP/eqP=> _; first apply/ffunP; move=> /I0/esym/notF[]. Qed. Lemma bigA_distr_big (I J : finType) (Q : pred J) (F : I -> J -> R) : \big[*%M/1]_i \big[+%M/0]_(j | Q j) F i j = \big[+%M/0]_(f in ffun_on Q) \big[*%M/1]_i F i (f i). Proof. exact: bigA_distr_big_dep. Qed. Lemma bigA_distr_bigA (I J : finType) F : \big[*%M/1]_(i : I) \big[+%M/0]_(j : J) F i j = \big[+%M/0]_(f : {ffun I -> J}) \big[*%M/1]_i F i (f i). Proof. by rewrite bigA_distr_big; apply: eq_bigl => ?; apply/familyP. Qed. End Distributivity. Arguments big_distrl [R zero times plus I r]. Arguments big_distrr [R zero times plus I r]. Arguments big_distr_big_dep [R zero one times plus I J]. Arguments big_distr_big [R zero one times plus I J]. Arguments bigA_distr_big_dep [R zero one times plus I J]. Arguments bigA_distr_big [R zero one times plus I J]. Arguments bigA_distr_bigA [R zero one times plus I J]. Section BigBool. Section Seq. Variables (I : Type) (r : seq I) (P B : pred I). Lemma big_has : \big[orb/false]_(i <- r) B i = has B r. Proof. by rewrite unlock. Qed. Lemma big_all : \big[andb/true]_(i <- r) B i = all B r. Proof. by rewrite unlock. Qed. Lemma big_has_cond : \big[orb/false]_(i <- r | P i) B i = has (predI P B) r. Proof. by rewrite big_mkcond unlock. Qed. Lemma big_all_cond : \big[andb/true]_(i <- r | P i) B i = all [pred i | P i ==> B i] r. Proof. by rewrite big_mkcond unlock. Qed. Lemma big_bool R (idx : R) (op : Monoid.com_law idx) (F : bool -> R): \big[op/idx]_(i : bool) F i = op (F true) (F false). Proof. by rewrite /index_enum !unlock /= Monoid.mulm1. Qed. End Seq. Section FinType. Variables (I : finType) (P B : pred I). Lemma big_orE : \big[orb/false]_(i | P i) B i = [exists (i | P i), B i]. Proof. by rewrite big_has_cond; apply/hasP/existsP=> [] [i]; exists i. Qed. Lemma big_andE : \big[andb/true]_(i | P i) B i = [forall (i | P i), B i]. Proof. rewrite big_all_cond; apply/allP/forallP=> /= allB i; rewrite allB //. exact: mem_index_enum. Qed. End FinType. End BigBool. Section NatConst. Variables (I : finType) (A : pred I). Lemma sum_nat_const n : \sum_(i in A) n = #|A| * n. Proof. by rewrite big_const iter_addn_0 mulnC. Qed. Lemma sum1_card : \sum_(i in A) 1 = #|A|. Proof. by rewrite sum_nat_const muln1. Qed. Lemma sum1_count J (r : seq J) (a : pred J) : \sum_(j <- r | a j) 1 = count a r. Proof. by rewrite big_const_seq iter_addn_0 mul1n. Qed. Lemma sum1_size J (r : seq J) : \sum_(j <- r) 1 = size r. Proof. by rewrite sum1_count count_predT. Qed. Lemma prod_nat_const n : \prod_(i in A) n = n ^ #|A|. Proof. by rewrite big_const -Monoid.iteropE. Qed. Lemma sum_nat_const_nat n1 n2 n : \sum_(n1 <= i < n2) n = (n2 - n1) * n. Proof. by rewrite big_const_nat iter_addn_0 mulnC. Qed. Lemma prod_nat_const_nat n1 n2 n : \prod_(n1 <= i < n2) n = n ^ (n2 - n1). Proof. by rewrite big_const_nat -Monoid.iteropE. Qed. End NatConst. Lemma telescope_sumn_in n m f : n <= m -> (forall i, n <= i < m -> f i <= f i.+1) -> \sum_(n <= k < m) (f k.+1 - f k) = f m - f n. Proof. move=> nm fle; rewrite (telescope_big (fun i j => f j - f i)). by case: ltngtP nm => // ->; rewrite subnn. move=> k /andP[nk km]; rewrite /= addnBAC ?subnKC ?fle ?(ltnW nk)//. elim: k nk km => [//| k IHk /[!ltnS]/[1!leq_eqVlt]+ km]. move=> /predU1P[/[dup]nk -> | nk]; first by rewrite fle ?nk ?leqnn 1?ltnW. by rewrite (leq_trans (IHk _ _) (fle _ _))// ltnW// ltnW. Qed. Lemma telescope_sumn n m f : {homo f : x y / x <= y} -> \sum_(n <= k < m) (f k.+1 - f k) = f m - f n. Proof. move=> fle; case: (ltnP n m) => nm. by apply: (telescope_sumn_in (ltnW nm)) => ? ?; apply: fle. by apply/esym/eqP; rewrite big_geq// subn_eq0 fle. Qed. Lemma sumnE r : sumn r = \sum_(i <- r) i. Proof. exact: foldrE. Qed. Lemma card_bseq n (T : finType) : #|{bseq n of T}| = \sum_(i < n.+1) #|T| ^ i. Proof. rewrite (bij_eq_card bseq_tagged_tuple_bij) card_tagged sumnE big_map big_enum. by under eq_bigr do rewrite card_tuple. Qed. Lemma leqif_sum (I : finType) (P C : pred I) (E1 E2 : I -> nat) : (forall i, P i -> E1 i <= E2 i ?= iff C i) -> \sum_(i | P i) E1 i <= \sum_(i | P i) E2 i ?= iff [forall (i | P i), C i]. Proof. move=> leE12; rewrite -big_andE. by elim/big_rec3: _ => // i Ci m1 m2 /leE12; apply: leqif_add. Qed. Lemma leq_sum I r (P : pred I) (E1 E2 : I -> nat) : (forall i, P i -> E1 i <= E2 i) -> \sum_(i <- r | P i) E1 i <= \sum_(i <- r | P i) E2 i. Proof. by move=> leE12; elim/big_ind2: _ => // m1 m2 n1 n2; apply: leq_add. Qed. Lemma sumnB I r (P : pred I) (E1 E2 : I -> nat) : (forall i, P i -> E1 i <= E2 i) -> \sum_(i <- r | P i) (E2 i - E1 i) = \sum_(i <- r | P i) E2 i - \sum_(i <- r | P i) E1 i. Proof. by move=> /(_ _ _)/subnK-/(eq_bigr _)<-; rewrite big_split addnK. Qed. Lemma sum_nat_eq0 (I : finType) (P : pred I) (E : I -> nat) : (\sum_(i | P i) E i == 0)%N = [forall (i | P i), E i == 0%N]. Proof. by rewrite eq_sym -(@leqif_sum I P _ (fun _ => 0%N) E) ?big1_eq. Qed. Lemma sum_nat_seq_eq0 I r (P : pred I) F : (\sum_(i <- r | P i) F i == 0)%N = all (fun i => P i ==> (F i == 0%N)) r. Proof. by rewrite (big_morph _ (id1:=true) addn_eq0)// big_all_cond. Qed. Lemma sum_nat_seq_neq0 I r (P : pred I) F : (\sum_(i <- r | P i) F i != 0)%N = has (fun i => P i && (F i != 0)%N) r. Proof. by rewrite sum_nat_seq_eq0// -has_predC; apply: eq_has => x /=; case Px: (P x). Qed. Lemma sum_nat_eq1 (I : finType) (P : pred I) (F : I -> nat) : reflect (exists i : I, [/\ P i, F i = 1 & forall j, j != i -> P j -> F j = 0]%N) (\sum_(i | P i) F i == 1)%N. Proof. apply/(iffP idP) => [sumF_eq1 | [i [Pi Fi1 zFj]]]; last first. rewrite (bigD1 i)//= Fi1 addn_eq1//= orbF sum_nat_eq0. by apply/forall_inP => j /andP[Pj ji]; apply/eqP/zFj. have /forall_inPn [i Pi FiN0]: ~~ [forall i in P, F i == 0]. by apply: contraTN sumF_eq1 => /'forall_in_eqP F0; rewrite big1. move: sumF_eq1; rewrite (bigD1 i)//= addn_eq1 (negPf FiN0)/= orbF. move=> /andP[/eqP Fi1]; rewrite sum_nat_eq0 => /'forall_in_eqP FNi0. by exists i; split; rewrite // => j /[swap] Nij /(conj Nij)/andP/FNi0. Qed. Lemma sum_nat_seq_eq1 (I : eqType) r (P : pred I) (F : I -> nat) : (\sum_(i <- r | P i) F i = 1)%N -> exists i, [/\ i \in r, P i, F i = 1 & forall j, j != i -> j \in r -> P j -> F j = 0]%N. Proof. rewrite big_tnth/= => /eqP/sum_nat_eq1[/= i [Pi Fi FNi]]. exists (tnth (in_tuple r) i); split; rewrite //= ?mem_tnth// => j. move=> /[swap] /(tnthP (in_tuple r))[{} j -> Nij /FNi->//]. by apply: contra_neq Nij => ->. Qed. Lemma prod_nat_seq_eq0 I r (P : pred I) F : (\prod_(i <- r | P i) F i == 0)%N = has (fun i => P i && (F i == 0%N)) r. Proof. by rewrite (big_morph _ (id1 := false) muln_eq0)// big_has_cond. Qed. Lemma prod_nat_seq_neq0 I r (P : pred I) F : (\prod_(i <- r | P i) F i != 0)%N = all (fun i => P i ==> (F i != 0%N)) r. Proof. by rewrite prod_nat_seq_eq0 -all_predC; apply: eq_all => i /=; case: (P i). Qed. Lemma prod_nat_seq_eq1 I r (P : pred I) F : (\prod_(i <- r | P i) F i == 1)%N = all (fun i => P i ==> (F i == 1%N)) r. Proof. by rewrite (big_morph _ (id1:=true) muln_eq1)// big_all_cond. Qed. Lemma prod_nat_seq_neq1 I r (P : pred I) F : (\prod_(i <- r | P i) F i != 1)%N = has (fun i => P i && (F i != 1%N)) r. Proof. by rewrite prod_nat_seq_eq1 -has_predC; apply: eq_has => i /=; case: (P i). Qed. Lemma leq_prod I r (P : pred I) (E1 E2 : I -> nat) : (forall i, P i -> E1 i <= E2 i) -> \prod_(i <- r | P i) E1 i <= \prod_(i <- r | P i) E2 i. Proof. by move=> leE12; elim/big_ind2: _ => // m1 m2 n1 n2; apply: leq_mul. Qed. Arguments leq_prod [I r P E1 E2]. Lemma prodn_cond_gt0 I r (P : pred I) F : (forall i, P i -> 0 < F i) -> 0 < \prod_(i <- r | P i) F i. Proof. by move=> Fpos; elim/big_ind: _ => // n1 n2; rewrite muln_gt0 => ->. Qed. Arguments prodn_cond_gt0 [I r P F]. Lemma prodn_gt0 I r (P : pred I) F : (forall i, 0 < F i) -> 0 < \prod_(i <- r | P i) F i. Proof. by move=> Fpos; apply: prodn_cond_gt0. Qed. Arguments prodn_gt0 [I r P F]. Lemma gt0_prodn_seq (I : eqType) r (P : pred I) F : 0 < \prod_(i <- r | P i) F i -> forall i, i \in r -> P i -> 0 < F i. Proof. move=> + i ri Pi; rewrite !lt0n; apply: contra_neq => Fi_eq0. by case: (path.splitP ri) => *; rewrite big_cat big_rcons Pi Fi_eq0/= muln0. Qed. Arguments gt0_prodn_seq [I r P F]. Lemma gt0_prodn (I : finType) (P : pred I) F : 0 < \prod_(i | P i) F i -> forall i, P i -> 0 < F i. Proof. by move=> /gt0_prodn_seq + i => /[apply]; apply. Qed. Arguments gt0_prodn [I P F]. Lemma leq_bigmax_seq (I : eqType) r (P : pred I) F i0 : i0 \in r -> P i0 -> F i0 <= \max_(i <- r | P i) F i. Proof. move=> + Pi0; elim: r => // h t ih; rewrite inE big_cons. move=> /predU1P[<-|i0t]; first by rewrite Pi0 leq_maxl. by case: ifPn => Ph; [rewrite leq_max ih// orbT|rewrite ih]. Qed. Arguments leq_bigmax_seq [I r P F]. Lemma leq_bigmax_cond (I : finType) (P : pred I) F i0 : P i0 -> F i0 <= \max_(i | P i) F i. Proof. exact: leq_bigmax_seq. Qed. Arguments leq_bigmax_cond [I P F]. Lemma leq_bigmax (I : finType) F (i0 : I) : F i0 <= \max_i F i. Proof. exact: leq_bigmax_cond. Qed. Arguments leq_bigmax [I F]. Lemma bigmax_leqP (I : finType) (P : pred I) m F : reflect (forall i, P i -> F i <= m) (\max_(i | P i) F i <= m). Proof. apply: (iffP idP) => leFm => [i Pi|]. by apply: leq_trans leFm; apply: leq_bigmax_cond. by elim/big_ind: _ => // m1 m2; rewrite geq_max => ->. Qed. Lemma bigmax_leqP_seq (I : eqType) r (P : pred I) m F : reflect (forall i, i \in r -> P i -> F i <= m) (\max_(i <- r | P i) F i <= m). Proof. apply: (iffP idP) => leFm => [i ri Pi|]. exact/(leq_trans _ leFm)/leq_bigmax_seq. rewrite big_seq_cond; elim/big_ind: _ => // [m1 m2|i /andP[ri]]. by rewrite geq_max => ->. exact: leFm. Qed. Lemma bigmax_sup (I : finType) i0 (P : pred I) m F : P i0 -> m <= F i0 -> m <= \max_(i | P i) F i. Proof. by move=> Pi0 le_m_Fi0; apply: leq_trans (leq_bigmax_cond i0 Pi0). Qed. Arguments bigmax_sup [I] i0 [P m F]. Lemma bigmax_sup_seq (I : eqType) r i0 (P : pred I) m F : i0 \in r -> P i0 -> m <= F i0 -> m <= \max_(i <- r | P i) F i. Proof. by move=> i0r Pi0 ?; apply: leq_trans (leq_bigmax_seq i0 _ _). Qed. Arguments bigmax_sup_seq [I r] i0 [P m F]. Lemma bigmax_eq_arg (I : finType) i0 (P : pred I) F : P i0 -> \max_(i | P i) F i = F [arg max_(i > i0 | P i) F i]. Proof. move=> Pi0; case: arg_maxnP => //= i Pi maxFi. by apply/eqP; rewrite eqn_leq leq_bigmax_cond // andbT; apply/bigmax_leqP. Qed. Arguments bigmax_eq_arg [I] i0 [P F]. Lemma eq_bigmax_cond (I : finType) (A : pred I) F : #|A| > 0 -> {i0 | i0 \in A & \max_(i in A) F i = F i0}. Proof. case: (pickP A) => [i0 Ai0 _ | ]; last by move/eq_card0->. by exists [arg max_(i > i0 in A) F i]; [case: arg_maxnP | apply: bigmax_eq_arg]. Qed. Lemma eq_bigmax (I : finType) F : #|I| > 0 -> {i0 : I | \max_i F i = F i0}. Proof. by case/(eq_bigmax_cond F) => x _ ->; exists x. Qed. Lemma expn_sum m I r (P : pred I) F : (m ^ (\sum_(i <- r | P i) F i) = \prod_(i <- r | P i) m ^ F i)%N. Proof. exact: (big_morph _ (expnD m)). Qed. Lemma dvdn_biglcmP (I : finType) (P : pred I) F m : reflect (forall i, P i -> F i %| m) (\big[lcmn/1%N]_(i | P i) F i %| m). Proof. apply: (iffP idP) => [dvFm i Pi | dvFm]. by rewrite (bigD1 i) // dvdn_lcm in dvFm; case/andP: dvFm. by elim/big_ind: _ => // p q p_m; rewrite dvdn_lcm p_m. Qed. Lemma biglcmn_sup (I : finType) i0 (P : pred I) F m : P i0 -> m %| F i0 -> m %| \big[lcmn/1%N]_(i | P i) F i. Proof. by move=> Pi0 m_Fi0; rewrite (dvdn_trans m_Fi0) // (bigD1 i0) ?dvdn_lcml. Qed. Arguments biglcmn_sup [I] i0 [P F m]. Lemma dvdn_biggcdP (I : finType) (P : pred I) F m : reflect (forall i, P i -> m %| F i) (m %| \big[gcdn/0]_(i | P i) F i). Proof. apply: (iffP idP) => [dvmF i Pi | dvmF]. by rewrite (bigD1 i) // dvdn_gcd in dvmF; case/andP: dvmF. by elim/big_ind: _ => // p q m_p; rewrite dvdn_gcd m_p. Qed. Lemma biggcdn_inf (I : finType) i0 (P : pred I) F m : P i0 -> F i0 %| m -> \big[gcdn/0]_(i | P i) F i %| m. Proof. by move=> Pi0; apply: dvdn_trans; rewrite (bigD1 i0) ?dvdn_gcdl. Qed. Arguments biggcdn_inf [I] i0 [P F m].
Orientation.lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Heather Macbeth -/ import Mathlib.Analysis.InnerProductSpace.GramSchmidtOrtho import Mathlib.LinearAlgebra.Orientation /-! # Orientations of real inner product spaces. This file provides definitions and proves lemmas about orientations of real inner product spaces. ## Main definitions * `OrthonormalBasis.adjustToOrientation` takes an orthonormal basis and an orientation, and returns an orthonormal basis with that orientation: either the original orthonormal basis, or one constructed by negating a single (arbitrary) basis vector. * `Orientation.finOrthonormalBasis` is an orthonormal basis, indexed by `Fin n`, with the given orientation. * `Orientation.volumeForm` is a nonvanishing top-dimensional alternating form on an oriented real inner product space, uniquely defined by compatibility with the orientation and inner product structure. ## Main theorems * `Orientation.volumeForm_apply_le` states that the result of applying the volume form to a set of `n` vectors, where `n` is the dimension the inner product space, is bounded by the product of the lengths of the vectors. * `Orientation.abs_volumeForm_apply_of_pairwise_orthogonal` states that the result of applying the volume form to a set of `n` orthogonal vectors, where `n` is the dimension the inner product space, is equal up to sign to the product of the lengths of the vectors. -/ noncomputable section variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] open Module InnerProductSpace open scoped RealInnerProductSpace namespace OrthonormalBasis variable {ι : Type*} [Fintype ι] [DecidableEq ι] (e f : OrthonormalBasis ι ℝ E) (x : Orientation ℝ E ι) /-- The change-of-basis matrix between two orthonormal bases with the same orientation has determinant 1. -/ theorem det_to_matrix_orthonormalBasis_of_same_orientation (h : e.toBasis.orientation = f.toBasis.orientation) : e.toBasis.det f = 1 := by apply (e.det_to_matrix_orthonormalBasis_real f).resolve_right have : 0 < e.toBasis.det f := by rw [e.toBasis.orientation_eq_iff_det_pos] at h simpa using h linarith /-- The change-of-basis matrix between two orthonormal bases with the opposite orientations has determinant -1. -/ theorem det_to_matrix_orthonormalBasis_of_opposite_orientation (h : e.toBasis.orientation ≠ f.toBasis.orientation) : e.toBasis.det f = -1 := by contrapose! h simp [e.toBasis.orientation_eq_iff_det_pos, (e.det_to_matrix_orthonormalBasis_real f).resolve_right h] variable {e f} /-- Two orthonormal bases with the same orientation determine the same "determinant" top-dimensional form on `E`, and conversely. -/ theorem same_orientation_iff_det_eq_det : e.toBasis.det = f.toBasis.det ↔ e.toBasis.orientation = f.toBasis.orientation := by constructor · intro h dsimp [Basis.orientation] congr · intro h rw [e.toBasis.det.eq_smul_basis_det f.toBasis] simp [e.det_to_matrix_orthonormalBasis_of_same_orientation f h] variable (e f) /-- Two orthonormal bases with opposite orientations determine opposite "determinant" top-dimensional forms on `E`. -/ theorem det_eq_neg_det_of_opposite_orientation (h : e.toBasis.orientation ≠ f.toBasis.orientation) : e.toBasis.det = -f.toBasis.det := by rw [e.toBasis.det.eq_smul_basis_det f.toBasis] simp [e.det_to_matrix_orthonormalBasis_of_opposite_orientation f h] variable [Nonempty ι] section AdjustToOrientation /-- `OrthonormalBasis.adjustToOrientation`, applied to an orthonormal basis, preserves the property of orthonormality. -/ theorem orthonormal_adjustToOrientation : Orthonormal ℝ (e.toBasis.adjustToOrientation x) := by apply e.orthonormal.orthonormal_of_forall_eq_or_eq_neg simpa using e.toBasis.adjustToOrientation_apply_eq_or_eq_neg x /-- Given an orthonormal basis and an orientation, return an orthonormal basis giving that orientation: either the original basis, or one constructed by negating a single (arbitrary) basis vector. -/ def adjustToOrientation : OrthonormalBasis ι ℝ E := (e.toBasis.adjustToOrientation x).toOrthonormalBasis (e.orthonormal_adjustToOrientation x) theorem toBasis_adjustToOrientation : (e.adjustToOrientation x).toBasis = e.toBasis.adjustToOrientation x := (e.toBasis.adjustToOrientation x).toBasis_toOrthonormalBasis _ /-- `adjustToOrientation` gives an orthonormal basis with the required orientation. -/ @[simp] theorem orientation_adjustToOrientation : (e.adjustToOrientation x).toBasis.orientation = x := by rw [e.toBasis_adjustToOrientation] exact e.toBasis.orientation_adjustToOrientation x /-- Every basis vector from `adjustToOrientation` is either that from the original basis or its negation. -/ theorem adjustToOrientation_apply_eq_or_eq_neg (i : ι) : e.adjustToOrientation x i = e i ∨ e.adjustToOrientation x i = -e i := by simpa [← e.toBasis_adjustToOrientation] using e.toBasis.adjustToOrientation_apply_eq_or_eq_neg x i theorem det_adjustToOrientation : (e.adjustToOrientation x).toBasis.det = e.toBasis.det ∨ (e.adjustToOrientation x).toBasis.det = -e.toBasis.det := by simpa using e.toBasis.det_adjustToOrientation x theorem abs_det_adjustToOrientation (v : ι → E) : |(e.adjustToOrientation x).toBasis.det v| = |e.toBasis.det v| := by simp [toBasis_adjustToOrientation] end AdjustToOrientation end OrthonormalBasis namespace Orientation variable {n : ℕ} open OrthonormalBasis /-- An orthonormal basis, indexed by `Fin n`, with the given orientation. -/ protected def finOrthonormalBasis (hn : 0 < n) (h : finrank ℝ E = n) (x : Orientation ℝ E (Fin n)) : OrthonormalBasis (Fin n) ℝ E := by haveI := Fin.pos_iff_nonempty.1 hn haveI : FiniteDimensional ℝ E := .of_finrank_pos <| h.symm ▸ hn exact ((@stdOrthonormalBasis _ _ _ _ _ this).reindex <| finCongr h).adjustToOrientation x /-- `Orientation.finOrthonormalBasis` gives a basis with the required orientation. -/ @[simp] theorem finOrthonormalBasis_orientation (hn : 0 < n) (h : finrank ℝ E = n) (x : Orientation ℝ E (Fin n)) : (x.finOrthonormalBasis hn h).toBasis.orientation = x := by haveI := Fin.pos_iff_nonempty.1 hn haveI : FiniteDimensional ℝ E := .of_finrank_pos <| h.symm ▸ hn exact ((@stdOrthonormalBasis _ _ _ _ _ this).reindex <| finCongr h).orientation_adjustToOrientation x section VolumeForm variable [_i : Fact (finrank ℝ E = n)] (o : Orientation ℝ E (Fin n)) /-- The volume form on an oriented real inner product space, a nonvanishing top-dimensional alternating form uniquely defined by compatibility with the orientation and inner product structure. -/ irreducible_def volumeForm : E [⋀^Fin n]→ₗ[ℝ] ℝ := by classical cases n with | zero => let opos : E [⋀^Fin 0]→ₗ[ℝ] ℝ := .constOfIsEmpty ℝ E (Fin 0) (1 : ℝ) exact o.eq_or_eq_neg_of_isEmpty.by_cases (fun _ => opos) fun _ => -opos | succ n => exact (o.finOrthonormalBasis n.succ_pos _i.out).toBasis.det @[simp] theorem volumeForm_zero_pos [_i : Fact (finrank ℝ E = 0)] : Orientation.volumeForm (positiveOrientation : Orientation ℝ E (Fin 0)) = AlternatingMap.constLinearEquivOfIsEmpty 1 := by simp [volumeForm, Or.by_cases] theorem volumeForm_zero_neg [_i : Fact (finrank ℝ E = 0)] : Orientation.volumeForm (-positiveOrientation : Orientation ℝ E (Fin 0)) = -AlternatingMap.constLinearEquivOfIsEmpty 1 := by simp_rw [volumeForm, Or.by_cases, positiveOrientation] apply if_neg simp only [neg_rayOfNeZero] rw [ray_eq_iff, SameRay.sameRay_comm] intro h simpa using congr_arg AlternatingMap.constLinearEquivOfIsEmpty.symm (eq_zero_of_sameRay_self_neg h) /-- The volume form on an oriented real inner product space can be evaluated as the determinant with respect to any orthonormal basis of the space compatible with the orientation. -/ theorem volumeForm_robust (b : OrthonormalBasis (Fin n) ℝ E) (hb : b.toBasis.orientation = o) : o.volumeForm = b.toBasis.det := by cases n · classical have : o = positiveOrientation := hb.symm.trans b.toBasis.orientation_isEmpty simp_rw [volumeForm, Or.by_cases, dif_pos this, Nat.rec_zero, Basis.det_isEmpty] · simp_rw [volumeForm] rw [same_orientation_iff_det_eq_det, hb] exact o.finOrthonormalBasis_orientation _ _ /-- The volume form on an oriented real inner product space can be evaluated as the determinant with respect to any orthonormal basis of the space compatible with the orientation. -/ theorem volumeForm_robust_neg (b : OrthonormalBasis (Fin n) ℝ E) (hb : b.toBasis.orientation ≠ o) : o.volumeForm = -b.toBasis.det := by rcases n with - | n · classical have : positiveOrientation ≠ o := by rwa [b.toBasis.orientation_isEmpty] at hb simp_rw [volumeForm, Or.by_cases, dif_neg this.symm, Nat.rec_zero, Basis.det_isEmpty] let e : OrthonormalBasis (Fin n.succ) ℝ E := o.finOrthonormalBasis n.succ_pos Fact.out simp_rw [volumeForm] apply e.det_eq_neg_det_of_opposite_orientation b convert hb.symm exact o.finOrthonormalBasis_orientation _ _ @[simp] theorem volumeForm_neg_orientation : (-o).volumeForm = -o.volumeForm := by rcases n with - | n · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl · simp [volumeForm_zero_neg] · simp [volumeForm_zero_neg] let e : OrthonormalBasis (Fin n.succ) ℝ E := o.finOrthonormalBasis n.succ_pos Fact.out have h₁ : e.toBasis.orientation = o := o.finOrthonormalBasis_orientation _ _ have h₂ : e.toBasis.orientation ≠ -o := by symm rw [e.toBasis.orientation_ne_iff_eq_neg, h₁] rw [o.volumeForm_robust e h₁, (-o).volumeForm_robust_neg e h₂] theorem volumeForm_robust' (b : OrthonormalBasis (Fin n) ℝ E) (v : Fin n → E) : |o.volumeForm v| = |b.toBasis.det v| := by cases n · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl <;> simp · rw [o.volumeForm_robust (b.adjustToOrientation o) (b.orientation_adjustToOrientation o), b.abs_det_adjustToOrientation] /-- Let `v` be an indexed family of `n` vectors in an oriented `n`-dimensional real inner product space `E`. The output of the volume form of `E` when evaluated on `v` is bounded in absolute value by the product of the norms of the vectors `v i`. -/ theorem abs_volumeForm_apply_le (v : Fin n → E) : |o.volumeForm v| ≤ ∏ i : Fin n, ‖v i‖ := by rcases n with - | n · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl <;> simp haveI : FiniteDimensional ℝ E := .of_fact_finrank_eq_succ n have : finrank ℝ E = Fintype.card (Fin n.succ) := by simpa using _i.out let b : OrthonormalBasis (Fin n.succ) ℝ E := gramSchmidtOrthonormalBasis this v have hb : b.toBasis.det v = ∏ i, ⟪b i, v i⟫ := gramSchmidtOrthonormalBasis_det this v rw [o.volumeForm_robust' b, hb, Finset.abs_prod] apply Finset.prod_le_prod · intro i _ positivity intro i _ convert abs_real_inner_le_norm (b i) (v i) simp [b.orthonormal.1 i] theorem volumeForm_apply_le (v : Fin n → E) : o.volumeForm v ≤ ∏ i : Fin n, ‖v i‖ := (le_abs_self _).trans (o.abs_volumeForm_apply_le v) /-- Let `v` be an indexed family of `n` orthogonal vectors in an oriented `n`-dimensional real inner product space `E`. The output of the volume form of `E` when evaluated on `v` is, up to sign, the product of the norms of the vectors `v i`. -/ theorem abs_volumeForm_apply_of_pairwise_orthogonal {v : Fin n → E} (hv : Pairwise fun i j => ⟪v i, v j⟫ = 0) : |o.volumeForm v| = ∏ i : Fin n, ‖v i‖ := by rcases n with - | n · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl <;> simp haveI : FiniteDimensional ℝ E := .of_fact_finrank_eq_succ n have hdim : finrank ℝ E = Fintype.card (Fin n.succ) := by simpa using _i.out let b : OrthonormalBasis (Fin n.succ) ℝ E := gramSchmidtOrthonormalBasis hdim v have hb : b.toBasis.det v = ∏ i, ⟪b i, v i⟫ := gramSchmidtOrthonormalBasis_det hdim v rw [o.volumeForm_robust' b, hb, Finset.abs_prod] by_cases h : ∃ i, v i = 0 · obtain ⟨i, hi⟩ := h rw [Finset.prod_eq_zero (Finset.mem_univ i), Finset.prod_eq_zero (Finset.mem_univ i)] <;> simp [hi] push_neg at h congr ext i have hb : b i = ‖v i‖⁻¹ • v i := gramSchmidtOrthonormalBasis_apply_of_orthogonal hdim hv (h i) simp only [hb, inner_smul_left, real_inner_self_eq_norm_mul_norm, RCLike.conj_to_real] rw [abs_of_nonneg] · field_simp · positivity /-- The output of the volume form of an oriented real inner product space `E` when evaluated on an orthonormal basis is ±1. -/ theorem abs_volumeForm_apply_of_orthonormal (v : OrthonormalBasis (Fin n) ℝ E) : |o.volumeForm v| = 1 := by simpa [o.volumeForm_robust' v v] using congr_arg abs v.toBasis.det_self theorem volumeForm_map {F : Type*} [NormedAddCommGroup F] [InnerProductSpace ℝ F] [Fact (finrank ℝ F = n)] (φ : E ≃ₗᵢ[ℝ] F) (x : Fin n → F) : (Orientation.map (Fin n) φ.toLinearEquiv o).volumeForm x = o.volumeForm (φ.symm ∘ x) := by rcases n with - | n · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl <;> simp let e : OrthonormalBasis (Fin n.succ) ℝ E := o.finOrthonormalBasis n.succ_pos Fact.out have he : e.toBasis.orientation = o := o.finOrthonormalBasis_orientation n.succ_pos Fact.out have heφ : (e.map φ).toBasis.orientation = Orientation.map (Fin n.succ) φ.toLinearEquiv o := by rw [← he] exact e.toBasis.orientation_map φ.toLinearEquiv rw [(Orientation.map (Fin n.succ) φ.toLinearEquiv o).volumeForm_robust (e.map φ) heφ] rw [o.volumeForm_robust e he] simp /-- The volume form is invariant under pullback by a positively-oriented isometric automorphism. -/ theorem volumeForm_comp_linearIsometryEquiv (φ : E ≃ₗᵢ[ℝ] E) (hφ : 0 < LinearMap.det (φ.toLinearEquiv : E →ₗ[ℝ] E)) (x : Fin n → E) : o.volumeForm (φ ∘ x) = o.volumeForm x := by rcases n with - | n -- Porting note: need to explicitly prove `FiniteDimensional ℝ E` · refine o.eq_or_eq_neg_of_isEmpty.elim ?_ ?_ <;> rintro rfl <;> simp haveI : FiniteDimensional ℝ E := .of_fact_finrank_eq_succ n convert o.volumeForm_map φ (φ ∘ x) · symm rwa [← o.map_eq_iff_det_pos φ.toLinearEquiv] at hφ rw [_i.out, Fintype.card_fin] · ext simp end VolumeForm end Orientation
ContinuousPreimage.lean
/- Copyright (c) 2024 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Topology.CompactOpen import Mathlib.Dynamics.Ergodic.MeasurePreserving import Mathlib.MeasureTheory.Measure.Regular /-! # Continuity of the preimage of a set under a measure preserving continuous function In this file we prove that the preimage of a null measurable set `s : Set Y` under a measure preserving continuous function `f : C(X, Y)` is continuous in `f` in the sense that `μ ((f a ⁻¹' s) ∆ (g ⁻¹' s))` tends to zero as `f a` tends to `g`. As a corollary, we show that for a continuous family of continuous maps `f z : C(X, Y)`, a null measurable set `s`, and a null measurable set `t` of finite measure, the set of parameters `z` such that `f z ⁻¹' t` is a.e. equal to `s` is a closed set. -/ open Filter Set open scoped ENNReal symmDiff Topology namespace MeasureTheory variable {α X Y Z : Type*} [TopologicalSpace X] [MeasurableSpace X] [BorelSpace X] [R1Space X] [TopologicalSpace Y] [MeasurableSpace Y] [BorelSpace Y] [R1Space Y] [TopologicalSpace Z] {μ : Measure X} {ν : Measure Y} [μ.InnerRegularCompactLTTop] [IsLocallyFiniteMeasure ν] /-- Let `X` and `Y` be R₁ topological spaces with Borel σ-algebras and measures `μ` and `ν`, respectively. Suppose that `μ` is inner regular for finite measure sets with respect to compact sets and `ν` is a locally finite measure. Let `f : α → C(X, Y)` be a family of continuous maps that converges to a continuous map `g : C(X, Y)` in the compact-open topology along a filter `l`. Suppose that `g` is a measure preserving map and `f a` is a measure preserving map eventually along `l`. Then for any finite measure measurable set `s`, the preimages `f a ⁻¹' s` tend to the preimage `g ⁻¹' s` in measure. More precisely, the measure of the symmetric difference of these two sets tends to zero. -/ theorem tendsto_measure_symmDiff_preimage_nhds_zero {l : Filter α} {f : α → C(X, Y)} {g : C(X, Y)} {s : Set Y} (hfg : Tendsto f l (𝓝 g)) (hf : ∀ᶠ a in l, MeasurePreserving (f a) μ ν) (hg : MeasurePreserving g μ ν) (hs : NullMeasurableSet s ν) (hνs : ν s ≠ ∞) : Tendsto (fun a ↦ μ ((f a ⁻¹' s) ∆ (g ⁻¹' s))) l (𝓝 0) := by have : ν.InnerRegularCompactLTTop := by rw [← hg.map_eq] exact .map_of_continuous (map_continuous _) rw [ENNReal.tendsto_nhds_zero] intro ε hε -- Without loss of generality, `s` is an open set. wlog hso : IsOpen s generalizing s ε · have H : 0 < ε / 3 := ENNReal.div_pos hε.ne' ENNReal.coe_ne_top -- Indeed, we can choose an open set `U` such that `ν (U ∆ s) < ε / 3`, -- apply the lemma to `U`, then use the triangle inequality for `μ (_ ∆ _)`. rcases hs.exists_isOpen_symmDiff_lt hνs H.ne' with ⟨U, hUo, hU, hUs⟩ have hmU : NullMeasurableSet U ν := hUo.measurableSet.nullMeasurableSet replace hUs := hUs.le filter_upwards [hf, this hmU hU.ne _ H hUo] with a hfa ha calc μ ((f a ⁻¹' s) ∆ (g ⁻¹' s)) ≤ μ ((f a ⁻¹' s) ∆ (f a ⁻¹' U)) + μ ((f a ⁻¹' U) ∆ (g ⁻¹' U)) + μ ((g ⁻¹' U) ∆ (g ⁻¹' s)) := by refine (measure_symmDiff_le _ (g ⁻¹' U) _).trans ?_ gcongr apply measure_symmDiff_le _ ≤ ε / 3 + ε / 3 + ε / 3 := by gcongr · rwa [← preimage_symmDiff, hfa.measure_preimage (hs.symmDiff hmU), symmDiff_comm] · rwa [← preimage_symmDiff, hg.measure_preimage (hmU.symmDiff hs)] _ = ε := by simp -- Take a compact closed subset `K ⊆ g ⁻¹' s` of almost full measure, -- `μ (g ⁻¹' s \ K) < ε / 2`. have hνs' : μ (g ⁻¹' s) ≠ ∞ := by rwa [hg.measure_preimage hs] obtain ⟨K, hKg, hKco, hKcl, hKμ⟩ : ∃ K, MapsTo g K s ∧ IsCompact K ∧ IsClosed K ∧ μ (g ⁻¹' s \ K) < ε / 2 := (hg.measurable hso.measurableSet).exists_isCompact_isClosed_diff_lt hνs' <| by simp [hε.ne'] have hKm : NullMeasurableSet K μ := hKcl.nullMeasurableSet -- Take `a` such that `f a` is measure preserving and maps `K` to `s`. -- This is possible, because `K` is a compact set and `s` is an open set. filter_upwards [hf, ContinuousMap.tendsto_nhds_compactOpen.mp hfg K hKco s hso hKg] with a hfa ha -- Then each of the sets `g ⁻¹' s ∆ K = g ⁻¹' s \ K` and `f a ⁻¹' s ∆ K = f a ⁻¹' s \ K` -- have measure at most `ε / 2`, thus `f a ⁻¹' s ∆ g ⁻¹' s` has measure at most `ε`. rw [← ENNReal.add_halves ε] refine (measure_symmDiff_le _ K _).trans ?_ rw [symmDiff_of_ge ha.subset_preimage, symmDiff_of_le hKg.subset_preimage] gcongr have hK' : μ K ≠ ∞ := ne_top_of_le_ne_top hνs' <| measure_mono hKg.subset_preimage rw [measure_diff_le_iff_le_add hKm ha.subset_preimage hK', hfa.measure_preimage hs, ← hg.measure_preimage hs, ← measure_diff_le_iff_le_add hKm hKg.subset_preimage hK'] exact hKμ.le /-- Let `f : Z → C(X, Y)` be a continuous (in the compact open topology) family of continuous measure preserving maps. Let `t : Set Y` be a null measurable set of finite measure. Then for any `s`, the set of parameters `z` such that the preimage of `t` under `f_z` is a.e. equal to `s` is a closed set. In particular, if `X = Y` and `s = t`, then we see that the a.e. stabilizer of a set is a closed set. -/ theorem isClosed_setOf_preimage_ae_eq {f : Z → C(X, Y)} (hf : Continuous f) (hfm : ∀ z, MeasurePreserving (f z) μ ν) (s : Set X) {t : Set Y} (htm : NullMeasurableSet t ν) (ht : ν t ≠ ∞) : IsClosed {z | f z ⁻¹' t =ᵐ[μ] s} := by rw [← isOpen_compl_iff, isOpen_iff_mem_nhds] intro z hz replace hz : ∀ᶠ ε : ℝ≥0∞ in 𝓝 0, ε < μ ((f z ⁻¹' t) ∆ s) := by apply gt_mem_nhds rwa [pos_iff_ne_zero, ne_eq, measure_symmDiff_eq_zero_iff] filter_upwards [(tendsto_measure_symmDiff_preimage_nhds_zero (hf.tendsto z) (.of_forall hfm) (hfm z) htm ht).eventually hz] with w hw intro (hw' : f w ⁻¹' t =ᵐ[μ] s) rw [measure_congr (hw'.symmDiff (ae_eq_refl _)), symmDiff_comm] at hw exact hw.false end MeasureTheory
LevyProkhorovMetric.lean
/- Copyright (c) 2023 Kalle Kytölä. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kalle Kytölä -/ import Mathlib.MeasureTheory.Measure.Portmanteau import Mathlib.MeasureTheory.Integral.DominatedConvergence import Mathlib.MeasureTheory.Integral.Layercake import Mathlib.MeasureTheory.Integral.BoundedContinuousFunction /-! # The Lévy-Prokhorov distance on spaces of finite measures and probability measures ## Main definitions * `MeasureTheory.levyProkhorovEDist`: The Lévy-Prokhorov edistance between two measures. * `MeasureTheory.levyProkhorovDist`: The Lévy-Prokhorov distance between two finite measures. ## Main results * `levyProkhorovDist_pseudoMetricSpace_finiteMeasure`: The Lévy-Prokhorov distance is a pseudoemetric on the space of finite measures. * `levyProkhorovDist_pseudoMetricSpace_probabilityMeasure`: The Lévy-Prokhorov distance is a pseudoemetric on the space of probability measures. * `levyProkhorov_le_convergenceInDistribution`: The topology of the Lévy-Prokhorov metric on probability measures is always at least as fine as the topology of convergence in distribution. * `levyProkhorov_eq_convergenceInDistribution`: The topology of the Lévy-Prokhorov metric on probability measures on a separable space coincides with the topology of convergence in distribution, and in particular convergence in distribution is then pseudometrizable. ## Tags finite measure, probability measure, weak convergence, convergence in distribution, metrizability -/ open Topology Metric Filter Set ENNReal NNReal namespace MeasureTheory open scoped Topology ENNReal NNReal BoundedContinuousFunction section Levy_Prokhorov /-! ### Lévy-Prokhorov metric -/ variable {Ω : Type*} [MeasurableSpace Ω] [PseudoEMetricSpace Ω] /-- The Lévy-Prokhorov edistance between measures: `d(μ,ν) = inf {r ≥ 0 | ∀ B, μ B ≤ ν Bᵣ + r ∧ ν B ≤ μ Bᵣ + r}`. -/ noncomputable def levyProkhorovEDist (μ ν : Measure Ω) : ℝ≥0∞ := sInf {ε | ∀ B, MeasurableSet B → μ B ≤ ν (thickening ε.toReal B) + ε ∧ ν B ≤ μ (thickening ε.toReal B) + ε} /- This result is not placed in earlier more generic files, since it is rather specialized; it mixes measure and metric in a very particular way. -/ lemma meas_le_of_le_of_forall_le_meas_thickening_add {ε₁ ε₂ : ℝ≥0∞} (μ ν : Measure Ω) (h_le : ε₁ ≤ ε₂) {B : Set Ω} (hε₁ : μ B ≤ ν (thickening ε₁.toReal B) + ε₁) : μ B ≤ ν (thickening ε₂.toReal B) + ε₂ := by by_cases ε_top : ε₂ = ∞ · simp only [ε_top, toReal_top, add_top, le_top] apply hε₁.trans (add_le_add ?_ h_le) exact measure_mono (μ := ν) (thickening_mono (toReal_mono ε_top h_le) B) lemma left_measure_le_of_levyProkhorovEDist_lt {μ ν : Measure Ω} {c : ℝ≥0∞} (h : levyProkhorovEDist μ ν < c) {B : Set Ω} (B_mble : MeasurableSet B) : μ B ≤ ν (thickening c.toReal B) + c := by obtain ⟨c', ⟨hc', lt_c⟩⟩ := sInf_lt_iff.mp h exact meas_le_of_le_of_forall_le_meas_thickening_add μ ν lt_c.le (hc' B B_mble).1 lemma right_measure_le_of_levyProkhorovEDist_lt {μ ν : Measure Ω} {c : ℝ≥0∞} (h : levyProkhorovEDist μ ν < c) {B : Set Ω} (B_mble : MeasurableSet B) : ν B ≤ μ (thickening c.toReal B) + c := by obtain ⟨c', ⟨hc', lt_c⟩⟩ := sInf_lt_iff.mp h exact meas_le_of_le_of_forall_le_meas_thickening_add ν μ lt_c.le (hc' B B_mble).2 /-- A general sufficient condition for bounding `levyProkhorovEDist` from above. -/ lemma levyProkhorovEDist_le_of_forall_add_pos_le (μ ν : Measure Ω) (δ : ℝ≥0∞) (h : ∀ ε B, 0 < ε → ε < ∞ → MeasurableSet B → μ B ≤ ν (thickening (δ + ε).toReal B) + δ + ε ∧ ν B ≤ μ (thickening (δ + ε).toReal B) + δ + ε) : levyProkhorovEDist μ ν ≤ δ := by apply ENNReal.le_of_forall_pos_le_add intro ε hε _ by_cases ε_top : ε = ∞ · simp only [ε_top, add_top, le_top] apply sInf_le intro B B_mble simpa only [add_assoc] using h ε B (coe_pos.mpr hε) coe_lt_top B_mble /-- A simple general sufficient condition for bounding `levyProkhorovEDist` from above. -/ lemma levyProkhorovEDist_le_of_forall (μ ν : Measure Ω) (δ : ℝ≥0∞) (h : ∀ ε B, δ < ε → ε < ∞ → MeasurableSet B → μ B ≤ ν (thickening ε.toReal B) + ε ∧ ν B ≤ μ (thickening ε.toReal B) + ε) : levyProkhorovEDist μ ν ≤ δ := by by_cases δ_top : δ = ∞ · simp only [δ_top, le_top] apply levyProkhorovEDist_le_of_forall_add_pos_le intro x B x_pos x_lt_top B_mble simpa only [← add_assoc] using h (δ + x) B (ENNReal.lt_add_right δ_top x_pos.ne.symm) (by simp only [add_lt_top, Ne.lt_top δ_top, x_lt_top, and_self]) B_mble lemma levyProkhorovEDist_le_max_measure_univ (μ ν : Measure Ω) : levyProkhorovEDist μ ν ≤ max (μ univ) (ν univ) := by refine sInf_le fun B _ ↦ ⟨?_, ?_⟩ <;> apply le_add_left <;> simp [measure_mono] lemma levyProkhorovEDist_lt_top (μ ν : Measure Ω) [IsFiniteMeasure μ] [IsFiniteMeasure ν] : levyProkhorovEDist μ ν < ∞ := (levyProkhorovEDist_le_max_measure_univ μ ν).trans_lt <| by simp [measure_lt_top] lemma levyProkhorovEDist_ne_top (μ ν : Measure Ω) [IsFiniteMeasure μ] [IsFiniteMeasure ν] : levyProkhorovEDist μ ν ≠ ∞ := (levyProkhorovEDist_lt_top μ ν).ne lemma levyProkhorovEDist_self (μ : Measure Ω) : levyProkhorovEDist μ μ = 0 := by rw [← nonpos_iff_eq_zero, ← csInf_Ioo zero_lt_top] refine sInf_le_sInf fun ε ⟨hε₀, hε_top⟩ B _ ↦ and_self_iff.2 ?_ refine le_add_right <| measure_mono <| self_subset_thickening ?_ _ exact ENNReal.toReal_pos hε₀.ne' hε_top.ne lemma levyProkhorovEDist_comm (μ ν : Measure Ω) : levyProkhorovEDist μ ν = levyProkhorovEDist ν μ := by simp only [levyProkhorovEDist, and_comm] lemma levyProkhorovEDist_triangle [OpensMeasurableSpace Ω] (μ ν κ : Measure Ω) : levyProkhorovEDist μ κ ≤ levyProkhorovEDist μ ν + levyProkhorovEDist ν κ := by by_cases LPμν_finite : levyProkhorovEDist μ ν = ∞ · simp [LPμν_finite] by_cases LPνκ_finite : levyProkhorovEDist ν κ = ∞ · simp [LPνκ_finite] apply levyProkhorovEDist_le_of_forall_add_pos_le intro ε B ε_pos ε_lt_top B_mble have half_ε_pos : 0 < ε / 2 := ENNReal.div_pos ε_pos.ne' ofNat_ne_top have half_ε_lt_top : ε / 2 ≠ ∞ := by finiteness let r := levyProkhorovEDist μ ν + ε / 2 let s := levyProkhorovEDist ν κ + ε / 2 have lt_r : levyProkhorovEDist μ ν < r := lt_add_right LPμν_finite half_ε_pos.ne' have lt_s : levyProkhorovEDist ν κ < s := lt_add_right LPνκ_finite half_ε_pos.ne' have hs_add_r : s + r = levyProkhorovEDist μ ν + levyProkhorovEDist ν κ + ε := by simp_rw [s, r, add_assoc, add_comm (ε / 2), add_assoc, ENNReal.add_halves, ← add_assoc, add_comm (levyProkhorovEDist μ ν)] have hs_add_r' : s.toReal + r.toReal = (levyProkhorovEDist μ ν + levyProkhorovEDist ν κ + ε).toReal := by rw [← hs_add_r, ← ENNReal.toReal_add] · finiteness · finiteness rw [← hs_add_r', add_assoc, ← hs_add_r, add_assoc _ _ ε, ← hs_add_r] refine ⟨?_, ?_⟩ · calc μ B ≤ ν (thickening r.toReal B) + r := left_measure_le_of_levyProkhorovEDist_lt lt_r B_mble _ ≤ κ (thickening s.toReal (thickening r.toReal B)) + s + r := add_le_add_right (left_measure_le_of_levyProkhorovEDist_lt lt_s isOpen_thickening.measurableSet) _ _ = κ (thickening s.toReal (thickening r.toReal B)) + (s + r) := add_assoc _ _ _ _ ≤ κ (thickening (s.toReal + r.toReal) B) + (s + r) := add_le_add_right (measure_mono (thickening_thickening_subset _ _ _)) _ · calc κ B ≤ ν (thickening s.toReal B) + s := right_measure_le_of_levyProkhorovEDist_lt lt_s B_mble _ ≤ μ (thickening r.toReal (thickening s.toReal B)) + r + s := add_le_add_right (right_measure_le_of_levyProkhorovEDist_lt lt_r isOpen_thickening.measurableSet) s _ = μ (thickening r.toReal (thickening s.toReal B)) + (s + r) := by rw [add_assoc, add_comm r] _ ≤ μ (thickening (r.toReal + s.toReal) B) + (s + r) := add_le_add_right (measure_mono (thickening_thickening_subset _ _ _)) _ _ = μ (thickening (s.toReal + r.toReal) B) + (s + r) := by rw [add_comm r.toReal] /-- The Lévy-Prokhorov distance between finite measures: `d(μ,ν) = inf {r ≥ 0 | ∀ B, μ B ≤ ν Bᵣ + r ∧ ν B ≤ μ Bᵣ + r}`. -/ noncomputable def levyProkhorovDist (μ ν : Measure Ω) : ℝ := (levyProkhorovEDist μ ν).toReal lemma levyProkhorovDist_self (μ : Measure Ω) : levyProkhorovDist μ μ = 0 := by simp only [levyProkhorovDist, levyProkhorovEDist_self, toReal_zero] lemma levyProkhorovDist_comm (μ ν : Measure Ω) : levyProkhorovDist μ ν = levyProkhorovDist ν μ := by simp only [levyProkhorovDist, levyProkhorovEDist_comm] lemma levyProkhorovDist_triangle [OpensMeasurableSpace Ω] (μ ν κ : Measure Ω) [IsFiniteMeasure μ] [IsFiniteMeasure ν] [IsFiniteMeasure κ] : levyProkhorovDist μ κ ≤ levyProkhorovDist μ ν + levyProkhorovDist ν κ := by have dμν_finite := (levyProkhorovEDist_lt_top μ ν).ne have dνκ_finite := (levyProkhorovEDist_lt_top ν κ).ne convert ENNReal.toReal_mono ?_ <| levyProkhorovEDist_triangle μ ν κ · simp only [levyProkhorovDist, ENNReal.toReal_add dμν_finite dνκ_finite] · exact ENNReal.add_ne_top.mpr ⟨dμν_finite, dνκ_finite⟩ /-- A type synonym, to be used for `Measure α`, `FiniteMeasure α`, or `ProbabilityMeasure α`, when they are to be equipped with the Lévy-Prokhorov distance. -/ def LevyProkhorov (α : Type*) := α /-- The "identity" equivalence between the type synonym `LevyProkhorov α` and `α`. -/ def LevyProkhorov.equiv (α : Type*) : LevyProkhorov α ≃ α := Equiv.refl _ variable [OpensMeasurableSpace Ω] /-- The Lévy-Prokhorov distance `levyProkhorovEDist` makes `Measure Ω` a pseudoemetric space. The instance is recorded on the type synonym `LevyProkhorov (Measure Ω) := Measure Ω`. -/ noncomputable instance : PseudoEMetricSpace (LevyProkhorov (Measure Ω)) where edist := levyProkhorovEDist edist_self := levyProkhorovEDist_self edist_comm := levyProkhorovEDist_comm edist_triangle := levyProkhorovEDist_triangle /-- The Lévy-Prokhorov distance `levyProkhorovDist` makes `FiniteMeasure Ω` a pseudometric space. The instance is recorded on the type synonym `LevyProkhorov (FiniteMeasure Ω) := FiniteMeasure Ω`. -/ noncomputable instance levyProkhorovDist_pseudoMetricSpace_finiteMeasure : PseudoMetricSpace (LevyProkhorov (FiniteMeasure Ω)) where dist μ ν := levyProkhorovDist μ.toMeasure ν.toMeasure dist_self _ := levyProkhorovDist_self _ dist_comm _ _ := levyProkhorovDist_comm _ _ dist_triangle _ _ _ := levyProkhorovDist_triangle _ _ _ edist_dist μ ν := by simp [← ENNReal.ofReal_coe_nnreal] lemma measure_le_measure_closure_of_levyProkhorovEDist_eq_zero {μ ν : Measure Ω} (hLP : levyProkhorovEDist μ ν = 0) {s : Set Ω} (s_mble : MeasurableSet s) (h_finite : ∃ δ > 0, ν (thickening δ s) ≠ ∞) : μ s ≤ ν (closure s) := by have key : Tendsto (fun ε ↦ ν (thickening ε.toReal s)) (𝓝[>] (0 : ℝ≥0∞)) (𝓝 (ν (closure s))) := by have aux : Tendsto ENNReal.toReal (𝓝[>] 0) (𝓝[>] 0) := by apply tendsto_nhdsWithin_of_tendsto_nhds_of_eventually_within (s := Ioi 0) ENNReal.toReal · exact tendsto_nhdsWithin_of_tendsto_nhds (continuousAt_toReal zero_ne_top).tendsto · filter_upwards [Ioo_mem_nhdsGT zero_lt_one] with x hx exact toReal_pos hx.1.ne' <| ne_top_of_lt hx.2 exact (tendsto_measure_thickening h_finite).comp aux have obs := Tendsto.add key (tendsto_nhdsWithin_of_tendsto_nhds tendsto_id) simp only [id_eq, add_zero] at obs apply ge_of_tendsto (b := μ s) obs filter_upwards [self_mem_nhdsWithin] with ε ε_pos exact left_measure_le_of_levyProkhorovEDist_lt (B_mble := s_mble) (hLP ▸ ε_pos) /-- Two measures at vanishing Lévy-Prokhorov distance from each other assign the same values to all closed sets. -/ lemma measure_eq_measure_of_levyProkhorovEDist_eq_zero_of_isClosed {μ ν : Measure Ω} (hLP : levyProkhorovEDist μ ν = 0) {s : Set Ω} (s_closed : IsClosed s) (hμs : ∃ δ > 0, μ (thickening δ s) ≠ ∞) (hνs : ∃ δ > 0, ν (thickening δ s) ≠ ∞) : μ s = ν s := by apply le_antisymm · exact measure_le_measure_closure_of_levyProkhorovEDist_eq_zero hLP s_closed.measurableSet hνs |>.trans <| le_of_eq (congr_arg _ s_closed.closure_eq) · exact measure_le_measure_closure_of_levyProkhorovEDist_eq_zero (levyProkhorovEDist_comm μ ν ▸ hLP) s_closed.measurableSet hμs |>.trans <| le_of_eq (congr_arg _ s_closed.closure_eq) /-- The Lévy-Prokhorov distance `levyProkhorovDist` makes `ProbabilityMeasure Ω` a pseudometric space. The instance is recorded on the type synonym `LevyProkhorov (ProbabilityMeasure Ω) := ProbabilityMeasure Ω`. Note: For this pseudometric to give the topology of convergence in distribution, one must furthermore assume that `Ω` is separable. -/ noncomputable instance levyProkhorovDist_pseudoMetricSpace_probabilityMeasure : PseudoMetricSpace (LevyProkhorov (ProbabilityMeasure Ω)) where dist μ ν := levyProkhorovDist μ.toMeasure ν.toMeasure dist_self _ := levyProkhorovDist_self _ dist_comm _ _ := levyProkhorovDist_comm _ _ dist_triangle _ _ _ := levyProkhorovDist_triangle _ _ _ edist_dist μ ν := by simp [← ENNReal.ofReal_coe_nnreal] lemma LevyProkhorov.dist_def (μ ν : LevyProkhorov (ProbabilityMeasure Ω)) : dist μ ν = levyProkhorovDist μ.toMeasure ν.toMeasure := rfl /-- If `Ω` is a Borel space, then the Lévy-Prokhorov distance `levyProkhorovDist` makes `ProbabilityMeasure Ω` a metric space. The instance is recorded on the type synonym `LevyProkhorov (ProbabilityMeasure Ω) := ProbabilityMeasure Ω`. Note: For this metric to give the topology of convergence in distribution, one must furthermore assume that `Ω` is separable. -/ noncomputable instance levyProkhorovDist_metricSpace_probabilityMeasure [BorelSpace Ω] : MetricSpace (LevyProkhorov (ProbabilityMeasure Ω)) where eq_of_dist_eq_zero := by intro μ ν h apply (LevyProkhorov.equiv _).injective apply ProbabilityMeasure.toMeasure_injective apply ext_of_generate_finite _ ?_ isPiSystem_isClosed ?_ (by simp) · rw [BorelSpace.measurable_eq (α := Ω), borel_eq_generateFrom_isClosed] · intro A A_closed apply measure_eq_measure_of_levyProkhorovEDist_eq_zero_of_isClosed · simpa only [levyProkhorovEDist_ne_top μ.toMeasure ν.toMeasure, mem_setOf_eq, or_false, ne_eq, zero_ne_top, not_false_eq_true, toReal_zero] using (toReal_eq_zero_iff _).mp h · exact A_closed · exact ⟨1, Real.zero_lt_one, measure_ne_top _ _⟩ · exact ⟨1, Real.zero_lt_one, measure_ne_top _ _⟩ /-- A simple sufficient condition for bounding `levyProkhorovEDist` between probability measures from above. The condition involves only one of two natural bounds, the other bound is for free. -/ lemma levyProkhorovEDist_le_of_forall_le (μ ν : Measure Ω) [IsProbabilityMeasure μ] [IsProbabilityMeasure ν] (δ : ℝ≥0∞) (h : ∀ ε B, δ < ε → ε < ∞ → MeasurableSet B → μ B ≤ ν (thickening ε.toReal B) + ε) : levyProkhorovEDist μ ν ≤ δ := by apply levyProkhorovEDist_le_of_forall μ ν δ intro ε B ε_gt ε_lt_top B_mble refine ⟨h ε B ε_gt ε_lt_top B_mble, ?_⟩ have B_subset := subset_compl_thickening_compl_thickening_self ε.toReal B apply (measure_mono (μ := ν) B_subset).trans rw [prob_compl_eq_one_sub isOpen_thickening.measurableSet] have Tc_mble := (isOpen_thickening (δ := ε.toReal) (E := B)).isClosed_compl.measurableSet specialize h ε (thickening ε.toReal B)ᶜ ε_gt ε_lt_top Tc_mble rw [prob_compl_eq_one_sub isOpen_thickening.measurableSet] at h have almost := add_le_add (c := μ (thickening ε.toReal B)) h rfl.le rw [tsub_add_cancel_of_le prob_le_one, add_assoc] at almost apply (tsub_le_tsub_right almost _).trans rw [ENNReal.add_sub_cancel_left (measure_ne_top ν _), add_comm ε] /-- A simple sufficient condition for bounding `levyProkhorovDist` between probability measures from above. The condition involves only one of two natural bounds, the other bound is for free. -/ lemma levyProkhorovDist_le_of_forall_le (μ ν : Measure Ω) [IsProbabilityMeasure μ] [IsProbabilityMeasure ν] {δ : ℝ} (δ_nn : 0 ≤ δ) (h : ∀ ε B, δ < ε → MeasurableSet B → μ B ≤ ν (thickening ε B) + ENNReal.ofReal ε) : levyProkhorovDist μ ν ≤ δ := by apply toReal_le_of_le_ofReal δ_nn apply levyProkhorovEDist_le_of_forall_le intro ε B ε_gt ε_lt_top B_mble have ε_gt' : δ < ε.toReal := by refine (ofReal_lt_ofReal_iff ?_).mp ?_ · exact ENNReal.toReal_pos (ne_zero_of_lt ε_gt) ε_lt_top.ne · simpa [ofReal_toReal_eq_iff.mpr ε_lt_top.ne] using ε_gt convert h ε.toReal B ε_gt' B_mble exact (ENNReal.ofReal_toReal ε_lt_top.ne).symm end Levy_Prokhorov --section section Levy_Prokhorov_is_finer /-! ### The Lévy-Prokhorov topology is at least as fine as convergence in distribution -/ open BoundedContinuousFunction variable {Ω : Type*} [MeasurableSpace Ω] variable [PseudoMetricSpace Ω] [OpensMeasurableSpace Ω] /-- A version of the layer cake formula for bounded continuous functions which have finite integral: ∫ f dμ = ∫ t in (0, ‖f‖], μ {x | f(x) ≥ t} dt. -/ lemma BoundedContinuousFunction.integral_eq_integral_meas_le_of_hasFiniteIntegral {α : Type*} [MeasurableSpace α] [TopologicalSpace α] [OpensMeasurableSpace α] (f : α →ᵇ ℝ) (μ : Measure α) (f_nn : 0 ≤ᵐ[μ] f) (hf : HasFiniteIntegral f μ) : ∫ ω, f ω ∂μ = ∫ t in Ioc 0 ‖f‖, μ.real {a : α | t ≤ f a} := by rw [Integrable.integral_eq_integral_Ioc_meas_le (M := ‖f‖) ?_ f_nn ?_] · exact ⟨f.continuous.measurable.aestronglyMeasurable, hf⟩ · exact Eventually.of_forall (fun x ↦ BoundedContinuousFunction.apply_le_norm f x) /-- A version of the layer cake formula for bounded continuous functions and finite measures: ∫ f dμ = ∫ t in (0, ‖f‖], μ {x | f(x) ≥ t} dt. -/ lemma BoundedContinuousFunction.integral_eq_integral_meas_le {α : Type*} [MeasurableSpace α] [TopologicalSpace α] [OpensMeasurableSpace α] (f : α →ᵇ ℝ) (μ : Measure α) [IsFiniteMeasure μ] (f_nn : 0 ≤ᵐ[μ] f) : ∫ ω, f ω ∂μ = ∫ t in Ioc 0 ‖f‖, μ.real {a : α | t ≤ f a} := integral_eq_integral_meas_le_of_hasFiniteIntegral _ _ f_nn (f.integrable μ).2 /-- Assuming `levyProkhorovEDist μ ν < ε`, we can bound `∫ f ∂μ` in terms of `∫ t in (0, ‖f‖], ν (thickening ε {x | f(x) ≥ t}) dt` and `‖f‖`. -/ lemma BoundedContinuousFunction.integral_le_of_levyProkhorovEDist_lt (μ ν : Measure Ω) [IsFiniteMeasure μ] [IsFiniteMeasure ν] {ε : ℝ} (ε_pos : 0 < ε) (hμν : levyProkhorovEDist μ ν < ENNReal.ofReal ε) (f : Ω →ᵇ ℝ) (f_nn : 0 ≤ᵐ[μ] f) : ∫ ω, f ω ∂μ ≤ (∫ t in Ioc 0 ‖f‖, ν.real (thickening ε {a | t ≤ f a})) + ε * ‖f‖ := by rw [BoundedContinuousFunction.integral_eq_integral_meas_le f μ f_nn] have key : (fun (t : ℝ) ↦ μ.real {a | t ≤ f a}) ≤ (fun (t : ℝ) ↦ ν.real (thickening ε {a | t ≤ f a}) + ε) := by intro t simp only [measureReal_def] convert ENNReal.toReal_mono ?_ <| left_measure_le_of_levyProkhorovEDist_lt hμν (B := {a | t ≤ f a}) (f.continuous.measurable measurableSet_Ici) · rw [ENNReal.toReal_add (measure_ne_top ν _) ofReal_ne_top, ENNReal.toReal_ofReal ε_pos.le] · exact ENNReal.add_ne_top.mpr ⟨measure_ne_top ν _, ofReal_ne_top⟩ have intble₁ : IntegrableOn (fun t ↦ μ.real {a | t ≤ f a}) (Ioc 0 ‖f‖) := by apply Measure.integrableOn_of_bounded (M := μ.real univ) measure_Ioc_lt_top.ne · apply (Measurable.ennreal_toReal (Antitone.measurable ?_)).aestronglyMeasurable exact fun _ _ hst ↦ measure_mono (fun _ h ↦ hst.trans h) · apply Eventually.of_forall <| fun t ↦ ?_ simp only [Real.norm_eq_abs, abs_of_nonneg measureReal_nonneg] exact measureReal_mono (subset_univ _) have intble₂ : IntegrableOn (fun t ↦ ν.real (thickening ε {a | t ≤ f a})) (Ioc 0 ‖f‖) := by apply Measure.integrableOn_of_bounded (M := ν.real univ) measure_Ioc_lt_top.ne · apply (Measurable.ennreal_toReal (Antitone.measurable ?_)).aestronglyMeasurable exact fun _ _ hst ↦ measure_mono <| thickening_subset_of_subset ε (fun _ h ↦ hst.trans h) · apply Eventually.of_forall <| fun t ↦ ?_ simp only [Real.norm_eq_abs, abs_of_nonneg measureReal_nonneg] exact ENNReal.toReal_mono (by finiteness) <| measure_mono (subset_univ _) apply le_trans (setIntegral_mono (s := Ioc 0 ‖f‖) ?_ ?_ key) · rw [integral_add] · apply add_le_add_left simp [(mul_comm _ ε).le] · exact intble₂ · exact integrable_const ε · exact intble₁ · exact intble₂.add <| integrable_const ε /-- A monotone decreasing convergence lemma for integrals of measures of thickenings: `∫ t in (0, ‖f‖], μ (thickening ε {x | f(x) ≥ t}) dt` tends to `∫ t in (0, ‖f‖], μ {x | f(x) ≥ t} dt` as `ε → 0`. -/ lemma tendsto_integral_meas_thickening_le (f : Ω →ᵇ ℝ) {A : Set ℝ} (A_finmeas : volume A ≠ ∞) (μ : ProbabilityMeasure Ω) : Tendsto (fun ε ↦ ∫ t in A, (Measure.real μ (thickening ε {a | t ≤ f a}))) (𝓝[>] (0 : ℝ)) (𝓝 (∫ t in A, (Measure.real μ {a | t ≤ f a}))) := by apply tendsto_integral_filter_of_dominated_convergence (G := ℝ) (μ := volume.restrict A) (F := fun ε t ↦ (μ (thickening ε {a | t ≤ f a}))) (f := fun t ↦ (μ {a | t ≤ f a})) 1 · apply Eventually.of_forall fun n ↦ Measurable.aestronglyMeasurable ?_ simp only [measurable_coe_nnreal_real_iff] apply measurable_toNNReal.comp <| Antitone.measurable (fun s t hst ↦ ?_) exact measure_mono <| thickening_subset_of_subset _ <| fun ω h ↦ hst.trans h · apply Eventually.of_forall (fun i ↦ ?_) apply Eventually.of_forall (fun t ↦ ?_) simp only [Real.norm_eq_abs, NNReal.abs_eq, Pi.one_apply] exact ENNReal.toReal_mono one_ne_top prob_le_one · have aux : IsFiniteMeasure (volume.restrict A) := ⟨by simp [lt_top_iff_ne_top, A_finmeas]⟩ apply integrable_const · apply Eventually.of_forall (fun t ↦ ?_) simp only [NNReal.tendsto_coe] apply (ENNReal.tendsto_toNNReal _).comp · apply tendsto_measure_thickening_of_isClosed ?_ ?_ · exact ⟨1, ⟨Real.zero_lt_one, measure_ne_top _ _⟩⟩ · exact isClosed_le continuous_const f.continuous · finiteness /-- The identity map `LevyProkhorov (ProbabilityMeasure Ω) → ProbabilityMeasure Ω` is continuous. -/ lemma LevyProkhorov.continuous_equiv_probabilityMeasure : Continuous (LevyProkhorov.equiv (α := ProbabilityMeasure Ω)) := by refine SeqContinuous.continuous ?_ intro μs ν hμs set P := LevyProkhorov.equiv _ ν -- more palatable notation set Ps := fun n ↦ LevyProkhorov.equiv _ (μs n) -- more palatable notation rw [ProbabilityMeasure.tendsto_iff_forall_integral_tendsto] refine fun f ↦ tendsto_integral_of_forall_limsup_integral_le_integral ?_ f intro f f_nn by_cases f_zero : ‖f‖ = 0 · simp only [norm_eq_zero] at f_zero simp [f_zero, limsup_const] have norm_f_pos : 0 < ‖f‖ := lt_of_le_of_ne (norm_nonneg _) (fun a => f_zero a.symm) apply _root_.le_of_forall_pos_le_add intro δ δ_pos apply limsup_le_of_le ?_ · obtain ⟨εs, ⟨_, ⟨εs_pos, εs_lim⟩⟩⟩ := exists_seq_strictAnti_tendsto (0 : ℝ) have ε_of_room := Tendsto.add (tendsto_iff_dist_tendsto_zero.mp hμs) εs_lim have ε_of_room' : Tendsto (fun n ↦ dist (μs n) ν + εs n) atTop (𝓝[>] 0) := by rw [tendsto_nhdsWithin_iff] refine ⟨by simpa using ε_of_room, Eventually.of_forall fun n ↦ ?_⟩ · rw [mem_Ioi] linarith [εs_pos n, dist_nonneg (x := μs n) (y := ν)] rw [add_zero] at ε_of_room have key := (tendsto_integral_meas_thickening_le f (A := Ioc 0 ‖f‖) (by simp) P).comp ε_of_room' have aux : ∀ (z : ℝ), Iio (z + δ/2) ∈ 𝓝 z := fun z ↦ Iio_mem_nhds (by linarith) filter_upwards [key (aux _), ε_of_room <| Iio_mem_nhds <| half_pos <| mul_pos (inv_pos.mpr norm_f_pos) δ_pos] with n hn hn' simp only [mem_preimage, mem_Iio] at * specialize εs_pos n have bound := BoundedContinuousFunction.integral_le_of_levyProkhorovEDist_lt (Ps n) P (ε := dist (μs n) ν + εs n) ?_ ?_ f ?_ · refine bound.trans ?_ apply (add_le_add_right hn.le _).trans rw [BoundedContinuousFunction.integral_eq_integral_meas_le] · rw [add_assoc, mul_comm] gcongr calc δ / 2 + ‖f‖ * (dist (μs n) ν + εs n) _ ≤ δ / 2 + ‖f‖ * (‖f‖⁻¹ * δ / 2) := by gcongr _ = δ := by field_simp; ring · exact Eventually.of_forall f_nn · positivity · rw [ENNReal.ofReal_add (by positivity) (by positivity), ← add_zero (levyProkhorovEDist _ _)] apply ENNReal.add_lt_add_of_le_of_lt (levyProkhorovEDist_ne_top _ _) (le_of_eq ?_) (ofReal_pos.mpr εs_pos) rw [LevyProkhorov.dist_def, levyProkhorovDist, ofReal_toReal (levyProkhorovEDist_ne_top _ _)] rfl · exact Eventually.of_forall f_nn · simp only [IsCoboundedUnder, IsCobounded, eventually_map, eventually_atTop, forall_exists_index] refine ⟨0, fun a i hia ↦ le_trans (integral_nonneg f_nn) (hia i le_rfl)⟩ /-- The topology of the Lévy-Prokhorov metric is at least as fine as the topology of convergence in distribution. -/ theorem levyProkhorov_le_convergenceInDistribution : TopologicalSpace.coinduced (LevyProkhorov.equiv (α := ProbabilityMeasure Ω)) inferInstance ≤ (inferInstance : TopologicalSpace (ProbabilityMeasure Ω)) := (LevyProkhorov.continuous_equiv_probabilityMeasure).coinduced_le end Levy_Prokhorov_is_finer section Levy_Prokhorov_metrizes_convergence_in_distribution /-! ### On separable spaces the Lévy-Prokhorov distance metrizes convergence in distribution -/ open BoundedContinuousFunction TopologicalSpace variable {Ω : Type*} [PseudoMetricSpace Ω] variable [MeasurableSpace Ω] [OpensMeasurableSpace Ω] lemma ProbabilityMeasure.toMeasure_add_pos_gt_mem_nhds (P : ProbabilityMeasure Ω) {G : Set Ω} (G_open : IsOpen G) {ε : ℝ≥0∞} (ε_pos : 0 < ε) : {Q | P.toMeasure G < Q.toMeasure G + ε} ∈ 𝓝 P := by by_cases easy : P.toMeasure G < ε · exact Eventually.of_forall (fun _ ↦ lt_of_lt_of_le easy le_add_self) by_cases ε_top : ε = ∞ · simp [ε_top, measure_lt_top] simp only [not_lt] at easy have aux : P.toMeasure G - ε < liminf (fun Q ↦ Q.toMeasure G) (𝓝 P) := by apply lt_of_lt_of_le (ENNReal.sub_lt_self (by finiteness) _ _) <| ProbabilityMeasure.le_liminf_measure_open_of_tendsto tendsto_id G_open · exact (lt_of_lt_of_le ε_pos easy).ne.symm · exact ε_pos.ne.symm filter_upwards [gt_mem_sets_of_limsInf_gt (α := ℝ≥0∞) isBounded_ge_of_bot (show P.toMeasure G - ε < limsInf ((𝓝 P).map (fun Q ↦ Q.toMeasure G)) from aux)] with Q hQ simp only [preimage_setOf_eq, mem_setOf_eq] at hQ convert ENNReal.add_lt_add_right ε_top hQ exact (tsub_add_cancel_of_le easy).symm variable [SeparableSpace Ω] variable (Ω) in /-- In a separable pseudometric space, for any ε > 0 there exists a countable collection of disjoint Borel measurable subsets of diameter at most ε that cover the whole space. -/ lemma SeparableSpace.exists_measurable_partition_diam_le {ε : ℝ} (ε_pos : 0 < ε) : ∃ (As : ℕ → Set Ω), (∀ n, MeasurableSet (As n)) ∧ (∀ n, Bornology.IsBounded (As n)) ∧ (∀ n, diam (As n) ≤ ε) ∧ (⋃ n, As n = univ) ∧ (Pairwise (fun (n m : ℕ) ↦ Disjoint (As n) (As m))) := by by_cases X_emp : IsEmpty Ω · refine ⟨fun _ ↦ ∅, fun _ ↦ MeasurableSet.empty, fun _ ↦ Bornology.isBounded_empty, ?_, ?_, fun _ _ _ ↦ disjoint_of_subsingleton⟩ · intro n simpa only [diam_empty] using LT.lt.le ε_pos · subsingleton rw [not_isEmpty_iff] at X_emp obtain ⟨xs, xs_dense⟩ := exists_dense_seq Ω have half_ε_pos : 0 < ε / 2 := half_pos ε_pos set Bs := fun n ↦ Metric.ball (xs n) (ε / 2) set As := disjointed Bs refine ⟨As, ?_, ?_, ?_, ?_, ?_⟩ · exact MeasurableSet.disjointed (fun n ↦ measurableSet_ball) · exact fun n ↦ Bornology.IsBounded.subset isBounded_ball <| disjointed_subset Bs n · intro n apply (diam_mono (disjointed_subset Bs n) isBounded_ball).trans convert diam_ball half_ε_pos.le ring · have aux : ⋃ n, Bs n = univ := by convert DenseRange.iUnion_uniformity_ball xs_dense <| Metric.dist_mem_uniformity half_ε_pos exact (ball_eq_ball' _ _).symm simpa only [← aux] using iUnion_disjointed · exact disjoint_disjointed Bs lemma LevyProkhorov.continuous_equiv_symm_probabilityMeasure : Continuous (LevyProkhorov.equiv (α := ProbabilityMeasure Ω)).symm := by -- We check continuity of `id : ProbabilityMeasure Ω → LevyProkhorov (ProbabilityMeasure Ω)` at -- each point `P : ProbabilityMeasure Ω`. rw [continuous_iff_continuousAt] intro P -- To check continuity, fix `ε > 0`. To leave some wiggle room, be ready to use `ε/3 > 0` instead. rw [continuousAt_iff'] intro ε ε_pos have third_ε_pos : 0 < ε / 3 := by linarith have third_ε_pos' : 0 < ENNReal.ofReal (ε / 3) := ofReal_pos.mpr third_ε_pos -- First use separability to choose a countable partition of `Ω` into measurable -- subsets `Es n ⊆ Ω` of small diameter, `diam (Es n) < ε/3`. obtain ⟨Es, Es_mble, Es_bdd, Es_diam, Es_cover, Es_disjoint⟩ := SeparableSpace.exists_measurable_partition_diam_le Ω third_ε_pos -- Instead of the whole space `Ω = ⋃ n ∈ ℕ, Es n`, focus on a large but finite -- union `⋃ n < N, Es n`, chosen in such a way that the complement has small `P`-mass, -- `P (⋃ n < N, Es n)ᶜ < ε/3`. obtain ⟨N, hN⟩ : ∃ N, P.toMeasure (⋃ j ∈ Iio N, Es j)ᶜ < ENNReal.ofReal (ε/3) := by have exhaust := @tendsto_measure_biUnion_Ici_zero_of_pairwise_disjoint Ω _ P.toMeasure _ Es (fun n ↦ (Es_mble n).nullMeasurableSet) Es_disjoint simp only [tendsto_atTop_nhds, Function.comp_apply] at exhaust obtain ⟨N, hN⟩ := exhaust (Iio (ENNReal.ofReal (ε / 3))) third_ε_pos' isOpen_Iio refine ⟨N, ?_⟩ have rewr : ⋃ i, ⋃ (_ : N ≤ i), Es i = (⋃ i, ⋃ (_ : i < N), Es i)ᶜ := by simpa only [mem_Iio, compl_Iio, mem_Ici] using (biUnion_compl_eq_of_pairwise_disjoint_of_iUnion_eq_univ Es_cover Es_disjoint (Iio N)).symm simpa only [mem_Iio, ← rewr, gt_iff_lt] using hN N le_rfl -- With the finite `N` fixed above, consider the finite collection of open sets of the form -- `Gs J = thickening (ε/3) (⋃ j ∈ J, Es j)`, where `J ⊆ {0, 1, ..., N-1}`. have Js_finite : Set.Finite {J | J ⊆ Iio N} := Finite.finite_subsets <| finite_Iio N set Gs := (fun (J : Set ℕ) ↦ thickening (ε/3) (⋃ j ∈ J, Es j)) '' {J | J ⊆ Iio N} have Gs_open : ∀ (J : Set ℕ), IsOpen (thickening (ε/3) (⋃ j ∈ J, Es j)) := fun J ↦ isOpen_thickening -- Any open set `G ⊆ Ω` determines a neighborhood of `P` consisting of those `Q` that -- satisfy `P G < Q G + ε/3`. have mem_nhds_P (G : Set Ω) (G_open : IsOpen G) : {Q | P.toMeasure G < Q.toMeasure G + ENNReal.ofReal (ε/3)} ∈ 𝓝 P := P.toMeasure_add_pos_gt_mem_nhds G_open third_ε_pos' -- Assume that `Q` is in the neighborhood of `P` such that for each `J ⊆ {0, 1, ..., N-1}` -- we have `P (Gs J) < Q (Gs J) + ε/3`. filter_upwards [(Finset.iInter_mem_sets Js_finite.toFinset).mpr <| fun J _ ↦ mem_nhds_P _ (Gs_open J)] with Q hQ simp only [Finite.mem_toFinset, mem_setOf_eq, thickening_iUnion, mem_iInter] at hQ -- Note that in order to show that the Lévy-Prokhorov distance `LPdist P Q` is small (`≤ 2*ε/3`), -- it suffices to show that for arbitrary subsets `B ⊆ Ω`, the measure `P B` is bounded above up -- to a small error by the `Q`-measure of a small thickening of `B`. apply lt_of_le_of_lt ?_ (show 2*(ε/3) < ε by linarith) rw [dist_comm] -- Fix an arbitrary set `B ⊆ Ω`, and an arbitrary `δ > 2*ε/3` to gain some room for error -- and for thickening. apply levyProkhorovDist_le_of_forall_le _ _ (by linarith) (fun δ B δ_gt _ ↦ ?_) -- Let `JB ⊆ {0, 1, ..., N-1}` consist of those indices `j` such that `B` intersects `Es j`. -- Then the open set `Gs JB` approximates `B` rather well: -- except for what happens in the small complement `(⋃ n < N, Es n)ᶜ`, the set `B` is -- contained in `Gs JB`, and conversely `Gs JB` only contains points within `δ` from `B`. set JB := {i | B ∩ Es i ≠ ∅ ∧ i ∈ Iio N} have B_subset : B ⊆ (⋃ i ∈ JB, thickening (ε/3) (Es i)) ∪ (⋃ j ∈ Iio N, Es j)ᶜ := by suffices B ⊆ (⋃ i ∈ JB, thickening (ε/3) (Es i)) ∪ (⋃ j ∈ Ici N, Es j) by refine this.trans <| union_subset_union le_rfl ?_ intro ω hω simp only [mem_Ici, mem_iUnion, exists_prop] at hω obtain ⟨i, i_large, ω_in_Esi⟩ := hω by_contra con simp only [mem_Iio, compl_iUnion, mem_iInter, mem_compl_iff, not_forall, not_not, exists_prop] at con obtain ⟨j, j_small, ω_in_Esj⟩ := con exact disjoint_left.mp (Es_disjoint (show j ≠ i by omega)) ω_in_Esj ω_in_Esi intro ω ω_in_B obtain ⟨i, hi⟩ := show ∃ n, ω ∈ Es n by simp only [← mem_iUnion, Es_cover, mem_univ] simp only [mem_Ici, mem_union, mem_iUnion, exists_prop] by_cases i_small : i ∈ Iio N · refine Or.inl ⟨i, ?_, self_subset_thickening third_ε_pos _ hi⟩ simp only [mem_Iio, mem_setOf_eq, JB] refine ⟨nonempty_iff_ne_empty.mp <| Set.nonempty_of_mem <| mem_inter ω_in_B hi, i_small⟩ · exact Or.inr ⟨i, by simpa only [mem_Iio, not_lt] using i_small, hi⟩ have subset_thickB : ⋃ i ∈ JB, thickening (ε / 3) (Es i) ⊆ thickening δ B := by intro ω ω_in_U simp only [mem_iUnion, exists_prop] at ω_in_U obtain ⟨k, ⟨B_intersects, _⟩, ω_in_thEk⟩ := ω_in_U rw [mem_thickening_iff] at ω_in_thEk ⊢ obtain ⟨w, w_in_Ek, w_near⟩ := ω_in_thEk obtain ⟨z, ⟨z_in_B, z_in_Ek⟩⟩ := nonempty_iff_ne_empty.mpr B_intersects refine ⟨z, z_in_B, lt_of_le_of_lt (dist_triangle ω w z) ?_⟩ apply lt_of_le_of_lt (add_le_add w_near.le <| (dist_le_diam_of_mem (Es_bdd k) w_in_Ek z_in_Ek).trans <| Es_diam k) linarith -- We use the resulting upper bound `P B ≤ P (Gs JB) + P (small complement)`. apply (measure_mono B_subset).trans ((measure_union_le _ _).trans ?_) -- From the choice of `Q` in a suitable neighborhood, we have `P (Gs JB) < Q (Gs JB) + ε/3`. specialize hQ _ (show JB ⊆ Iio N from fun _ h ↦ h.2) -- Now it remains to add the pieces and use the above estimates. apply (add_le_add hQ.le hN.le).trans rw [add_assoc, ← ENNReal.ofReal_add third_ε_pos.le third_ε_pos.le, ← two_mul] apply add_le_add (measure_mono subset_thickB) (ofReal_le_ofReal _) exact δ_gt.le /-- The topology of the Lévy-Prokhorov metric on probability measures on a separable space coincides with the topology of convergence in distribution. -/ theorem levyProkhorov_eq_convergenceInDistribution : (inferInstance : TopologicalSpace (ProbabilityMeasure Ω)) = TopologicalSpace.coinduced (LevyProkhorov.equiv _) inferInstance := le_antisymm (LevyProkhorov.continuous_equiv_symm_probabilityMeasure (Ω := Ω)).coinduced_le levyProkhorov_le_convergenceInDistribution /-- The identity map is a homeomorphism from `ProbabilityMeasure Ω` with the topology of convergence in distribution to `ProbabilityMeasure Ω` with the Lévy-Prokhorov (pseudo)metric. -/ noncomputable def homeomorph_probabilityMeasure_levyProkhorov : ProbabilityMeasure Ω ≃ₜ LevyProkhorov (ProbabilityMeasure Ω) where toFun := LevyProkhorov.equiv _ invFun := (LevyProkhorov.equiv _).symm left_inv := congrFun rfl right_inv := congrFun rfl continuous_toFun := LevyProkhorov.continuous_equiv_symm_probabilityMeasure continuous_invFun := LevyProkhorov.continuous_equiv_probabilityMeasure /-- The topology of convergence in distribution on a separable space is pseudo-metrizable. -/ instance (X : Type*) [TopologicalSpace X] [PseudoMetrizableSpace X] [SeparableSpace X] [MeasurableSpace X] [OpensMeasurableSpace X] : PseudoMetrizableSpace (ProbabilityMeasure X) := letI : PseudoMetricSpace X := TopologicalSpace.pseudoMetrizableSpacePseudoMetric X (homeomorph_probabilityMeasure_levyProkhorov (Ω := X)).isInducing.pseudoMetrizableSpace /-- The topology of convergence in distribution on a separable Borel space is metrizable. -/ instance instMetrizableSpaceProbabilityMeasure (X : Type*) [TopologicalSpace X] [PseudoMetrizableSpace X] [SeparableSpace X] [MeasurableSpace X] [BorelSpace X] : MetrizableSpace (ProbabilityMeasure X) := by letI : PseudoMetricSpace X := TopologicalSpace.pseudoMetrizableSpacePseudoMetric X exact homeomorph_probabilityMeasure_levyProkhorov.isEmbedding.metrizableSpace end Levy_Prokhorov_metrizes_convergence_in_distribution end MeasureTheory -- namespace
Basic.lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Analysis.InnerProductSpace.Basic import Mathlib.Analysis.Normed.Group.AddTorsor import Mathlib.Tactic.AdaptationNote /-! # Inversion in an affine space In this file we define inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. In many applications, it is convenient to assume that the inversions swaps the center and the point at infinity. In order to stay in the original affine space, we define the map so that it sends center to itself. Currently, we prove only a few basic lemmas needed to prove Ptolemy's inequality, see `EuclideanGeometry.mul_dist_le_mul_dist_add_mul_dist`. -/ noncomputable section open Metric Function AffineMap Set AffineSubspace open scoped Topology variable {V P : Type*} [NormedAddCommGroup V] [InnerProductSpace ℝ V] [MetricSpace P] [NormedAddTorsor V P] namespace EuclideanGeometry variable {c x y : P} {R : ℝ} /-- Inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. -/ def inversion (c : P) (R : ℝ) (x : P) : P := (R / dist x c) ^ 2 • (x -ᵥ c) +ᵥ c theorem inversion_def : inversion = fun (c : P) (R : ℝ) (x : P) => (R / dist x c) ^ 2 • (x -ᵥ c) +ᵥ c := rfl /-! ### Basic properties In this section we prove that `EuclideanGeometry.inversion c R` is involutive and preserves the sphere `Metric.sphere c R`. We also prove that the distance to the center of the image of `x` under this inversion is given by `R ^ 2 / dist x c`. -/ theorem inversion_eq_lineMap (c : P) (R : ℝ) (x : P) : inversion c R x = lineMap c x ((R / dist x c) ^ 2) := rfl theorem inversion_vsub_center (c : P) (R : ℝ) (x : P) : inversion c R x -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c) := vadd_vsub _ _ @[simp] theorem inversion_self (c : P) (R : ℝ) : inversion c R c = c := by simp [inversion] @[simp] theorem inversion_zero_radius (c x : P) : inversion c 0 x = c := by simp [inversion] theorem inversion_mul (c : P) (a R : ℝ) (x : P) : inversion c (a * R) x = homothety c (a ^ 2) (inversion c R x) := by simp only [inversion_eq_lineMap, ← homothety_eq_lineMap, ← homothety_mul_apply, mul_div_assoc, mul_pow] @[simp] theorem inversion_dist_center (c x : P) : inversion c (dist x c) x = x := by rcases eq_or_ne x c with (rfl | hne) · apply inversion_self · rw [inversion, div_self, one_pow, one_smul, vsub_vadd] rwa [dist_ne_zero] @[simp] theorem inversion_dist_center' (c x : P) : inversion c (dist c x) x = x := by rw [dist_comm, inversion_dist_center] theorem inversion_of_mem_sphere (h : x ∈ Metric.sphere c R) : inversion c R x = x := h.out ▸ inversion_dist_center c x /-- Distance from the image of a point under inversion to the center. This formula accidentally works for `x = c`. -/ theorem dist_inversion_center (c x : P) (R : ℝ) : dist (inversion c R x) c = R ^ 2 / dist x c := by rcases eq_or_ne x c with (rfl | hx) · simp have : dist x c ≠ 0 := dist_ne_zero.2 hx -- was `field_simp [inversion, norm_smul, abs_div, ← dist_eq_norm_vsub, sq, mul_assoc]`, -- but really slow. Replaced by `simp only ...` to speed up. -- TODO(https://github.com/leanprover-community/mathlib4/issues/15486): reinstate `field_simp` once it is faster. simp (disch := field_simp_discharge) only [inversion, sq, mul_div_assoc', div_mul_eq_mul_div, div_div, dist_vadd_left, norm_smul, norm_div, norm_mul, Real.norm_eq_abs, abs_mul_abs_self, abs_dist, ← dist_eq_norm_vsub, mul_assoc, eq_div_iff, div_eq_iff] /-- Distance from the center of an inversion to the image of a point under the inversion. This formula accidentally works for `x = c`. -/ theorem dist_center_inversion (c x : P) (R : ℝ) : dist c (inversion c R x) = R ^ 2 / dist c x := by rw [dist_comm c, dist_comm c, dist_inversion_center] @[simp] theorem inversion_inversion (c : P) {R : ℝ} (hR : R ≠ 0) (x : P) : inversion c R (inversion c R x) = x := by rcases eq_or_ne x c with (rfl | hne) · rw [inversion_self, inversion_self] · rw [inversion, dist_inversion_center, inversion_vsub_center, smul_smul, ← mul_pow, div_mul_div_comm, div_mul_cancel₀ _ (dist_ne_zero.2 hne), ← sq, div_self, one_pow, one_smul, vsub_vadd] exact pow_ne_zero _ hR theorem inversion_involutive (c : P) {R : ℝ} (hR : R ≠ 0) : Involutive (inversion c R) := inversion_inversion c hR theorem inversion_surjective (c : P) {R : ℝ} (hR : R ≠ 0) : Surjective (inversion c R) := (inversion_involutive c hR).surjective theorem inversion_injective (c : P) {R : ℝ} (hR : R ≠ 0) : Injective (inversion c R) := (inversion_involutive c hR).injective theorem inversion_bijective (c : P) {R : ℝ} (hR : R ≠ 0) : Bijective (inversion c R) := (inversion_involutive c hR).bijective theorem inversion_eq_center (hR : R ≠ 0) : inversion c R x = c ↔ x = c := (inversion_injective c hR).eq_iff' <| inversion_self _ _ @[simp] theorem inversion_eq_center' : inversion c R x = c ↔ x = c ∨ R = 0 := by by_cases hR : R = 0 <;> simp [inversion_eq_center, hR] theorem center_eq_inversion (hR : R ≠ 0) : c = inversion c R x ↔ x = c := eq_comm.trans (inversion_eq_center hR) @[simp] theorem center_eq_inversion' : c = inversion c R x ↔ x = c ∨ R = 0 := eq_comm.trans inversion_eq_center' /-! ### Similarity of triangles If inversion with center `O` sends `A` to `A'` and `B` to `B'`, then the triangle `OB'A'` is similar to the triangle `OAB` with coefficient `R ^ 2 / (|OA|*|OB|)` and the triangle `OA'B` is similar to the triangle `OAB'` with coefficient `|OB|/|OA|`. We formulate these statements in terms of ratios of the lengths of their sides. -/ /-- Distance between the images of two points under an inversion. -/ theorem dist_inversion_inversion (hx : x ≠ c) (hy : y ≠ c) (R : ℝ) : dist (inversion c R x) (inversion c R y) = R ^ 2 / (dist x c * dist y c) * dist x y := by dsimp only [inversion] simp_rw [dist_vadd_cancel_right, dist_eq_norm_vsub V _ c] simpa only [dist_vsub_cancel_right] using dist_div_norm_sq_smul (vsub_ne_zero.2 hx) (vsub_ne_zero.2 hy) R theorem dist_inversion_mul_dist_center_eq (hx : x ≠ c) (hy : y ≠ c) : dist (inversion c R x) y * dist x c = dist x (inversion c R y) * dist y c := by rcases eq_or_ne R 0 with rfl | hR; · simp [dist_comm, mul_comm] have hy' : inversion c R y ≠ c := by simp [*] conv in dist _ y => rw [← inversion_inversion c hR y] rw [dist_inversion_inversion hx hy', dist_inversion_center] have : dist x c ≠ 0 := dist_ne_zero.2 hx -- used to be `field_simp`, but was really slow; replaced by `simp only ...` to speed up -- TODO(https://github.com/leanprover-community/mathlib4/issues/15486): reinstate `field_simp` once it is faster. simp (disch := field_simp_discharge) only [mul_div_assoc', div_div_eq_mul_div, div_mul_eq_mul_div, div_eq_iff] ring /-! ### Ptolemy's inequality -/ include V in /-- **Ptolemy's inequality**: in a quadrangle `ABCD`, `|AC| * |BD| ≤ |AB| * |CD| + |BC| * |AD|`. If `ABCD` is a convex cyclic polygon, then this inequality becomes an equality, see `EuclideanGeometry.mul_dist_add_mul_dist_eq_mul_dist_of_cospherical`. -/ theorem mul_dist_le_mul_dist_add_mul_dist (a b c d : P) : dist a c * dist b d ≤ dist a b * dist c d + dist b c * dist a d := by -- If one of the points `b`, `c`, `d` is equal to `a`, then the inequality is trivial. rcases eq_or_ne b a with (rfl | hb) · rw [dist_self, zero_mul, zero_add] rcases eq_or_ne c a with (rfl | hc) · rw [dist_self, zero_mul] positivity rcases eq_or_ne d a with (rfl | hd) · rw [dist_self, mul_zero, add_zero, dist_comm d, dist_comm d, mul_comm] /- Otherwise, we apply the triangle inequality to `EuclideanGeometry.inversion a 1 b`, `EuclideanGeometry.inversion a 1 c`, and `EuclideanGeometry.inversion a 1 d`. -/ have H := dist_triangle (inversion a 1 b) (inversion a 1 c) (inversion a 1 d) rw [dist_inversion_inversion hb hd, dist_inversion_inversion hb hc, dist_inversion_inversion hc hd, one_pow] at H rw [← dist_pos] at hb hc hd rw [← div_le_div_iff_of_pos_right (mul_pos hb (mul_pos hc hd))] convert H using 1 <;> (field_simp [hb.ne', hc.ne', hd.ne', dist_comm a]; ring) end EuclideanGeometry open EuclideanGeometry /-! ### Continuity of inversion -/ protected theorem Filter.Tendsto.inversion {α : Type*} {x c : P} {R : ℝ} {l : Filter α} {fc fx : α → P} {fR : α → ℝ} (hc : Tendsto fc l (𝓝 c)) (hR : Tendsto fR l (𝓝 R)) (hx : Tendsto fx l (𝓝 x)) (hne : x ≠ c) : Tendsto (fun a ↦ inversion (fc a) (fR a) (fx a)) l (𝓝 (inversion c R x)) := (((hR.div (hx.dist hc) <| dist_ne_zero.2 hne).pow 2).smul (hx.vsub hc)).vadd hc variable {X : Type*} [TopologicalSpace X] {c x : X → P} {R : X → ℝ} {a₀ : X} {s : Set X} protected nonrec theorem ContinuousWithinAt.inversion (hc : ContinuousWithinAt c s a₀) (hR : ContinuousWithinAt R s a₀) (hx : ContinuousWithinAt x s a₀) (hne : x a₀ ≠ c a₀) : ContinuousWithinAt (fun a ↦ inversion (c a) (R a) (x a)) s a₀ := hc.inversion hR hx hne protected nonrec theorem ContinuousAt.inversion (hc : ContinuousAt c a₀) (hR : ContinuousAt R a₀) (hx : ContinuousAt x a₀) (hne : x a₀ ≠ c a₀) : ContinuousAt (fun a ↦ inversion (c a) (R a) (x a)) a₀ := hc.inversion hR hx hne protected theorem ContinuousOn.inversion (hc : ContinuousOn c s) (hR : ContinuousOn R s) (hx : ContinuousOn x s) (hne : ∀ a ∈ s, x a ≠ c a) : ContinuousOn (fun a ↦ inversion (c a) (R a) (x a)) s := fun a ha ↦ (hc a ha).inversion (hR a ha) (hx a ha) (hne a ha) protected theorem Continuous.inversion (hc : Continuous c) (hR : Continuous R) (hx : Continuous x) (hne : ∀ a, x a ≠ c a) : Continuous (fun a ↦ inversion (c a) (R a) (x a)) := continuous_iff_continuousAt.2 fun _ ↦ hc.continuousAt.inversion hR.continuousAt hx.continuousAt (hne _)
countalg.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrfun ssrbool eqtype ssrnat seq choice. From mathcomp Require Import fintype bigop ssralg. (*****************************************************************************) (* The algebraic part of the algebraic hierarchy for countable types *) (* *) (* This file clones part of ssralg hierarchy for countable types; it does *) (* not cover the left module / algebra interfaces, providing only *) (* countNmodType == countable nmodType interface *) (* countZmodType == countable zmodType interface *) (* countPzSemiRingType == countable pzSemiRingType interface *) (* countNzSemiRingType == countable nzSemiRingType interface *) (* countPzRingType == countable pzRingType interface *) (* countNzRingType == countable nzRingType interface *) (* countComPzSemiRingType == countable comPzSemiRingType interface *) (* countComNzSemiRingType == countable comNzSemiRingType interface *) (* countComPzRingType == countable comPzRingType interface *) (* countComNzRingType == countable comNzRingType interface *) (* countUnitRingType == countable unitRingType interface *) (* countComUnitRingType == countable comUnitRingType interface *) (* countIdomainType == countable idomainType interface *) (* countFieldType == countable fieldType interface *) (* countDecFieldType == countable decFieldType interface *) (* countClosedFieldType == countable closedFieldType interface *) (* *) (* This file provides constructions for both simple extension and algebraic *) (* closure of countable fields. *) (*****************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Local Open Scope ring_scope. Import GRing.Theory CodeSeq. Module CountRing. Import GRing.Theory. #[short(type="countNmodType")] HB.structure Definition Nmodule := {M of GRing.Nmodule M & Countable M}. #[short(type="countZmodType")] HB.structure Definition Zmodule := {M of GRing.Zmodule M & Countable M}. #[short(type="countPzSemiRingType")] HB.structure Definition PzSemiRing := {R of GRing.PzSemiRing R & Countable R}. #[short(type="countNzSemiRingType")] HB.structure Definition NzSemiRing := {R of GRing.NzSemiRing R & Countable R}. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzSemiRing instead.")] Notation SemiRing R := (NzSemiRing R) (only parsing). Module SemiRing. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzSemiRing.sort instead.")] Notation sort := (NzSemiRing.sort) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzSemiRing.on instead.")] Notation on R := (NzSemiRing.on R) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzSemiRing.copy instead.")] Notation copy T U := (NzSemiRing.copy T U) (only parsing). End SemiRing. #[short(type="countPzRingType")] HB.structure Definition PzRing := {R of GRing.PzRing R & Countable R}. #[short(type="countNzRingType")] HB.structure Definition NzRing := {R of GRing.NzRing R & Countable R}. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzRing instead.")] Notation Ring R := (NzRing R) (only parsing). Module Ring. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzRing.sort instead.")] Notation sort := (NzRing.sort) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzRing.on instead.")] Notation on R := (NzRing.on R) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.NzRing.copy instead.")] Notation copy T U := (NzRing.copy T U) (only parsing). End Ring. #[short(type="countComPzSemiRingType")] HB.structure Definition ComPzSemiRing := {R of GRing.ComPzSemiRing R & Countable R}. #[short(type="countComNzSemiRingType")] HB.structure Definition ComNzSemiRing := {R of GRing.ComNzSemiRing R & Countable R}. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzSemiRing instead.")] Notation ComSemiRing R := (ComNzSemiRing R) (only parsing). Module ComSemiRing. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzSemiRing.sort instead.")] Notation sort := (ComNzSemiRing.sort) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzSemiRing.on instead.")] Notation on R := (ComNzSemiRing.on R) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzSemiRing.copy instead.")] Notation copy T U := (ComNzSemiRing.copy T U) (only parsing). End ComSemiRing. #[short(type="countComPzRingType")] HB.structure Definition ComPzRing := {R of GRing.ComPzRing R & Countable R}. #[short(type="countComNzRingType")] HB.structure Definition ComNzRing := {R of GRing.ComNzRing R & Countable R}. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzRing instead.")] Notation ComRing R := (ComNzRing R) (only parsing). Module ComRing. #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzRing.sort instead.")] Notation sort := (ComNzRing.sort) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzRing.on instead.")] Notation on R := (ComNzRing.on R) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use CountRing.ComNzRing.copy instead.")] Notation copy T U := (ComNzRing.copy T U) (only parsing). End ComRing. #[short(type="countUnitRingType")] HB.structure Definition UnitRing := {R of GRing.UnitRing R & Countable R}. #[short(type="countComUnitRingType")] HB.structure Definition ComUnitRing := {R of GRing.ComUnitRing R & Countable R}. #[short(type="countIdomainType")] HB.structure Definition IntegralDomain := {R of GRing.IntegralDomain R & Countable R}. #[short(type="countFieldType")] HB.structure Definition Field := {R of GRing.Field R & Countable R}. #[short(type="countDecFieldType")] HB.structure Definition DecidableField := {R of GRing.DecidableField R & Countable R}. #[short(type="countClosedFieldType")] HB.structure Definition ClosedField := {R of GRing.ClosedField R & Countable R}. Module ReguralExports. HB.instance Definition _ (R : countType) := Countable.on R^o. HB.instance Definition _ (R : countNmodType) := Nmodule.on R^o. HB.instance Definition _ (R : countZmodType) := Zmodule.on R^o. HB.instance Definition _ (R : countPzSemiRingType) := PzSemiRing.on R^o. HB.instance Definition _ (R : countNzSemiRingType) := NzSemiRing.on R^o. HB.instance Definition _ (R : countPzRingType) := PzRing.on R^o. HB.instance Definition _ (R : countNzRingType) := NzRing.on R^o. HB.instance Definition _ (R : countComPzSemiRingType) := ComPzSemiRing.on R^o. HB.instance Definition _ (R : countComNzSemiRingType) := ComNzSemiRing.on R^o. HB.instance Definition _ (R : countComPzRingType) := ComPzRing.on R^o. HB.instance Definition _ (R : countComNzRingType) := ComNzRing.on R^o. HB.instance Definition _ (R : countUnitRingType) := UnitRing.on R^o. HB.instance Definition _ (R : countComUnitRingType) := ComUnitRing.on R^o. HB.instance Definition _ (R : countIdomainType) := IntegralDomain.on R^o. HB.instance Definition _ (R : countFieldType) := Field.on R^o. HB.instance Definition _ (R : countDecFieldType) := DecidableField.on R^o. HB.instance Definition _ (R : countClosedFieldType) := ClosedField.on R^o. End ReguralExports. HB.export ReguralExports. End CountRing. Import CountRing. HB.reexport. #[deprecated(since="mathcomp 2.4.0", note="Use countNzSemiRingType instead.")] Notation countSemiRingType := (countNzSemiRingType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use countNzRingType instead.")] Notation countRingType := (countNzRingType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use countComNzSemiRingType instead.")] Notation countComSemiRingType := (countComNzSemiRingType) (only parsing). #[deprecated(since="mathcomp 2.4.0", note="Use countComNzRingType instead.")] Notation countComRingType := (countComNzRingType) (only parsing).
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.Monoidal.FunctorCategory import Mathlib.CategoryTheory.Functor.Currying /-! # External product of diagrams in a monoidal category In a monoidal category `C`, given a pair of diagrams `K₁ : J₁ ⥤ C` and `K₂ : J₂ ⥤ C`, we introduce the external product `K₁ ⊠ K₂ : J₁ × J₂ ⥤ C` as the bifunctor `(j₁, j₂) ↦ K₁ j₁ ⊗ K₂ j₂`. The notation `- ⊠ -` is scoped to `MonoidalCategory.ExternalProduct`. -/ universe v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace CategoryTheory.MonoidalCategory open Functor variable (J₁ : Type u₁) (J₂ : Type u₂) (C : Type u₃) [Category.{v₁} J₁] [Category.{v₂} J₂] [Category.{v₃} C] [MonoidalCategory C] /-- The (curried version of the) external product bifunctor: given diagrams `K₁ : J₁ ⥤ C` and `K₂ : J₂ ⥤ C`, this is the bifunctor `j₁ ↦ j₂ ↦ K₁ j₁ ⊗ K₂ j₂`. -/ @[simps!] def externalProductBifunctorCurried : (J₁ ⥤ C) ⥤ (J₂ ⥤ C) ⥤ J₁ ⥤ J₂ ⥤ C := (Functor.postcompose₂.obj <| (evaluation _ _).obj <| curriedTensor C).obj <| whiskeringLeft₂ C /-- The external product bifunctor: given diagrams `K₁ : J₁ ⥤ C` and `K₂ : J₂ ⥤ C`, this is the bifunctor `(j₁, j₂) ↦ K₁ j₁ ⊗ K₂ j₂`. -/ @[simps!] def externalProductBifunctor : ((J₁ ⥤ C) × (J₂ ⥤ C)) ⥤ J₁ × J₂ ⥤ C := uncurry.obj <| (Functor.postcompose₂.obj <| uncurry).obj <| externalProductBifunctorCurried J₁ J₂ C variable {J₁ J₂ C} /-- An abbreviation for the action of `externalProductBifunctor J₁ J₂ C` on objects. -/ abbrev externalProduct (F₁ : J₁ ⥤ C) (F₂ : J₂ ⥤ C) := externalProductBifunctor J₁ J₂ C|>.obj (F₁, F₂) namespace ExternalProduct /-- Notation for `externalProduct`. Do `open scoped CategoryTheory.MonoidalCategory.ExternalProduct` to bring this notation in scope. -/ scoped infixr:80 " ⊠ " => externalProduct end ExternalProduct open scoped ExternalProduct variable (J₁ J₂ C) /-- When both diagrams have the same source category, composing the external product with the diagonal gives the pointwise functor tensor product. Note that `(externalProductCompDiagIso _ _).app (F₁, F₂) : Functor.diag J₁ ⋙ F₁ ⊠ F₂ ≅ F₁ ⊗ F₂` type checks. -/ @[simps!] def externalProductCompDiagIso : externalProductBifunctor J₁ J₁ C ⋙ (whiskeringLeft _ _ _|>.obj <| Functor.diag J₁) ≅ tensor (J₁ ⥤ C) := NatIso.ofComponents (fun _ ↦ NatIso.ofComponents (fun _ ↦ Iso.refl _) (by simp [tensorHom_def])) (fun _ ↦ by ext; simp [tensorHom_def]) /-- When `C` is braided, there is an isomorphism `Prod.swap _ _ ⋙ F₁ ⊠ F₂ ≅ F₂ ⊠ F₁`, natural in both `F₁` and `F₂`. Note that `(externalProductSwap _ _ _).app (F₁, F₂) : Prod.swap _ _ ⋙ F₁ ⊠ F₂ ≅ F₂ ⊠ F₁` type checks. -/ @[simps!] def externalProductSwap [BraidedCategory C] : externalProductBifunctor J₁ J₂ C ⋙ (whiskeringLeft _ _ _|>.obj <| Prod.swap _ _) ≅ Prod.swap _ _ ⋙ externalProductBifunctor J₂ J₁ C := NatIso.ofComponents (fun _ ↦ NatIso.ofComponents (fun _ ↦ β_ _ _) (by simp [whisker_exchange])) (fun _ ↦ by ext; simp [whisker_exchange]) /-- A version of `externalProductSwap` phrased in terms of the curried functors. -/ @[simps!] def externalProductFlip [BraidedCategory C] : (Functor.postcompose₂.obj <| flipFunctor _ _ _).obj (externalProductBifunctorCurried J₁ J₂ C) ≅ (externalProductBifunctorCurried J₂ J₁ C).flip := NatIso.ofComponents <| fun _ ↦ NatIso.ofComponents <| fun _ ↦ NatIso.ofComponents <| fun _ ↦ NatIso.ofComponents (fun _ ↦ β_ _ _) section Composition variable {J₁ J₂ C} {I₁ : Type u₃} {I₂ : Type u₄} [Category.{v₃} I₁] [Category.{v₄} I₂] /-- Composing `F₁ × F₂` with `G₁ ⊠ G₂` is isomorphic to `(F₁ ⋙ G₁) ⊠ (F₂ ⋙ G₂)`. -/ @[simps!] def prodCompExternalProduct (F₁ : I₁ ⥤ J₁) (G₁ : J₁ ⥤ C) (F₂ : I₂ ⥤ J₂) (G₂ : J₂ ⥤ C) : F₁.prod F₂ ⋙ G₁ ⊠ G₂ ≅ (F₁ ⋙ G₁) ⊠ (F₂ ⋙ G₂) := NatIso.ofComponents (fun _ ↦ Iso.refl _) end Composition end CategoryTheory.MonoidalCategory
DenselyOrdered.lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import Mathlib.Algebra.Order.Group.Unbundled.Basic import Mathlib.Algebra.Order.Monoid.Unbundled.OrderDual import Mathlib.Algebra.Order.Monoid.Unbundled.ExistsOfLE /-! # Lemmas about densely linearly ordered groups. -/ variable {α : Type*} section DenselyOrdered variable [Group α] [LinearOrder α] variable [MulLeftMono α] variable [DenselyOrdered α] {a b : α} @[to_additive] theorem le_of_forall_lt_one_mul_le (h : ∀ ε < 1, a * ε ≤ b) : a ≤ b := le_of_forall_one_lt_le_mul (α := αᵒᵈ) h @[to_additive] theorem le_of_forall_one_lt_div_le (h : ∀ ε : α, 1 < ε → a / ε ≤ b) : a ≤ b := le_of_forall_lt_one_mul_le fun ε ε1 => by simpa only [div_eq_mul_inv, inv_inv] using h ε⁻¹ (Left.one_lt_inv_iff.2 ε1) @[to_additive] theorem le_iff_forall_lt_one_mul_le : a ≤ b ↔ ∀ ε < 1, a * ε ≤ b := le_iff_forall_one_lt_le_mul (α := αᵒᵈ) end DenselyOrdered section DenselyOrdered @[to_additive] private lemma exists_lt_mul_left [Group α] [LT α] [DenselyOrdered α] [MulRightStrictMono α] {a b c : α} (hc : c < a * b) : ∃ a' < a, c < a' * b := by obtain ⟨a', hc', ha'⟩ := exists_between (div_lt_iff_lt_mul.2 hc) exact ⟨a', ha', div_lt_iff_lt_mul.1 hc'⟩ @[to_additive] private lemma exists_lt_mul_right [CommGroup α] [LT α] [DenselyOrdered α] [MulLeftStrictMono α] {a b c : α} (hc : c < a * b) : ∃ b' < b, c < a * b' := by obtain ⟨a', hc', ha'⟩ := exists_between (div_lt_iff_lt_mul'.2 hc) exact ⟨a', ha', div_lt_iff_lt_mul'.1 hc'⟩ @[to_additive] private lemma exists_mul_left_lt [Group α] [LT α] [DenselyOrdered α] [MulRightStrictMono α] {a b c : α} (hc : a * b < c) : ∃ a' > a, a' * b < c := by obtain ⟨a', ha', hc'⟩ := exists_between (lt_div_iff_mul_lt.2 hc) exact ⟨a', ha', lt_div_iff_mul_lt.1 hc'⟩ @[to_additive] private lemma exists_mul_right_lt [CommGroup α] [LT α] [DenselyOrdered α] [MulLeftStrictMono α] {a b c : α} (hc : a * b < c) : ∃ b' > b, a * b' < c := by obtain ⟨a', ha', hc'⟩ := exists_between (lt_div_iff_mul_lt'.2 hc) exact ⟨a', ha', lt_div_iff_mul_lt'.1 hc'⟩ @[to_additive] lemma le_mul_of_forall_lt [CommGroup α] [LinearOrder α] [MulLeftMono α] [DenselyOrdered α] {a b c : α} (h : ∀ a' > a, ∀ b' > b, c ≤ a' * b') : c ≤ a * b := by refine le_of_forall_gt_imp_ge_of_dense fun d hd ↦ ?_ obtain ⟨a', ha', hd⟩ := exists_mul_left_lt hd obtain ⟨b', hb', hd⟩ := exists_mul_right_lt hd exact (h a' ha' b' hb').trans hd.le @[to_additive] lemma mul_le_of_forall_lt [CommGroup α] [LinearOrder α] [MulLeftMono α] [DenselyOrdered α] {a b c : α} (h : ∀ a' < a, ∀ b' < b, a' * b' ≤ c) : a * b ≤ c := by refine le_of_forall_lt_imp_le_of_dense fun d hd ↦ ?_ obtain ⟨a', ha', hd⟩ := exists_lt_mul_left hd obtain ⟨b', hb', hd⟩ := exists_lt_mul_right hd exact hd.le.trans (h a' ha' b' hb') end DenselyOrdered
Within.lean
/- Copyright (c) 2024 Geoffrey Irving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Geoffrey Irving -/ import Mathlib.Analysis.Analytic.Constructions import Mathlib.Analysis.Analytic.ChangeOrigin /-! # Properties of analyticity restricted to a set From `Mathlib/Analysis/Analytic/Basic.lean`, we have the definitions 1. `AnalyticWithinAt 𝕜 f s x` means a power series at `x` converges to `f` on `𝓝[insert x s] x`. 2. `AnalyticOn 𝕜 f s t` means `∀ x ∈ t, AnalyticWithinAt 𝕜 f s x`. This means there exists an extension of `f` which is analytic and agrees with `f` on `s ∪ {x}`, but `f` is allowed to be arbitrary elsewhere. Here we prove basic properties of these definitions. Where convenient we assume completeness of the ambient space, which allows us to relate `AnalyticWithinAt` to analyticity of a local extension. -/ noncomputable section open Topology Filter ENNReal open Set Filter variable {𝕜 : Type*} [NontriviallyNormedField 𝕜] variable {E F : Type*} [NormedAddCommGroup E] [NormedSpace 𝕜 E] [NormedAddCommGroup F] [NormedSpace 𝕜 F] /-! ### Basic properties -/ /-- `AnalyticWithinAt` is trivial if `{x} ∈ 𝓝[s] x` -/ lemma analyticWithinAt_of_singleton_mem {f : E → F} {s : Set E} {x : E} (h : {x} ∈ 𝓝[s] x) : AnalyticWithinAt 𝕜 f s x := by rcases mem_nhdsWithin.mp h with ⟨t, ot, xt, st⟩ rcases Metric.mem_nhds_iff.mp (ot.mem_nhds xt) with ⟨r, r0, rt⟩ exact ⟨constFormalMultilinearSeries 𝕜 E (f x), .ofReal r, { r_le := by simp only [FormalMultilinearSeries.constFormalMultilinearSeries_radius, le_top] r_pos := by positivity hasSum := by intro y ys yr simp only [subset_singleton_iff, mem_inter_iff, and_imp] at st simp only [mem_insert_iff, add_eq_left] at ys have : x + y = x := by rcases ys with rfl | ys · simp · exact st (x + y) (rt (by simpa using yr)) ys simp only [this] apply (hasFPowerSeriesOnBall_const (e := 0)).hasSum simp only [Metric.emetric_ball_top, mem_univ] }⟩ /-- If `f` is `AnalyticOn` near each point in a set, it is `AnalyticOn` the set -/ lemma analyticOn_of_locally_analyticOn {f : E → F} {s : Set E} (h : ∀ x ∈ s, ∃ u, IsOpen u ∧ x ∈ u ∧ AnalyticOn 𝕜 f (s ∩ u)) : AnalyticOn 𝕜 f s := by intro x m rcases h x m with ⟨u, ou, xu, fu⟩ rcases Metric.mem_nhds_iff.mp (ou.mem_nhds xu) with ⟨r, r0, ru⟩ rcases fu x ⟨m, xu⟩ with ⟨p, t, fp⟩ exact ⟨p, min (.ofReal r) t, { r_pos := lt_min (by positivity) fp.r_pos r_le := min_le_of_right_le fp.r_le hasSum := by intro y ys yr simp only [EMetric.mem_ball, lt_min_iff, edist_lt_ofReal, dist_zero_right] at yr apply fp.hasSum · simp only [mem_insert_iff, add_eq_left] at ys rcases ys with rfl | ys · simp · simp only [mem_insert_iff, add_eq_left, mem_inter_iff, ys, true_and] apply Or.inr (ru ?_) simp only [Metric.mem_ball, dist_self_add_left, yr] · simp only [EMetric.mem_ball, yr] }⟩ /-- On open sets, `AnalyticOnNhd` and `AnalyticOn` coincide -/ lemma IsOpen.analyticOn_iff_analyticOnNhd {f : E → F} {s : Set E} (hs : IsOpen s) : AnalyticOn 𝕜 f s ↔ AnalyticOnNhd 𝕜 f s := by refine ⟨?_, AnalyticOnNhd.analyticOn⟩ intro hf x m rcases Metric.mem_nhds_iff.mp (hs.mem_nhds m) with ⟨r, r0, rs⟩ rcases hf x m with ⟨p, t, fp⟩ exact ⟨p, min (.ofReal r) t, { r_pos := lt_min (by positivity) fp.r_pos r_le := min_le_of_right_le fp.r_le hasSum := by intro y ym simp only [EMetric.mem_ball, lt_min_iff, edist_lt_ofReal, dist_zero_right] at ym refine fp.hasSum ?_ ym.2 apply mem_insert_of_mem apply rs simp only [Metric.mem_ball, dist_self_add_left, ym.1] }⟩ /-! ### Equivalence to analyticity of a local extension We show that `HasFPowerSeriesWithinOnBall`, `HasFPowerSeriesWithinAt`, and `AnalyticWithinAt` are equivalent to the existence of a local extension with full analyticity. We do not yet show a result for `AnalyticOn`, as this requires a bit more work to show that local extensions can be stitched together. -/ set_option linter.style.multiGoal false in /-- `f` has power series `p` at `x` iff some local extension of `f` has that series -/ lemma hasFPowerSeriesWithinOnBall_iff_exists_hasFPowerSeriesOnBall [CompleteSpace F] {f : E → F} {p : FormalMultilinearSeries 𝕜 E F} {s : Set E} {x : E} {r : ℝ≥0∞} : HasFPowerSeriesWithinOnBall f p s x r ↔ ∃ g, EqOn f g (insert x s ∩ EMetric.ball x r) ∧ HasFPowerSeriesOnBall g p x r := by constructor · intro h refine ⟨fun y ↦ p.sum (y - x), ?_, ?_⟩ · intro y ⟨ys,yb⟩ simp only [EMetric.mem_ball, edist_eq_enorm_sub] at yb have e0 := p.hasSum (x := y - x) ?_ have e1 := (h.hasSum (y := y - x) ?_ ?_) · simp only [add_sub_cancel] at e1 exact e1.unique e0 · simpa only [add_sub_cancel] · simpa only [EMetric.mem_ball, edist_zero_eq_enorm] · simp only [EMetric.mem_ball, edist_zero_eq_enorm] exact lt_of_lt_of_le yb h.r_le · refine ⟨h.r_le, h.r_pos, ?_⟩ intro y lt simp only [add_sub_cancel_left] apply p.hasSum simp only [EMetric.mem_ball] at lt ⊢ exact lt_of_lt_of_le lt h.r_le · intro ⟨g, hfg, hg⟩ refine ⟨hg.r_le, hg.r_pos, ?_⟩ intro y ys lt rw [hfg] · exact hg.hasSum lt · refine ⟨ys, ?_⟩ simpa only [EMetric.mem_ball, edist_eq_enorm_sub, add_sub_cancel_left, sub_zero] using lt /-- `f` has power series `p` at `x` iff some local extension of `f` has that series -/ lemma hasFPowerSeriesWithinAt_iff_exists_hasFPowerSeriesAt [CompleteSpace F] {f : E → F} {p : FormalMultilinearSeries 𝕜 E F} {s : Set E} {x : E} : HasFPowerSeriesWithinAt f p s x ↔ ∃ g, f =ᶠ[𝓝[insert x s] x] g ∧ HasFPowerSeriesAt g p x := by constructor · intro ⟨r, h⟩ rcases hasFPowerSeriesWithinOnBall_iff_exists_hasFPowerSeriesOnBall.mp h with ⟨g, e, h⟩ refine ⟨g, ?_, ⟨r, h⟩⟩ refine Filter.eventuallyEq_iff_exists_mem.mpr ⟨_, ?_, e⟩ exact inter_mem_nhdsWithin _ (EMetric.ball_mem_nhds _ h.r_pos) · intro ⟨g, hfg, ⟨r, hg⟩⟩ simp only [eventuallyEq_nhdsWithin_iff, Metric.eventually_nhds_iff] at hfg rcases hfg with ⟨e, e0, hfg⟩ refine ⟨min r (.ofReal e), ?_⟩ refine hasFPowerSeriesWithinOnBall_iff_exists_hasFPowerSeriesOnBall.mpr ⟨g, ?_, ?_⟩ · intro y ⟨ys, xy⟩ refine hfg ?_ ys simp only [EMetric.mem_ball, lt_min_iff, edist_lt_ofReal] at xy exact xy.2 · exact hg.mono (lt_min hg.r_pos (by positivity)) (min_le_left _ _) /-- `f` is analytic within `s` at `x` iff some local extension of `f` is analytic at `x` -/ lemma analyticWithinAt_iff_exists_analyticAt [CompleteSpace F] {f : E → F} {s : Set E} {x : E} : AnalyticWithinAt 𝕜 f s x ↔ ∃ g, f =ᶠ[𝓝[insert x s] x] g ∧ AnalyticAt 𝕜 g x := by simp only [AnalyticWithinAt, AnalyticAt, hasFPowerSeriesWithinAt_iff_exists_hasFPowerSeriesAt] tauto /-- `f` is analytic within `s` at `x` iff some local extension of `f` is analytic at `x`. In this version, we make sure that the extension coincides with `f` on all of `insert x s`. -/ lemma analyticWithinAt_iff_exists_analyticAt' [CompleteSpace F] {f : E → F} {s : Set E} {x : E} : AnalyticWithinAt 𝕜 f s x ↔ ∃ g, f x = g x ∧ EqOn f g (insert x s) ∧ AnalyticAt 𝕜 g x := by classical simp only [analyticWithinAt_iff_exists_analyticAt] refine ⟨?_, ?_⟩ · rintro ⟨g, hf, hg⟩ rcases mem_nhdsWithin.1 hf with ⟨u, u_open, xu, hu⟩ let g' := Set.piecewise u g f refine ⟨g', ?_, ?_, ?_⟩ · have : x ∈ u ∩ insert x s := ⟨xu, by simp⟩ simpa [g', xu, this] using hu this · intro y hy by_cases h'y : y ∈ u · have : y ∈ u ∩ insert x s := ⟨h'y, hy⟩ simpa [g', h'y, this] using hu this · simp [g', h'y] · apply hg.congr filter_upwards [u_open.mem_nhds xu] with y hy using by simp [g', hy] · rintro ⟨g, -, hf, hg⟩ exact ⟨g, by filter_upwards [self_mem_nhdsWithin] using hf, hg⟩ alias ⟨AnalyticWithinAt.exists_analyticAt, _⟩ := analyticWithinAt_iff_exists_analyticAt' lemma AnalyticWithinAt.exists_mem_nhdsWithin_analyticOn [CompleteSpace F] {f : E → F} {s : Set E} {x : E} (h : AnalyticWithinAt 𝕜 f s x) : ∃ u ∈ 𝓝[insert x s] x, AnalyticOn 𝕜 f u := by obtain ⟨g, -, h'g, hg⟩ : ∃ g, f x = g x ∧ EqOn f g (insert x s) ∧ AnalyticAt 𝕜 g x := h.exists_analyticAt let u := insert x s ∩ {y | AnalyticAt 𝕜 g y} refine ⟨u, ?_, ?_⟩ · exact inter_mem_nhdsWithin _ ((isOpen_analyticAt 𝕜 g).mem_nhds hg) · intro y hy have : AnalyticWithinAt 𝕜 g u y := hy.2.analyticWithinAt exact this.congr (h'g.mono (inter_subset_left)) (h'g (inter_subset_left hy))
Sheafification.lean
/- Copyright (c) 2023 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Adjunction.Unique import Mathlib.CategoryTheory.Adjunction.Reflective import Mathlib.CategoryTheory.Sites.Sheaf import Mathlib.CategoryTheory.Limits.Preserves.Finite /-! # Sheafification Given a site `(C, J)` we define a typeclass `HasSheafify J A` saying that the inclusion functor from `A`-valued sheaves on `C` to presheaves admits a left exact left adjoint (sheafification). Note: to access the `HasSheafify` instance for suitable concrete categories, import the file `Mathlib/CategoryTheory/Sites/LeftExact.lean`. -/ universe v₁ v₂ u₁ u₂ namespace CategoryTheory open Limits variable {C : Type u₁} [Category.{v₁} C] (J : GrothendieckTopology C) variable (A : Type u₂) [Category.{v₂} A] /-- A proposition saying that the inclusion functor from sheaves to presheaves admits a left adjoint. -/ abbrev HasWeakSheafify : Prop := (sheafToPresheaf J A).IsRightAdjoint /-- `HasSheafify` means that the inclusion functor from sheaves to presheaves admits a left exact left adjoint (sheafification). Given a finite limit preserving functor `F : (Cᵒᵖ ⥤ A) ⥤ Sheaf J A` and an adjunction `adj : F ⊣ sheafToPresheaf J A`, use `HasSheafify.mk'` to construct a `HasSheafify` instance. -/ class HasSheafify : Prop where isRightAdjoint : HasWeakSheafify J A isLeftExact : PreservesFiniteLimits ((sheafToPresheaf J A).leftAdjoint) instance [HasSheafify J A] : HasWeakSheafify J A := HasSheafify.isRightAdjoint noncomputable section instance [HasSheafify J A] : PreservesFiniteLimits ((sheafToPresheaf J A).leftAdjoint) := HasSheafify.isLeftExact theorem HasSheafify.mk' {F : (Cᵒᵖ ⥤ A) ⥤ Sheaf J A} (adj : F ⊣ sheafToPresheaf J A) [PreservesFiniteLimits F] : HasSheafify J A where isRightAdjoint := ⟨F, ⟨adj⟩⟩ isLeftExact := ⟨by have : (sheafToPresheaf J A).IsRightAdjoint := ⟨_, ⟨adj⟩⟩ exact fun _ _ _ ↦ preservesLimitsOfShape_of_natIso (adj.leftAdjointUniq (Adjunction.ofIsRightAdjoint (sheafToPresheaf J A)))⟩ /-- The sheafification functor, left adjoint to the inclusion. -/ def presheafToSheaf [HasWeakSheafify J A] : (Cᵒᵖ ⥤ A) ⥤ Sheaf J A := (sheafToPresheaf J A).leftAdjoint instance [HasSheafify J A] : PreservesFiniteLimits (presheafToSheaf J A) := HasSheafify.isLeftExact /-- The sheafification-inclusion adjunction. -/ def sheafificationAdjunction [HasWeakSheafify J A] : presheafToSheaf J A ⊣ sheafToPresheaf J A := Adjunction.ofIsRightAdjoint _ instance [HasWeakSheafify J A] : (presheafToSheaf J A).IsLeftAdjoint := ⟨_, ⟨sheafificationAdjunction J A⟩⟩ instance [HasWeakSheafify J A] : Reflective (sheafToPresheaf J A) where L := presheafToSheaf J A adj := sheafificationAdjunction _ _ instance [HasSheafify J A] : PreservesFiniteLimits (reflector (sheafToPresheaf J A)) := inferInstanceAs (PreservesFiniteLimits (presheafToSheaf _ _)) end variable {D : Type*} [Category D] [HasWeakSheafify J D] /-- The sheafification of a presheaf `P`. -/ noncomputable abbrev sheafify (P : Cᵒᵖ ⥤ D) : Cᵒᵖ ⥤ D := presheafToSheaf J D |>.obj P |>.val /-- The canonical map from `P` to its sheafification. -/ noncomputable abbrev toSheafify (P : Cᵒᵖ ⥤ D) : P ⟶ sheafify J P := sheafificationAdjunction J D |>.unit.app P @[simp] theorem sheafificationAdjunction_unit_app (P : Cᵒᵖ ⥤ D) : (sheafificationAdjunction J D).unit.app P = toSheafify J P := rfl /-- The canonical map on sheafifications induced by a morphism. -/ noncomputable abbrev sheafifyMap {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : sheafify J P ⟶ sheafify J Q := presheafToSheaf J D |>.map η |>.val @[simp] theorem sheafifyMap_id (P : Cᵒᵖ ⥤ D) : sheafifyMap J (𝟙 P) = 𝟙 (sheafify J P) := by simp [sheafifyMap, sheafify] @[simp] theorem sheafifyMap_comp {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) : sheafifyMap J (η ≫ γ) = sheafifyMap J η ≫ sheafifyMap J γ := by simp [sheafifyMap, sheafify] @[reassoc (attr := simp)] theorem toSheafify_naturality {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : η ≫ toSheafify J _ = toSheafify J _ ≫ sheafifyMap J η := sheafificationAdjunction J D |>.unit.naturality η variable (D) /-- The sheafification of a presheaf `P`, as a functor. -/ noncomputable abbrev sheafification : (Cᵒᵖ ⥤ D) ⥤ Cᵒᵖ ⥤ D := presheafToSheaf J D ⋙ sheafToPresheaf J D theorem sheafification_obj (P : Cᵒᵖ ⥤ D) : (sheafification J D).obj P = sheafify J P := rfl theorem sheafification_map {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) : (sheafification J D).map η = sheafifyMap J η := rfl /-- The canonical map from `P` to its sheafification, as a natural transformation. -/ noncomputable abbrev toSheafification : 𝟭 _ ⟶ sheafification J D := sheafificationAdjunction J D |>.unit theorem toSheafification_app (P : Cᵒᵖ ⥤ D) : (toSheafification J D).app P = toSheafify J P := rfl variable {D} theorem isIso_toSheafify {P : Cᵒᵖ ⥤ D} (hP : Presheaf.IsSheaf J P) : IsIso (toSheafify J P) := by refine ⟨(sheafificationAdjunction J D |>.counit.app ⟨P, hP⟩).val, ?_, ?_⟩ · change _ = (𝟙 (sheafToPresheaf J D ⋙ 𝟭 (Cᵒᵖ ⥤ D)) :).app ⟨P, hP⟩ rw [← sheafificationAdjunction J D |>.right_triangle] rfl · change (sheafToPresheaf _ _).map _ ≫ _ = _ change _ ≫ (sheafificationAdjunction J D).unit.app ((sheafToPresheaf J D).obj ⟨P, hP⟩) = _ rw [← (sheafificationAdjunction J D).inv_counit_map (X := ⟨P, hP⟩)] simp /-- If `P` is a sheaf, then `P` is isomorphic to `sheafify J P`. -/ noncomputable def isoSheafify {P : Cᵒᵖ ⥤ D} (hP : Presheaf.IsSheaf J P) : P ≅ sheafify J P := letI := isIso_toSheafify J hP asIso (toSheafify J P) @[simp] theorem isoSheafify_hom {P : Cᵒᵖ ⥤ D} (hP : Presheaf.IsSheaf J P) : (isoSheafify J hP).hom = toSheafify J P := rfl /-- Given a sheaf `Q` and a morphism `P ⟶ Q`, construct a morphism from `sheafify J P` to `Q`. -/ noncomputable def sheafifyLift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) : sheafify J P ⟶ Q := (sheafificationAdjunction J D).homEquiv P ⟨Q, hQ⟩ |>.symm η |>.val @[simp] theorem sheafificationAdjunction_counit_app_val (P : Sheaf J D) : ((sheafificationAdjunction J D).counit.app P).val = sheafifyLift J (𝟙 P.val) P.cond := by unfold sheafifyLift rw [Adjunction.homEquiv_counit] simp @[reassoc (attr := simp)] theorem toSheafify_sheafifyLift {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) : toSheafify J P ≫ sheafifyLift J η hQ = η := by rw [toSheafify, sheafifyLift, Adjunction.homEquiv_counit] change _ ≫ (sheafToPresheaf J D).map _ ≫ _ = _ simp only [Adjunction.unit_naturality_assoc] change _ ≫ (sheafificationAdjunction J D).unit.app ((sheafToPresheaf J D).obj ⟨Q, hQ⟩) ≫ _ = _ change _ ≫ _ ≫ (sheafToPresheaf J D).map _ = _ rw [sheafificationAdjunction J D |>.right_triangle_components (Y := ⟨Q, hQ⟩)] simp theorem sheafifyLift_unique {P Q : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) (γ : sheafify J P ⟶ Q) : toSheafify J P ≫ γ = η → γ = sheafifyLift J η hQ := by intro h rw [toSheafify] at h rw [sheafifyLift] let γ' : (presheafToSheaf J D).obj P ⟶ ⟨Q, hQ⟩ := ⟨γ⟩ change γ'.val = _ rw [← Sheaf.Hom.ext_iff, ← Adjunction.homEquiv_apply_eq, Adjunction.homEquiv_unit] exact h @[simp] theorem isoSheafify_inv {P : Cᵒᵖ ⥤ D} (hP : Presheaf.IsSheaf J P) : (isoSheafify J hP).inv = sheafifyLift J (𝟙 _) hP := by apply sheafifyLift_unique simp [Iso.comp_inv_eq] theorem sheafify_hom_ext {P Q : Cᵒᵖ ⥤ D} (η γ : sheafify J P ⟶ Q) (hQ : Presheaf.IsSheaf J Q) (h : toSheafify J P ≫ η = toSheafify J P ≫ γ) : η = γ := by rw [sheafifyLift_unique J _ hQ _ h, ← h] exact (sheafifyLift_unique J _ hQ _ h.symm).symm @[reassoc (attr := simp)] theorem sheafifyMap_sheafifyLift {P Q R : Cᵒᵖ ⥤ D} (η : P ⟶ Q) (γ : Q ⟶ R) (hR : Presheaf.IsSheaf J R) : sheafifyMap J η ≫ sheafifyLift J γ hR = sheafifyLift J (η ≫ γ) hR := by apply sheafifyLift_unique rw [← Category.assoc, ← toSheafify_naturality, Category.assoc, toSheafify_sheafifyLift] variable {J} /-- A sheaf `P` is isomorphic to its own sheafification. -/ @[simps] noncomputable def sheafificationIso (P : Sheaf J D) : P ≅ (presheafToSheaf J D).obj P.val where hom := ⟨(isoSheafify J P.2).hom⟩ inv := ⟨(isoSheafify J P.2).inv⟩ hom_inv_id := by ext1 apply (isoSheafify J P.2).hom_inv_id inv_hom_id := by ext1 apply (isoSheafify J P.2).inv_hom_id instance isIso_sheafificationAdjunction_counit (P : Sheaf J D) : IsIso ((sheafificationAdjunction J D).counit.app P) := isIso_of_fully_faithful (sheafToPresheaf J D) _ instance sheafification_reflective : IsIso (sheafificationAdjunction J D).counit := NatIso.isIso_of_isIso_app _ variable (J D) /-- The natural isomorphism `𝟭 (Sheaf J D) ≅ sheafToPresheaf J D ⋙ presheafToSheaf J D`. -/ @[simps!] noncomputable def sheafificationNatIso : 𝟭 (Sheaf J D) ≅ sheafToPresheaf J D ⋙ presheafToSheaf J D := NatIso.ofComponents (fun P => sheafificationIso P) (by cat_disch) end CategoryTheory
Lattice.lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Johannes Hölzl, Mario Carneiro -/ import Mathlib.Logic.Pairwise import Mathlib.Data.Set.BooleanAlgebra /-! # The set lattice This file is a collection of results on the complete atomic boolean algebra structure of `Set α`. Notation for the complete lattice operations can be found in `Mathlib/Order/SetNotation.lean`. ## Main declarations * `Set.sInter_eq_biInter`, `Set.sUnion_eq_biInter`: Shows that `⋂₀ s = ⋂ x ∈ s, x` and `⋃₀ s = ⋃ x ∈ s, x`. * `Set.completeAtomicBooleanAlgebra`: `Set α` is a `CompleteAtomicBooleanAlgebra` with `≤ = ⊆`, `< = ⊂`, `⊓ = ∩`, `⊔ = ∪`, `⨅ = ⋂`, `⨆ = ⋃` and `\` as the set difference. See `Set.instBooleanAlgebra`. * `Set.unionEqSigmaOfDisjoint`: Equivalence between `⋃ i, t i` and `Σ i, t i`, where `t` is an indexed family of disjoint sets. ## Naming convention In lemma names, * `⋃ i, s i` is called `iUnion` * `⋂ i, s i` is called `iInter` * `⋃ i j, s i j` is called `iUnion₂`. This is an `iUnion` inside an `iUnion`. * `⋂ i j, s i j` is called `iInter₂`. This is an `iInter` inside an `iInter`. * `⋃ i ∈ s, t i` is called `biUnion` for "bounded `iUnion`". This is the special case of `iUnion₂` where `j : i ∈ s`. * `⋂ i ∈ s, t i` is called `biInter` for "bounded `iInter`". This is the special case of `iInter₂` where `j : i ∈ s`. ## Notation * `⋃`: `Set.iUnion` * `⋂`: `Set.iInter` * `⋃₀`: `Set.sUnion` * `⋂₀`: `Set.sInter` -/ open Function Set universe u variable {α β γ δ : Type*} {ι ι' ι₂ : Sort*} {κ κ₁ κ₂ : ι → Sort*} {κ' : ι' → Sort*} namespace Set /-! ### Complete lattice and complete Boolean algebra instances -/ theorem mem_iUnion₂ {x : γ} {s : ∀ i, κ i → Set γ} : (x ∈ ⋃ (i) (j), s i j) ↔ ∃ i j, x ∈ s i j := by simp_rw [mem_iUnion] theorem mem_iInter₂ {x : γ} {s : ∀ i, κ i → Set γ} : (x ∈ ⋂ (i) (j), s i j) ↔ ∀ i j, x ∈ s i j := by simp_rw [mem_iInter] theorem mem_iUnion_of_mem {s : ι → Set α} {a : α} (i : ι) (ha : a ∈ s i) : a ∈ ⋃ i, s i := mem_iUnion.2 ⟨i, ha⟩ theorem mem_iUnion₂_of_mem {s : ∀ i, κ i → Set α} {a : α} {i : ι} (j : κ i) (ha : a ∈ s i j) : a ∈ ⋃ (i) (j), s i j := mem_iUnion₂.2 ⟨i, j, ha⟩ theorem mem_iInter_of_mem {s : ι → Set α} {a : α} (h : ∀ i, a ∈ s i) : a ∈ ⋂ i, s i := mem_iInter.2 h theorem mem_iInter₂_of_mem {s : ∀ i, κ i → Set α} {a : α} (h : ∀ i j, a ∈ s i j) : a ∈ ⋂ (i) (j), s i j := mem_iInter₂.2 h /-! ### Union and intersection over an indexed family of sets -/ @[congr] theorem iUnion_congr_Prop {p q : Prop} {f₁ : p → Set α} {f₂ : q → Set α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : iUnion f₁ = iUnion f₂ := iSup_congr_Prop pq f @[congr] theorem iInter_congr_Prop {p q : Prop} {f₁ : p → Set α} {f₂ : q → Set α} (pq : p ↔ q) (f : ∀ x, f₁ (pq.mpr x) = f₂ x) : iInter f₁ = iInter f₂ := iInf_congr_Prop pq f theorem iUnion_plift_up (f : PLift ι → Set α) : ⋃ i, f (PLift.up i) = ⋃ i, f i := iSup_plift_up _ theorem iUnion_plift_down (f : ι → Set α) : ⋃ i, f (PLift.down i) = ⋃ i, f i := iSup_plift_down _ theorem iInter_plift_up (f : PLift ι → Set α) : ⋂ i, f (PLift.up i) = ⋂ i, f i := iInf_plift_up _ theorem iInter_plift_down (f : ι → Set α) : ⋂ i, f (PLift.down i) = ⋂ i, f i := iInf_plift_down _ theorem iUnion_eq_if {p : Prop} [Decidable p] (s : Set α) : ⋃ _ : p, s = if p then s else ∅ := iSup_eq_if _ theorem iUnion_eq_dif {p : Prop} [Decidable p] (s : p → Set α) : ⋃ h : p, s h = if h : p then s h else ∅ := iSup_eq_dif _ theorem iInter_eq_if {p : Prop} [Decidable p] (s : Set α) : ⋂ _ : p, s = if p then s else univ := iInf_eq_if _ theorem iInf_eq_dif {p : Prop} [Decidable p] (s : p → Set α) : ⋂ h : p, s h = if h : p then s h else univ := _root_.iInf_eq_dif _ theorem exists_set_mem_of_union_eq_top {ι : Type*} (t : Set ι) (s : ι → Set β) (w : ⋃ i ∈ t, s i = ⊤) (x : β) : ∃ i ∈ t, x ∈ s i := by have p : x ∈ ⊤ := Set.mem_univ x rw [← w, Set.mem_iUnion] at p simpa using p theorem nonempty_of_union_eq_top_of_nonempty {ι : Type*} (t : Set ι) (s : ι → Set α) (H : Nonempty α) (w : ⋃ i ∈ t, s i = ⊤) : t.Nonempty := by obtain ⟨x, m, -⟩ := exists_set_mem_of_union_eq_top t s w H.some exact ⟨x, m⟩ theorem nonempty_of_nonempty_iUnion {s : ι → Set α} (h_Union : (⋃ i, s i).Nonempty) : Nonempty ι := by obtain ⟨x, hx⟩ := h_Union exact ⟨Classical.choose <| mem_iUnion.mp hx⟩ theorem nonempty_of_nonempty_iUnion_eq_univ {s : ι → Set α} [Nonempty α] (h_Union : ⋃ i, s i = univ) : Nonempty ι := nonempty_of_nonempty_iUnion (s := s) (by simpa only [h_Union] using univ_nonempty) theorem setOf_exists (p : ι → β → Prop) : { x | ∃ i, p i x } = ⋃ i, { x | p i x } := ext fun _ => mem_iUnion.symm theorem setOf_forall (p : ι → β → Prop) : { x | ∀ i, p i x } = ⋂ i, { x | p i x } := ext fun _ => mem_iInter.symm theorem iUnion_subset {s : ι → Set α} {t : Set α} (h : ∀ i, s i ⊆ t) : ⋃ i, s i ⊆ t := iSup_le h theorem iUnion₂_subset {s : ∀ i, κ i → Set α} {t : Set α} (h : ∀ i j, s i j ⊆ t) : ⋃ (i) (j), s i j ⊆ t := iUnion_subset fun x => iUnion_subset (h x) theorem subset_iInter {t : Set β} {s : ι → Set β} (h : ∀ i, t ⊆ s i) : t ⊆ ⋂ i, s i := le_iInf h theorem subset_iInter₂ {s : Set α} {t : ∀ i, κ i → Set α} (h : ∀ i j, s ⊆ t i j) : s ⊆ ⋂ (i) (j), t i j := subset_iInter fun x => subset_iInter <| h x @[simp] theorem iUnion_subset_iff {s : ι → Set α} {t : Set α} : ⋃ i, s i ⊆ t ↔ ∀ i, s i ⊆ t := ⟨fun h _ => Subset.trans (le_iSup s _) h, iUnion_subset⟩ theorem iUnion₂_subset_iff {s : ∀ i, κ i → Set α} {t : Set α} : ⋃ (i) (j), s i j ⊆ t ↔ ∀ i j, s i j ⊆ t := by simp_rw [iUnion_subset_iff] @[simp] theorem subset_iInter_iff {s : Set α} {t : ι → Set α} : (s ⊆ ⋂ i, t i) ↔ ∀ i, s ⊆ t i := le_iInf_iff theorem subset_iInter₂_iff {s : Set α} {t : ∀ i, κ i → Set α} : (s ⊆ ⋂ (i) (j), t i j) ↔ ∀ i j, s ⊆ t i j := by simp_rw [subset_iInter_iff] theorem subset_iUnion : ∀ (s : ι → Set β) (i : ι), s i ⊆ ⋃ i, s i := le_iSup theorem iInter_subset : ∀ (s : ι → Set β) (i : ι), ⋂ i, s i ⊆ s i := iInf_le lemma iInter_subset_iUnion [Nonempty ι] {s : ι → Set α} : ⋂ i, s i ⊆ ⋃ i, s i := iInf_le_iSup theorem subset_iUnion₂ {s : ∀ i, κ i → Set α} (i : ι) (j : κ i) : s i j ⊆ ⋃ (i') (j'), s i' j' := le_iSup₂ i j theorem iInter₂_subset {s : ∀ i, κ i → Set α} (i : ι) (j : κ i) : ⋂ (i) (j), s i j ⊆ s i j := iInf₂_le i j /-- This rather trivial consequence of `subset_iUnion`is convenient with `apply`, and has `i` explicit for this purpose. -/ theorem subset_iUnion_of_subset {s : Set α} {t : ι → Set α} (i : ι) (h : s ⊆ t i) : s ⊆ ⋃ i, t i := le_iSup_of_le i h /-- This rather trivial consequence of `iInter_subset`is convenient with `apply`, and has `i` explicit for this purpose. -/ theorem iInter_subset_of_subset {s : ι → Set α} {t : Set α} (i : ι) (h : s i ⊆ t) : ⋂ i, s i ⊆ t := iInf_le_of_le i h /-- This rather trivial consequence of `subset_iUnion₂` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ theorem subset_iUnion₂_of_subset {s : Set α} {t : ∀ i, κ i → Set α} (i : ι) (j : κ i) (h : s ⊆ t i j) : s ⊆ ⋃ (i) (j), t i j := le_iSup₂_of_le i j h /-- This rather trivial consequence of `iInter₂_subset` is convenient with `apply`, and has `i` and `j` explicit for this purpose. -/ theorem iInter₂_subset_of_subset {s : ∀ i, κ i → Set α} {t : Set α} (i : ι) (j : κ i) (h : s i j ⊆ t) : ⋂ (i) (j), s i j ⊆ t := iInf₂_le_of_le i j h theorem iUnion_mono {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : ⋃ i, s i ⊆ ⋃ i, t i := iSup_mono h @[gcongr] theorem iUnion_mono'' {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : iUnion s ⊆ iUnion t := iSup_mono h theorem iUnion₂_mono {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j ⊆ t i j) : ⋃ (i) (j), s i j ⊆ ⋃ (i) (j), t i j := iSup₂_mono h theorem iInter_mono {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : ⋂ i, s i ⊆ ⋂ i, t i := iInf_mono h @[gcongr] theorem iInter_mono'' {s t : ι → Set α} (h : ∀ i, s i ⊆ t i) : iInter s ⊆ iInter t := iInf_mono h theorem iInter₂_mono {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j ⊆ t i j) : ⋂ (i) (j), s i j ⊆ ⋂ (i) (j), t i j := iInf₂_mono h theorem iUnion_mono' {s : ι → Set α} {t : ι₂ → Set α} (h : ∀ i, ∃ j, s i ⊆ t j) : ⋃ i, s i ⊆ ⋃ i, t i := iSup_mono' h theorem iUnion₂_mono' {s : ∀ i, κ i → Set α} {t : ∀ i', κ' i' → Set α} (h : ∀ i j, ∃ i' j', s i j ⊆ t i' j') : ⋃ (i) (j), s i j ⊆ ⋃ (i') (j'), t i' j' := iSup₂_mono' h theorem iInter_mono' {s : ι → Set α} {t : ι' → Set α} (h : ∀ j, ∃ i, s i ⊆ t j) : ⋂ i, s i ⊆ ⋂ j, t j := Set.subset_iInter fun j => let ⟨i, hi⟩ := h j iInter_subset_of_subset i hi theorem iInter₂_mono' {s : ∀ i, κ i → Set α} {t : ∀ i', κ' i' → Set α} (h : ∀ i' j', ∃ i j, s i j ⊆ t i' j') : ⋂ (i) (j), s i j ⊆ ⋂ (i') (j'), t i' j' := subset_iInter₂_iff.2 fun i' j' => let ⟨_, _, hst⟩ := h i' j' (iInter₂_subset _ _).trans hst theorem iUnion₂_subset_iUnion (κ : ι → Sort*) (s : ι → Set α) : ⋃ (i) (_ : κ i), s i ⊆ ⋃ i, s i := iUnion_mono fun _ => iUnion_subset fun _ => Subset.rfl theorem iInter_subset_iInter₂ (κ : ι → Sort*) (s : ι → Set α) : ⋂ i, s i ⊆ ⋂ (i) (_ : κ i), s i := iInter_mono fun _ => subset_iInter fun _ => Subset.rfl theorem iUnion_setOf (P : ι → α → Prop) : ⋃ i, { x : α | P i x } = { x : α | ∃ i, P i x } := by ext exact mem_iUnion theorem iInter_setOf (P : ι → α → Prop) : ⋂ i, { x : α | P i x } = { x : α | ∀ i, P i x } := by ext exact mem_iInter theorem iUnion_congr_of_surjective {f : ι → Set α} {g : ι₂ → Set α} (h : ι → ι₂) (h1 : Surjective h) (h2 : ∀ x, g (h x) = f x) : ⋃ x, f x = ⋃ y, g y := h1.iSup_congr h h2 theorem iInter_congr_of_surjective {f : ι → Set α} {g : ι₂ → Set α} (h : ι → ι₂) (h1 : Surjective h) (h2 : ∀ x, g (h x) = f x) : ⋂ x, f x = ⋂ y, g y := h1.iInf_congr h h2 lemma iUnion_congr {s t : ι → Set α} (h : ∀ i, s i = t i) : ⋃ i, s i = ⋃ i, t i := iSup_congr h lemma iInter_congr {s t : ι → Set α} (h : ∀ i, s i = t i) : ⋂ i, s i = ⋂ i, t i := iInf_congr h lemma iUnion₂_congr {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j = t i j) : ⋃ (i) (j), s i j = ⋃ (i) (j), t i j := iUnion_congr fun i => iUnion_congr <| h i lemma iInter₂_congr {s t : ∀ i, κ i → Set α} (h : ∀ i j, s i j = t i j) : ⋂ (i) (j), s i j = ⋂ (i) (j), t i j := iInter_congr fun i => iInter_congr <| h i section Nonempty variable [Nonempty ι] {f : ι → Set α} {s : Set α} lemma iUnion_const (s : Set β) : ⋃ _ : ι, s = s := iSup_const lemma iInter_const (s : Set β) : ⋂ _ : ι, s = s := iInf_const lemma iUnion_eq_const (hf : ∀ i, f i = s) : ⋃ i, f i = s := (iUnion_congr hf).trans <| iUnion_const _ lemma iInter_eq_const (hf : ∀ i, f i = s) : ⋂ i, f i = s := (iInter_congr hf).trans <| iInter_const _ end Nonempty @[simp] theorem compl_iUnion (s : ι → Set β) : (⋃ i, s i)ᶜ = ⋂ i, (s i)ᶜ := compl_iSup theorem compl_iUnion₂ (s : ∀ i, κ i → Set α) : (⋃ (i) (j), s i j)ᶜ = ⋂ (i) (j), (s i j)ᶜ := by simp_rw [compl_iUnion] @[simp] theorem compl_iInter (s : ι → Set β) : (⋂ i, s i)ᶜ = ⋃ i, (s i)ᶜ := compl_iInf theorem compl_iInter₂ (s : ∀ i, κ i → Set α) : (⋂ (i) (j), s i j)ᶜ = ⋃ (i) (j), (s i j)ᶜ := by simp_rw [compl_iInter] -- classical -- complete_boolean_algebra theorem iUnion_eq_compl_iInter_compl (s : ι → Set β) : ⋃ i, s i = (⋂ i, (s i)ᶜ)ᶜ := by simp only [compl_iInter, compl_compl] -- classical -- complete_boolean_algebra theorem iInter_eq_compl_iUnion_compl (s : ι → Set β) : ⋂ i, s i = (⋃ i, (s i)ᶜ)ᶜ := by simp only [compl_iUnion, compl_compl] theorem inter_iUnion (s : Set β) (t : ι → Set β) : (s ∩ ⋃ i, t i) = ⋃ i, s ∩ t i := inf_iSup_eq _ _ theorem iUnion_inter (s : Set β) (t : ι → Set β) : (⋃ i, t i) ∩ s = ⋃ i, t i ∩ s := iSup_inf_eq _ _ theorem iUnion_union_distrib (s : ι → Set β) (t : ι → Set β) : ⋃ i, s i ∪ t i = (⋃ i, s i) ∪ ⋃ i, t i := iSup_sup_eq theorem iInter_inter_distrib (s : ι → Set β) (t : ι → Set β) : ⋂ i, s i ∩ t i = (⋂ i, s i) ∩ ⋂ i, t i := iInf_inf_eq theorem union_iUnion [Nonempty ι] (s : Set β) (t : ι → Set β) : (s ∪ ⋃ i, t i) = ⋃ i, s ∪ t i := sup_iSup theorem iUnion_union [Nonempty ι] (s : Set β) (t : ι → Set β) : (⋃ i, t i) ∪ s = ⋃ i, t i ∪ s := iSup_sup theorem inter_iInter [Nonempty ι] (s : Set β) (t : ι → Set β) : (s ∩ ⋂ i, t i) = ⋂ i, s ∩ t i := inf_iInf theorem iInter_inter [Nonempty ι] (s : Set β) (t : ι → Set β) : (⋂ i, t i) ∩ s = ⋂ i, t i ∩ s := iInf_inf theorem insert_iUnion [Nonempty ι] (x : β) (t : ι → Set β) : insert x (⋃ i, t i) = ⋃ i, insert x (t i) := by simp_rw [← union_singleton, iUnion_union] -- classical theorem union_iInter (s : Set β) (t : ι → Set β) : (s ∪ ⋂ i, t i) = ⋂ i, s ∪ t i := sup_iInf_eq _ _ theorem iInter_union (s : ι → Set β) (t : Set β) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := iInf_sup_eq _ _ theorem insert_iInter (x : β) (t : ι → Set β) : insert x (⋂ i, t i) = ⋂ i, insert x (t i) := by simp_rw [← union_singleton, iInter_union] theorem iUnion_diff (s : Set β) (t : ι → Set β) : (⋃ i, t i) \ s = ⋃ i, t i \ s := iUnion_inter _ _ theorem diff_iUnion [Nonempty ι] (s : Set β) (t : ι → Set β) : (s \ ⋃ i, t i) = ⋂ i, s \ t i := by rw [diff_eq, compl_iUnion, inter_iInter]; rfl theorem diff_iInter (s : Set β) (t : ι → Set β) : (s \ ⋂ i, t i) = ⋃ i, s \ t i := by rw [diff_eq, compl_iInter, inter_iUnion]; rfl theorem iUnion_inter_subset {ι α} {s t : ι → Set α} : ⋃ i, s i ∩ t i ⊆ (⋃ i, s i) ∩ ⋃ i, t i := le_iSup_inf_iSup s t theorem iUnion_inter_of_monotone {ι α} [Preorder ι] [IsDirected ι (· ≤ ·)] {s t : ι → Set α} (hs : Monotone s) (ht : Monotone t) : ⋃ i, s i ∩ t i = (⋃ i, s i) ∩ ⋃ i, t i := iSup_inf_of_monotone hs ht theorem iUnion_inter_of_antitone {ι α} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {s t : ι → Set α} (hs : Antitone s) (ht : Antitone t) : ⋃ i, s i ∩ t i = (⋃ i, s i) ∩ ⋃ i, t i := iSup_inf_of_antitone hs ht theorem iInter_union_of_monotone {ι α} [Preorder ι] [IsDirected ι (swap (· ≤ ·))] {s t : ι → Set α} (hs : Monotone s) (ht : Monotone t) : ⋂ i, s i ∪ t i = (⋂ i, s i) ∪ ⋂ i, t i := iInf_sup_of_monotone hs ht theorem iInter_union_of_antitone {ι α} [Preorder ι] [IsDirected ι (· ≤ ·)] {s t : ι → Set α} (hs : Antitone s) (ht : Antitone t) : ⋂ i, s i ∪ t i = (⋂ i, s i) ∪ ⋂ i, t i := iInf_sup_of_antitone hs ht /-- An equality version of this lemma is `iUnion_iInter_of_monotone` in `Data.Set.Finite`. -/ theorem iUnion_iInter_subset {s : ι → ι' → Set α} : (⋃ j, ⋂ i, s i j) ⊆ ⋂ i, ⋃ j, s i j := iSup_iInf_le_iInf_iSup (flip s) theorem iUnion_option {ι} (s : Option ι → Set α) : ⋃ o, s o = s none ∪ ⋃ i, s (some i) := iSup_option s theorem iInter_option {ι} (s : Option ι → Set α) : ⋂ o, s o = s none ∩ ⋂ i, s (some i) := iInf_option s section variable (p : ι → Prop) [DecidablePred p] theorem iUnion_dite (f : ∀ i, p i → Set α) (g : ∀ i, ¬p i → Set α) : ⋃ i, (if h : p i then f i h else g i h) = (⋃ (i) (h : p i), f i h) ∪ ⋃ (i) (h : ¬p i), g i h := iSup_dite _ _ _ theorem iUnion_ite (f g : ι → Set α) : ⋃ i, (if p i then f i else g i) = (⋃ (i) (_ : p i), f i) ∪ ⋃ (i) (_ : ¬p i), g i := iUnion_dite _ _ _ theorem iInter_dite (f : ∀ i, p i → Set α) (g : ∀ i, ¬p i → Set α) : ⋂ i, (if h : p i then f i h else g i h) = (⋂ (i) (h : p i), f i h) ∩ ⋂ (i) (h : ¬p i), g i h := iInf_dite _ _ _ theorem iInter_ite (f g : ι → Set α) : ⋂ i, (if p i then f i else g i) = (⋂ (i) (_ : p i), f i) ∩ ⋂ (i) (_ : ¬p i), g i := iInter_dite _ _ _ end /-! ### Unions and intersections indexed by `Prop` -/ theorem iInter_false {s : False → Set α} : iInter s = univ := iInf_false theorem iUnion_false {s : False → Set α} : iUnion s = ∅ := iSup_false @[simp] theorem iInter_true {s : True → Set α} : iInter s = s trivial := iInf_true @[simp] theorem iUnion_true {s : True → Set α} : iUnion s = s trivial := iSup_true @[simp] theorem iInter_exists {p : ι → Prop} {f : Exists p → Set α} : ⋂ x, f x = ⋂ (i) (h : p i), f ⟨i, h⟩ := iInf_exists @[simp] theorem iUnion_exists {p : ι → Prop} {f : Exists p → Set α} : ⋃ x, f x = ⋃ (i) (h : p i), f ⟨i, h⟩ := iSup_exists @[simp] theorem iUnion_empty : (⋃ _ : ι, ∅ : Set α) = ∅ := iSup_bot @[simp] theorem iInter_univ : (⋂ _ : ι, univ : Set α) = univ := iInf_top section variable {s : ι → Set α} @[simp] theorem iUnion_eq_empty : ⋃ i, s i = ∅ ↔ ∀ i, s i = ∅ := iSup_eq_bot @[simp] theorem iInter_eq_univ : ⋂ i, s i = univ ↔ ∀ i, s i = univ := iInf_eq_top @[simp] theorem nonempty_iUnion : (⋃ i, s i).Nonempty ↔ ∃ i, (s i).Nonempty := by simp [nonempty_iff_ne_empty] theorem nonempty_biUnion {t : Set α} {s : α → Set β} : (⋃ i ∈ t, s i).Nonempty ↔ ∃ i ∈ t, (s i).Nonempty := by simp theorem iUnion_nonempty_index (s : Set α) (t : s.Nonempty → Set β) : ⋃ h, t h = ⋃ x ∈ s, t ⟨x, ‹_›⟩ := iSup_exists end @[simp] theorem iInter_iInter_eq_left {b : β} {s : ∀ x : β, x = b → Set α} : ⋂ (x) (h : x = b), s x h = s b rfl := iInf_iInf_eq_left @[simp] theorem iInter_iInter_eq_right {b : β} {s : ∀ x : β, b = x → Set α} : ⋂ (x) (h : b = x), s x h = s b rfl := iInf_iInf_eq_right @[simp] theorem iUnion_iUnion_eq_left {b : β} {s : ∀ x : β, x = b → Set α} : ⋃ (x) (h : x = b), s x h = s b rfl := iSup_iSup_eq_left @[simp] theorem iUnion_iUnion_eq_right {b : β} {s : ∀ x : β, b = x → Set α} : ⋃ (x) (h : b = x), s x h = s b rfl := iSup_iSup_eq_right theorem iInter_or {p q : Prop} (s : p ∨ q → Set α) : ⋂ h, s h = (⋂ h : p, s (Or.inl h)) ∩ ⋂ h : q, s (Or.inr h) := iInf_or theorem iUnion_or {p q : Prop} (s : p ∨ q → Set α) : ⋃ h, s h = (⋃ i, s (Or.inl i)) ∪ ⋃ j, s (Or.inr j) := iSup_or theorem iUnion_and {p q : Prop} (s : p ∧ q → Set α) : ⋃ h, s h = ⋃ (hp) (hq), s ⟨hp, hq⟩ := iSup_and theorem iInter_and {p q : Prop} (s : p ∧ q → Set α) : ⋂ h, s h = ⋂ (hp) (hq), s ⟨hp, hq⟩ := iInf_and theorem iUnion_comm (s : ι → ι' → Set α) : ⋃ (i) (i'), s i i' = ⋃ (i') (i), s i i' := iSup_comm theorem iInter_comm (s : ι → ι' → Set α) : ⋂ (i) (i'), s i i' = ⋂ (i') (i), s i i' := iInf_comm theorem iUnion_sigma {γ : α → Type*} (s : Sigma γ → Set β) : ⋃ ia, s ia = ⋃ i, ⋃ a, s ⟨i, a⟩ := iSup_sigma theorem iUnion_sigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋃ i, ⋃ a, s i a = ⋃ ia : Sigma γ, s ia.1 ia.2 := iSup_sigma' _ theorem iInter_sigma {γ : α → Type*} (s : Sigma γ → Set β) : ⋂ ia, s ia = ⋂ i, ⋂ a, s ⟨i, a⟩ := iInf_sigma theorem iInter_sigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋂ i, ⋂ a, s i a = ⋂ ia : Sigma γ, s ia.1 ia.2 := iInf_sigma' _ theorem iUnion₂_comm (s : ∀ i, κ i → ∀ i', κ' i' → Set α) : ⋃ (i) (j) (i') (j'), s i j i' j' = ⋃ (i') (j') (i) (j), s i j i' j' := iSup₂_comm _ theorem iInter₂_comm (s : ∀ i, κ i → ∀ i', κ' i' → Set α) : ⋂ (i) (j) (i') (j'), s i j i' j' = ⋂ (i') (j') (i) (j), s i j i' j' := iInf₂_comm _ @[simp] theorem biUnion_and (p : ι → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p x ∧ q x y → Set α) : ⋃ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h = ⋃ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [iUnion_and, @iUnion_comm _ ι'] @[simp] theorem biUnion_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p y ∧ q x y → Set α) : ⋃ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h = ⋃ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [iUnion_and, @iUnion_comm _ ι] @[simp] theorem biInter_and (p : ι → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p x ∧ q x y → Set α) : ⋂ (x : ι) (y : ι') (h : p x ∧ q x y), s x y h = ⋂ (x : ι) (hx : p x) (y : ι') (hy : q x y), s x y ⟨hx, hy⟩ := by simp only [iInter_and, @iInter_comm _ ι'] @[simp] theorem biInter_and' (p : ι' → Prop) (q : ι → ι' → Prop) (s : ∀ x y, p y ∧ q x y → Set α) : ⋂ (x : ι) (y : ι') (h : p y ∧ q x y), s x y h = ⋂ (y : ι') (hy : p y) (x : ι) (hx : q x y), s x y ⟨hy, hx⟩ := by simp only [iInter_and, @iInter_comm _ ι] @[simp] theorem iUnion_iUnion_eq_or_left {b : β} {p : β → Prop} {s : ∀ x : β, x = b ∨ p x → Set α} : ⋃ (x) (h), s x h = s b (Or.inl rfl) ∪ ⋃ (x) (h : p x), s x (Or.inr h) := by simp only [iUnion_or, iUnion_union_distrib, iUnion_iUnion_eq_left] @[simp] theorem iInter_iInter_eq_or_left {b : β} {p : β → Prop} {s : ∀ x : β, x = b ∨ p x → Set α} : ⋂ (x) (h), s x h = s b (Or.inl rfl) ∩ ⋂ (x) (h : p x), s x (Or.inr h) := by simp only [iInter_or, iInter_inter_distrib, iInter_iInter_eq_left] lemma iUnion_sum {s : α ⊕ β → Set γ} : ⋃ x, s x = (⋃ x, s (.inl x)) ∪ ⋃ x, s (.inr x) := iSup_sum lemma iInter_sum {s : α ⊕ β → Set γ} : ⋂ x, s x = (⋂ x, s (.inl x)) ∩ ⋂ x, s (.inr x) := iInf_sum theorem iUnion_psigma {γ : α → Type*} (s : PSigma γ → Set β) : ⋃ ia, s ia = ⋃ i, ⋃ a, s ⟨i, a⟩ := iSup_psigma _ /-- A reversed version of `iUnion_psigma` with a curried map. -/ theorem iUnion_psigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋃ i, ⋃ a, s i a = ⋃ ia : PSigma γ, s ia.1 ia.2 := iSup_psigma' _ theorem iInter_psigma {γ : α → Type*} (s : PSigma γ → Set β) : ⋂ ia, s ia = ⋂ i, ⋂ a, s ⟨i, a⟩ := iInf_psigma _ /-- A reversed version of `iInter_psigma` with a curried map. -/ theorem iInter_psigma' {γ : α → Type*} (s : ∀ i, γ i → Set β) : ⋂ i, ⋂ a, s i a = ⋂ ia : PSigma γ, s ia.1 ia.2 := iInf_psigma' _ /-! ### Bounded unions and intersections -/ /-- A specialization of `mem_iUnion₂`. -/ theorem mem_biUnion {s : Set α} {t : α → Set β} {x : α} {y : β} (xs : x ∈ s) (ytx : y ∈ t x) : y ∈ ⋃ x ∈ s, t x := mem_iUnion₂_of_mem xs ytx /-- A specialization of `mem_iInter₂`. -/ theorem mem_biInter {s : Set α} {t : α → Set β} {y : β} (h : ∀ x ∈ s, y ∈ t x) : y ∈ ⋂ x ∈ s, t x := mem_iInter₂_of_mem h /-- A specialization of `subset_iUnion₂`. -/ theorem subset_biUnion_of_mem {s : Set α} {u : α → Set β} {x : α} (xs : x ∈ s) : u x ⊆ ⋃ x ∈ s, u x := subset_iUnion₂ (s := fun i _ => u i) x xs /-- A specialization of `iInter₂_subset`. -/ theorem biInter_subset_of_mem {s : Set α} {t : α → Set β} {x : α} (xs : x ∈ s) : ⋂ x ∈ s, t x ⊆ t x := iInter₂_subset x xs lemma biInter_subset_biUnion {s : Set α} (hs : s.Nonempty) {t : α → Set β} : ⋂ x ∈ s, t x ⊆ ⋃ x ∈ s, t x := biInf_le_biSup hs theorem biUnion_subset_biUnion_left {s s' : Set α} {t : α → Set β} (h : s ⊆ s') : ⋃ x ∈ s, t x ⊆ ⋃ x ∈ s', t x := iUnion₂_subset fun _ hx => subset_biUnion_of_mem <| h hx theorem biInter_subset_biInter_left {s s' : Set α} {t : α → Set β} (h : s' ⊆ s) : ⋂ x ∈ s, t x ⊆ ⋂ x ∈ s', t x := subset_iInter₂ fun _ hx => biInter_subset_of_mem <| h hx theorem biUnion_mono {s s' : Set α} {t t' : α → Set β} (hs : s' ⊆ s) (h : ∀ x ∈ s, t x ⊆ t' x) : ⋃ x ∈ s', t x ⊆ ⋃ x ∈ s, t' x := (biUnion_subset_biUnion_left hs).trans <| iUnion₂_mono h theorem biInter_mono {s s' : Set α} {t t' : α → Set β} (hs : s ⊆ s') (h : ∀ x ∈ s, t x ⊆ t' x) : ⋂ x ∈ s', t x ⊆ ⋂ x ∈ s, t' x := (biInter_subset_biInter_left hs).trans <| iInter₂_mono h theorem biUnion_eq_iUnion (s : Set α) (t : ∀ x ∈ s, Set β) : ⋃ x ∈ s, t x ‹_› = ⋃ x : s, t x x.2 := iSup_subtype' theorem biInter_eq_iInter (s : Set α) (t : ∀ x ∈ s, Set β) : ⋂ x ∈ s, t x ‹_› = ⋂ x : s, t x x.2 := iInf_subtype' @[simp] lemma biUnion_const {s : Set α} (hs : s.Nonempty) (t : Set β) : ⋃ a ∈ s, t = t := biSup_const hs @[simp] lemma biInter_const {s : Set α} (hs : s.Nonempty) (t : Set β) : ⋂ a ∈ s, t = t := biInf_const hs theorem iUnion_subtype (p : α → Prop) (s : { x // p x } → Set β) : ⋃ x : { x // p x }, s x = ⋃ (x) (hx : p x), s ⟨x, hx⟩ := iSup_subtype theorem iInter_subtype (p : α → Prop) (s : { x // p x } → Set β) : ⋂ x : { x // p x }, s x = ⋂ (x) (hx : p x), s ⟨x, hx⟩ := iInf_subtype theorem biInter_empty (u : α → Set β) : ⋂ x ∈ (∅ : Set α), u x = univ := iInf_emptyset theorem biInter_univ (u : α → Set β) : ⋂ x ∈ @univ α, u x = ⋂ x, u x := iInf_univ @[simp] theorem biUnion_self (s : Set α) : ⋃ x ∈ s, s = s := Subset.antisymm (iUnion₂_subset fun _ _ => Subset.refl s) fun _ hx => mem_biUnion hx hx @[simp] theorem iUnion_nonempty_self (s : Set α) : ⋃ _ : s.Nonempty, s = s := by rw [iUnion_nonempty_index, biUnion_self] theorem biInter_singleton (a : α) (s : α → Set β) : ⋂ x ∈ ({a} : Set α), s x = s a := iInf_singleton theorem biInter_union (s t : Set α) (u : α → Set β) : ⋂ x ∈ s ∪ t, u x = (⋂ x ∈ s, u x) ∩ ⋂ x ∈ t, u x := iInf_union theorem biInter_insert (a : α) (s : Set α) (t : α → Set β) : ⋂ x ∈ insert a s, t x = t a ∩ ⋂ x ∈ s, t x := by simp theorem biInter_pair (a b : α) (s : α → Set β) : ⋂ x ∈ ({a, b} : Set α), s x = s a ∩ s b := by rw [biInter_insert, biInter_singleton] theorem biInter_inter {ι α : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → Set α) (t : Set α) : ⋂ i ∈ s, f i ∩ t = (⋂ i ∈ s, f i) ∩ t := by haveI : Nonempty s := hs.to_subtype simp [biInter_eq_iInter, ← iInter_inter] theorem inter_biInter {ι α : Type*} {s : Set ι} (hs : s.Nonempty) (f : ι → Set α) (t : Set α) : ⋂ i ∈ s, t ∩ f i = t ∩ ⋂ i ∈ s, f i := by rw [inter_comm, ← biInter_inter hs] simp [inter_comm] theorem biUnion_empty (s : α → Set β) : ⋃ x ∈ (∅ : Set α), s x = ∅ := iSup_emptyset theorem biUnion_univ (s : α → Set β) : ⋃ x ∈ @univ α, s x = ⋃ x, s x := iSup_univ theorem biUnion_singleton (a : α) (s : α → Set β) : ⋃ x ∈ ({a} : Set α), s x = s a := iSup_singleton @[simp] theorem biUnion_of_singleton (s : Set α) : ⋃ x ∈ s, {x} = s := ext <| by simp theorem biUnion_union (s t : Set α) (u : α → Set β) : ⋃ x ∈ s ∪ t, u x = (⋃ x ∈ s, u x) ∪ ⋃ x ∈ t, u x := iSup_union @[simp] theorem iUnion_coe_set {α β : Type*} (s : Set α) (f : s → Set β) : ⋃ i, f i = ⋃ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := iUnion_subtype _ _ @[simp] theorem iInter_coe_set {α β : Type*} (s : Set α) (f : s → Set β) : ⋂ i, f i = ⋂ i ∈ s, f ⟨i, ‹i ∈ s›⟩ := iInter_subtype _ _ theorem biUnion_insert (a : α) (s : Set α) (t : α → Set β) : ⋃ x ∈ insert a s, t x = t a ∪ ⋃ x ∈ s, t x := by simp theorem biUnion_pair (a b : α) (s : α → Set β) : ⋃ x ∈ ({a, b} : Set α), s x = s a ∪ s b := by simp theorem inter_iUnion₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s ∩ ⋃ (i) (j), t i j) = ⋃ (i) (j), s ∩ t i j := by simp only [inter_iUnion] theorem iUnion₂_inter (s : ∀ i, κ i → Set α) (t : Set α) : (⋃ (i) (j), s i j) ∩ t = ⋃ (i) (j), s i j ∩ t := by simp_rw [iUnion_inter] theorem union_iInter₂ (s : Set α) (t : ∀ i, κ i → Set α) : (s ∪ ⋂ (i) (j), t i j) = ⋂ (i) (j), s ∪ t i j := by simp_rw [union_iInter] theorem iInter₂_union (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) ∪ t = ⋂ (i) (j), s i j ∪ t := by simp_rw [iInter_union] theorem mem_sUnion_of_mem {x : α} {t : Set α} {S : Set (Set α)} (hx : x ∈ t) (ht : t ∈ S) : x ∈ ⋃₀ S := ⟨t, ht, hx⟩ -- is this theorem really necessary? theorem notMem_of_notMem_sUnion {x : α} {t : Set α} {S : Set (Set α)} (hx : x ∉ ⋃₀ S) (ht : t ∈ S) : x ∉ t := fun h => hx ⟨t, ht, h⟩ @[deprecated (since := "2025-05-23")] alias not_mem_of_not_mem_sUnion := notMem_of_notMem_sUnion theorem sInter_subset_of_mem {S : Set (Set α)} {t : Set α} (tS : t ∈ S) : ⋂₀ S ⊆ t := sInf_le tS theorem subset_sUnion_of_mem {S : Set (Set α)} {t : Set α} (tS : t ∈ S) : t ⊆ ⋃₀ S := le_sSup tS theorem subset_sUnion_of_subset {s : Set α} (t : Set (Set α)) (u : Set α) (h₁ : s ⊆ u) (h₂ : u ∈ t) : s ⊆ ⋃₀ t := Subset.trans h₁ (subset_sUnion_of_mem h₂) theorem sUnion_subset {S : Set (Set α)} {t : Set α} (h : ∀ t' ∈ S, t' ⊆ t) : ⋃₀ S ⊆ t := sSup_le h @[simp] theorem sUnion_subset_iff {s : Set (Set α)} {t : Set α} : ⋃₀ s ⊆ t ↔ ∀ t' ∈ s, t' ⊆ t := sSup_le_iff /-- `sUnion` is monotone under taking a subset of each set. -/ lemma sUnion_mono_subsets {s : Set (Set α)} {f : Set α → Set α} (hf : ∀ t : Set α, t ⊆ f t) : ⋃₀ s ⊆ ⋃₀ (f '' s) := fun _ ⟨t, htx, hxt⟩ ↦ ⟨f t, mem_image_of_mem f htx, hf t hxt⟩ /-- `sUnion` is monotone under taking a superset of each set. -/ lemma sUnion_mono_supsets {s : Set (Set α)} {f : Set α → Set α} (hf : ∀ t : Set α, f t ⊆ t) : ⋃₀ (f '' s) ⊆ ⋃₀ s := -- If t ∈ f '' s is arbitrary; t = f u for some u : Set α. fun _ ⟨_, ⟨u, hus, hut⟩, hxt⟩ ↦ ⟨u, hus, (hut ▸ hf u) hxt⟩ theorem subset_sInter {S : Set (Set α)} {t : Set α} (h : ∀ t' ∈ S, t ⊆ t') : t ⊆ ⋂₀ S := le_sInf h @[simp] theorem subset_sInter_iff {S : Set (Set α)} {t : Set α} : t ⊆ ⋂₀ S ↔ ∀ t' ∈ S, t ⊆ t' := le_sInf_iff @[gcongr] theorem sUnion_subset_sUnion {S T : Set (Set α)} (h : S ⊆ T) : ⋃₀ S ⊆ ⋃₀ T := sUnion_subset fun _ hs => subset_sUnion_of_mem (h hs) @[gcongr] theorem sInter_subset_sInter {S T : Set (Set α)} (h : S ⊆ T) : ⋂₀ T ⊆ ⋂₀ S := subset_sInter fun _ hs => sInter_subset_of_mem (h hs) @[simp] theorem sUnion_empty : ⋃₀ ∅ = (∅ : Set α) := sSup_empty @[simp] theorem sInter_empty : ⋂₀ ∅ = (univ : Set α) := sInf_empty @[simp] theorem sUnion_singleton (s : Set α) : ⋃₀ {s} = s := sSup_singleton @[simp] theorem sInter_singleton (s : Set α) : ⋂₀ {s} = s := sInf_singleton @[simp] theorem sUnion_eq_empty {S : Set (Set α)} : ⋃₀ S = ∅ ↔ ∀ s ∈ S, s = ∅ := sSup_eq_bot @[simp] theorem sInter_eq_univ {S : Set (Set α)} : ⋂₀ S = univ ↔ ∀ s ∈ S, s = univ := sInf_eq_top theorem subset_powerset_iff {s : Set (Set α)} {t : Set α} : s ⊆ 𝒫 t ↔ ⋃₀ s ⊆ t := sUnion_subset_iff.symm /-- `⋃₀` and `𝒫` form a Galois connection. -/ theorem sUnion_powerset_gc : GaloisConnection (⋃₀ · : Set (Set α) → Set α) (𝒫 · : Set α → Set (Set α)) := gc_sSup_Iic /-- `⋃₀` and `𝒫` form a Galois insertion. -/ def sUnionPowersetGI : GaloisInsertion (⋃₀ · : Set (Set α) → Set α) (𝒫 · : Set α → Set (Set α)) := gi_sSup_Iic /-- If all sets in a collection are either `∅` or `Set.univ`, then so is their union. -/ theorem sUnion_mem_empty_univ {S : Set (Set α)} (h : S ⊆ {∅, univ}) : ⋃₀ S ∈ ({∅, univ} : Set (Set α)) := by simp only [mem_insert_iff, mem_singleton_iff, or_iff_not_imp_left, sUnion_eq_empty, not_forall] rintro ⟨s, hs, hne⟩ obtain rfl : s = univ := (h hs).resolve_left hne exact univ_subset_iff.1 <| subset_sUnion_of_mem hs @[simp] theorem nonempty_sUnion {S : Set (Set α)} : (⋃₀ S).Nonempty ↔ ∃ s ∈ S, Set.Nonempty s := by simp [nonempty_iff_ne_empty] theorem Nonempty.of_sUnion {s : Set (Set α)} (h : (⋃₀ s).Nonempty) : s.Nonempty := let ⟨s, hs, _⟩ := nonempty_sUnion.1 h ⟨s, hs⟩ theorem Nonempty.of_sUnion_eq_univ [Nonempty α] {s : Set (Set α)} (h : ⋃₀ s = univ) : s.Nonempty := Nonempty.of_sUnion <| h.symm ▸ univ_nonempty theorem sUnion_union (S T : Set (Set α)) : ⋃₀ (S ∪ T) = ⋃₀ S ∪ ⋃₀ T := sSup_union theorem sInter_union (S T : Set (Set α)) : ⋂₀ (S ∪ T) = ⋂₀ S ∩ ⋂₀ T := sInf_union @[simp] theorem sUnion_insert (s : Set α) (T : Set (Set α)) : ⋃₀ insert s T = s ∪ ⋃₀ T := sSup_insert @[simp] theorem sInter_insert (s : Set α) (T : Set (Set α)) : ⋂₀ insert s T = s ∩ ⋂₀ T := sInf_insert @[simp] theorem sUnion_diff_singleton_empty (s : Set (Set α)) : ⋃₀ (s \ {∅}) = ⋃₀ s := sSup_diff_singleton_bot s @[simp] theorem sInter_diff_singleton_univ (s : Set (Set α)) : ⋂₀ (s \ {univ}) = ⋂₀ s := sInf_diff_singleton_top s theorem sUnion_pair (s t : Set α) : ⋃₀ {s, t} = s ∪ t := sSup_pair theorem sInter_pair (s t : Set α) : ⋂₀ {s, t} = s ∩ t := sInf_pair @[simp] theorem sUnion_image (f : α → Set β) (s : Set α) : ⋃₀ (f '' s) = ⋃ a ∈ s, f a := sSup_image @[simp] theorem sInter_image (f : α → Set β) (s : Set α) : ⋂₀ (f '' s) = ⋂ a ∈ s, f a := sInf_image @[simp] lemma sUnion_image2 (f : α → β → Set γ) (s : Set α) (t : Set β) : ⋃₀ (image2 f s t) = ⋃ (a ∈ s) (b ∈ t), f a b := sSup_image2 @[simp] lemma sInter_image2 (f : α → β → Set γ) (s : Set α) (t : Set β) : ⋂₀ (image2 f s t) = ⋂ (a ∈ s) (b ∈ t), f a b := sInf_image2 @[simp] theorem sUnion_range (f : ι → Set β) : ⋃₀ range f = ⋃ x, f x := rfl @[simp] theorem sInter_range (f : ι → Set β) : ⋂₀ range f = ⋂ x, f x := rfl theorem iUnion_eq_univ_iff {f : ι → Set α} : ⋃ i, f i = univ ↔ ∀ x, ∃ i, x ∈ f i := by simp only [eq_univ_iff_forall, mem_iUnion] theorem iUnion₂_eq_univ_iff {s : ∀ i, κ i → Set α} : ⋃ (i) (j), s i j = univ ↔ ∀ a, ∃ i j, a ∈ s i j := by simp only [iUnion_eq_univ_iff, mem_iUnion] theorem sUnion_eq_univ_iff {c : Set (Set α)} : ⋃₀ c = univ ↔ ∀ a, ∃ b ∈ c, a ∈ b := by simp only [eq_univ_iff_forall, mem_sUnion] -- classical theorem iInter_eq_empty_iff {f : ι → Set α} : ⋂ i, f i = ∅ ↔ ∀ x, ∃ i, x ∉ f i := by simp [Set.eq_empty_iff_forall_notMem] -- classical theorem iInter₂_eq_empty_iff {s : ∀ i, κ i → Set α} : ⋂ (i) (j), s i j = ∅ ↔ ∀ a, ∃ i j, a ∉ s i j := by simp only [eq_empty_iff_forall_notMem, mem_iInter, not_forall] -- classical theorem sInter_eq_empty_iff {c : Set (Set α)} : ⋂₀ c = ∅ ↔ ∀ a, ∃ b ∈ c, a ∉ b := by simp [Set.eq_empty_iff_forall_notMem] -- classical @[simp] theorem nonempty_iInter {f : ι → Set α} : (⋂ i, f i).Nonempty ↔ ∃ x, ∀ i, x ∈ f i := by simp [nonempty_iff_ne_empty, iInter_eq_empty_iff] -- classical theorem nonempty_iInter₂ {s : ∀ i, κ i → Set α} : (⋂ (i) (j), s i j).Nonempty ↔ ∃ a, ∀ i j, a ∈ s i j := by simp -- classical @[simp] theorem nonempty_sInter {c : Set (Set α)} : (⋂₀ c).Nonempty ↔ ∃ a, ∀ b ∈ c, a ∈ b := by simp [nonempty_iff_ne_empty, sInter_eq_empty_iff] -- classical theorem compl_sUnion (S : Set (Set α)) : (⋃₀ S)ᶜ = ⋂₀ (compl '' S) := ext fun x => by simp -- classical theorem sUnion_eq_compl_sInter_compl (S : Set (Set α)) : ⋃₀ S = (⋂₀ (compl '' S))ᶜ := by rw [← compl_compl (⋃₀ S), compl_sUnion] -- classical theorem compl_sInter (S : Set (Set α)) : (⋂₀ S)ᶜ = ⋃₀ (compl '' S) := by rw [sUnion_eq_compl_sInter_compl, compl_compl_image] -- classical theorem sInter_eq_compl_sUnion_compl (S : Set (Set α)) : ⋂₀ S = (⋃₀ (compl '' S))ᶜ := by rw [← compl_compl (⋂₀ S), compl_sInter] theorem inter_empty_of_inter_sUnion_empty {s t : Set α} {S : Set (Set α)} (hs : t ∈ S) (h : s ∩ ⋃₀ S = ∅) : s ∩ t = ∅ := eq_empty_of_subset_empty <| by rw [← h]; exact inter_subset_inter_right _ (subset_sUnion_of_mem hs) theorem range_sigma_eq_iUnion_range {γ : α → Type*} (f : Sigma γ → β) : range f = ⋃ a, range fun b => f ⟨a, b⟩ := Set.ext <| by simp theorem iUnion_eq_range_sigma (s : α → Set β) : ⋃ i, s i = range fun a : Σ i, s i => a.2 := by simp [Set.ext_iff] theorem iUnion_eq_range_psigma (s : ι → Set β) : ⋃ i, s i = range fun a : Σ' i, s i => a.2 := by simp [Set.ext_iff] theorem iUnion_image_preimage_sigma_mk_eq_self {ι : Type*} {σ : ι → Type*} (s : Set (Sigma σ)) : ⋃ i, Sigma.mk i '' (Sigma.mk i ⁻¹' s) = s := by ext x simp only [mem_iUnion, mem_image, mem_preimage] constructor · rintro ⟨i, a, h, rfl⟩ exact h · intro h obtain ⟨i, a⟩ := x exact ⟨i, a, h, rfl⟩ theorem Sigma.univ (X : α → Type*) : (Set.univ : Set (Σ a, X a)) = ⋃ a, range (Sigma.mk a) := Set.ext fun x => iff_of_true trivial ⟨range (Sigma.mk x.1), Set.mem_range_self _, x.2, Sigma.eta x⟩ alias sUnion_mono := sUnion_subset_sUnion alias sInter_mono := sInter_subset_sInter theorem iUnion_subset_iUnion_const {s : Set α} (h : ι → ι₂) : ⋃ _ : ι, s ⊆ ⋃ _ : ι₂, s := iSup_const_mono (α := Set α) h @[simp] theorem iUnion_singleton_eq_range (f : α → β) : ⋃ x : α, {f x} = range f := by ext x simp [@eq_comm _ x] theorem iUnion_insert_eq_range_union_iUnion {ι : Type*} (x : ι → β) (t : ι → Set β) : ⋃ i, insert (x i) (t i) = range x ∪ ⋃ i, t i := by simp_rw [← union_singleton, iUnion_union_distrib, union_comm, iUnion_singleton_eq_range] theorem iUnion_of_singleton (α : Type*) : (⋃ x, {x} : Set α) = univ := by simp [Set.ext_iff] theorem iUnion_of_singleton_coe (s : Set α) : ⋃ i : s, ({(i : α)} : Set α) = s := by simp theorem sUnion_eq_biUnion {s : Set (Set α)} : ⋃₀ s = ⋃ (i : Set α) (_ : i ∈ s), i := by rw [← sUnion_image, image_id'] theorem sInter_eq_biInter {s : Set (Set α)} : ⋂₀ s = ⋂ (i : Set α) (_ : i ∈ s), i := by rw [← sInter_image, image_id'] theorem sUnion_eq_iUnion {s : Set (Set α)} : ⋃₀ s = ⋃ i : s, i := by simp only [← sUnion_range, Subtype.range_coe] theorem sInter_eq_iInter {s : Set (Set α)} : ⋂₀ s = ⋂ i : s, i := by simp only [← sInter_range, Subtype.range_coe] @[simp] theorem iUnion_of_empty [IsEmpty ι] (s : ι → Set α) : ⋃ i, s i = ∅ := iSup_of_empty _ @[simp] theorem iInter_of_empty [IsEmpty ι] (s : ι → Set α) : ⋂ i, s i = univ := iInf_of_empty _ theorem union_eq_iUnion {s₁ s₂ : Set α} : s₁ ∪ s₂ = ⋃ b : Bool, cond b s₁ s₂ := sup_eq_iSup s₁ s₂ theorem inter_eq_iInter {s₁ s₂ : Set α} : s₁ ∩ s₂ = ⋂ b : Bool, cond b s₁ s₂ := inf_eq_iInf s₁ s₂ theorem sInter_union_sInter {S T : Set (Set α)} : ⋂₀ S ∪ ⋂₀ T = ⋂ p ∈ S ×ˢ T, (p : Set α × Set α).1 ∪ p.2 := sInf_sup_sInf theorem sUnion_inter_sUnion {s t : Set (Set α)} : ⋃₀ s ∩ ⋃₀ t = ⋃ p ∈ s ×ˢ t, (p : Set α × Set α).1 ∩ p.2 := sSup_inf_sSup theorem biUnion_iUnion (s : ι → Set α) (t : α → Set β) : ⋃ x ∈ ⋃ i, s i, t x = ⋃ (i) (x ∈ s i), t x := by simp [@iUnion_comm _ ι] theorem biInter_iUnion (s : ι → Set α) (t : α → Set β) : ⋂ x ∈ ⋃ i, s i, t x = ⋂ (i) (x ∈ s i), t x := by simp [@iInter_comm _ ι] theorem sUnion_iUnion (s : ι → Set (Set α)) : ⋃₀ ⋃ i, s i = ⋃ i, ⋃₀ s i := by simp only [sUnion_eq_biUnion, biUnion_iUnion] theorem sInter_iUnion (s : ι → Set (Set α)) : ⋂₀ ⋃ i, s i = ⋂ i, ⋂₀ s i := by simp only [sInter_eq_biInter, biInter_iUnion] theorem iUnion_range_eq_sUnion {α β : Type*} (C : Set (Set α)) {f : ∀ s : C, β → (s : Type _)} (hf : ∀ s : C, Surjective (f s)) : ⋃ y : β, range (fun s : C => (f s y).val) = ⋃₀ C := by ext x; constructor · rintro ⟨s, ⟨y, rfl⟩, ⟨s, hs⟩, rfl⟩ refine ⟨_, hs, ?_⟩ exact (f ⟨s, hs⟩ y).2 · rintro ⟨s, hs, hx⟩ obtain ⟨y, hy⟩ := hf ⟨s, hs⟩ ⟨x, hx⟩ refine ⟨_, ⟨y, rfl⟩, ⟨s, hs⟩, ?_⟩ exact congr_arg Subtype.val hy theorem iUnion_range_eq_iUnion (C : ι → Set α) {f : ∀ x : ι, β → C x} (hf : ∀ x : ι, Surjective (f x)) : ⋃ y : β, range (fun x : ι => (f x y).val) = ⋃ x, C x := by ext x; rw [mem_iUnion, mem_iUnion]; constructor · rintro ⟨y, i, rfl⟩ exact ⟨i, (f i y).2⟩ · rintro ⟨i, hx⟩ obtain ⟨y, hy⟩ := hf i ⟨x, hx⟩ exact ⟨y, i, congr_arg Subtype.val hy⟩ theorem union_distrib_iInter_left (s : ι → Set α) (t : Set α) : (t ∪ ⋂ i, s i) = ⋂ i, t ∪ s i := sup_iInf_eq _ _ theorem union_distrib_iInter₂_left (s : Set α) (t : ∀ i, κ i → Set α) : (s ∪ ⋂ (i) (j), t i j) = ⋂ (i) (j), s ∪ t i j := by simp_rw [union_distrib_iInter_left] theorem union_distrib_iInter_right (s : ι → Set α) (t : Set α) : (⋂ i, s i) ∪ t = ⋂ i, s i ∪ t := iInf_sup_eq _ _ theorem union_distrib_iInter₂_right (s : ∀ i, κ i → Set α) (t : Set α) : (⋂ (i) (j), s i j) ∪ t = ⋂ (i) (j), s i j ∪ t := by simp_rw [union_distrib_iInter_right] lemma biUnion_lt_eq_iUnion [LT α] [NoMaxOrder α] {s : α → Set β} : ⋃ (n) (m < n), s m = ⋃ n, s n := biSup_lt_eq_iSup lemma biUnion_le_eq_iUnion [Preorder α] {s : α → Set β} : ⋃ (n) (m ≤ n), s m = ⋃ n, s n := biSup_le_eq_iSup lemma biInter_lt_eq_iInter [LT α] [NoMaxOrder α] {s : α → Set β} : ⋂ (n) (m < n), s m = ⋂ (n), s n := biInf_lt_eq_iInf lemma biInter_le_eq_iInter [Preorder α] {s : α → Set β} : ⋂ (n) (m ≤ n), s m = ⋂ (n), s n := biInf_le_eq_iInf lemma biUnion_gt_eq_iUnion [LT α] [NoMinOrder α] {s : α → Set β} : ⋃ (n) (m > n), s m = ⋃ n, s n := biSup_gt_eq_iSup lemma biUnion_ge_eq_iUnion [Preorder α] {s : α → Set β} : ⋃ (n) (m ≥ n), s m = ⋃ n, s n := biSup_ge_eq_iSup lemma biInter_gt_eq_iInf [LT α] [NoMinOrder α] {s : α → Set β} : ⋂ (n) (m > n), s m = ⋂ n, s n := biInf_gt_eq_iInf lemma biInter_ge_eq_iInf [Preorder α] {s : α → Set β} : ⋂ (n) (m ≥ n), s m = ⋂ n, s n := biInf_ge_eq_iInf section le variable {ι : Type*} [PartialOrder ι] (s : ι → Set α) (i : ι) theorem biUnion_le : (⋃ j ≤ i, s j) = (⋃ j < i, s j) ∪ s i := biSup_le_eq_sup s i theorem biInter_le : (⋂ j ≤ i, s j) = (⋂ j < i, s j) ∩ s i := biInf_le_eq_inf s i theorem biUnion_ge : (⋃ j ≥ i, s j) = s i ∪ ⋃ j > i, s j := biSup_ge_eq_sup s i theorem biInter_ge : (⋂ j ≥ i, s j) = s i ∩ ⋂ j > i, s j := biInf_ge_eq_inf s i end le section Pi variable {π : α → Type*} theorem pi_def (i : Set α) (s : ∀ a, Set (π a)) : pi i s = ⋂ a ∈ i, eval a ⁻¹' s a := by ext simp theorem univ_pi_eq_iInter (t : ∀ i, Set (π i)) : pi univ t = ⋂ i, eval i ⁻¹' t i := by simp only [pi_def, iInter_true, mem_univ] theorem pi_diff_pi_subset (i : Set α) (s t : ∀ a, Set (π a)) : pi i s \ pi i t ⊆ ⋃ a ∈ i, eval a ⁻¹' (s a \ t a) := by refine diff_subset_comm.2 fun x hx a ha => ?_ simp only [mem_diff, mem_pi, mem_iUnion, not_exists, mem_preimage, not_and, not_not] at hx exact hx.2 _ ha (hx.1 _ ha) theorem iUnion_univ_pi {ι : α → Type*} (t : (a : α) → ι a → Set (π a)) : ⋃ x : (a : α) → ι a, pi univ (fun a => t a (x a)) = pi univ fun a => ⋃ j : ι a, t a j := by ext simp [Classical.skolem] theorem biUnion_univ_pi {ι : α → Type*} (s : (a : α) → Set (ι a)) (t : (a : α) → ι a → Set (π a)) : ⋃ x ∈ univ.pi s, pi univ (fun a => t a (x a)) = pi univ fun a => ⋃ j ∈ s a, t a j := by ext simp [Classical.skolem, forall_and] end Pi section Directed theorem directedOn_iUnion {r} {f : ι → Set α} (hd : Directed (· ⊆ ·) f) (h : ∀ x, DirectedOn r (f x)) : DirectedOn r (⋃ x, f x) := by simp only [DirectedOn, mem_iUnion, exists_imp] exact fun a₁ b₁ fb₁ a₂ b₂ fb₂ => let ⟨z, zb₁, zb₂⟩ := hd b₁ b₂ let ⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂) ⟨x, ⟨z, xf⟩, xa₁, xa₂⟩ theorem directedOn_sUnion {r} {S : Set (Set α)} (hd : DirectedOn (· ⊆ ·) S) (h : ∀ x ∈ S, DirectedOn r x) : DirectedOn r (⋃₀ S) := by rw [sUnion_eq_iUnion] exact directedOn_iUnion (directedOn_iff_directed.mp hd) (fun i ↦ h i.1 i.2) theorem pairwise_iUnion₂ {S : Set (Set α)} (hd : DirectedOn (· ⊆ ·) S) (r : α → α → Prop) (h : ∀ s ∈ S, s.Pairwise r) : (⋃ s ∈ S, s).Pairwise r := by simp only [Set.Pairwise, Set.mem_iUnion, exists_prop, forall_exists_index, and_imp] intro x S hS hx y T hT hy hne obtain ⟨U, hU, hSU, hTU⟩ := hd S hS T hT exact h U hU (hSU hx) (hTU hy) hne end Directed end Set namespace Function namespace Surjective theorem iUnion_comp {f : ι → ι₂} (hf : Surjective f) (g : ι₂ → Set α) : ⋃ x, g (f x) = ⋃ y, g y := hf.iSup_comp g theorem iInter_comp {f : ι → ι₂} (hf : Surjective f) (g : ι₂ → Set α) : ⋂ x, g (f x) = ⋂ y, g y := hf.iInf_comp g end Surjective end Function /-! ### Disjoint sets -/ section Disjoint variable {s t : Set α} namespace Set @[simp] theorem disjoint_iUnion_left {ι : Sort*} {s : ι → Set α} : Disjoint (⋃ i, s i) t ↔ ∀ i, Disjoint (s i) t := iSup_disjoint_iff @[simp] theorem disjoint_iUnion_right {ι : Sort*} {s : ι → Set α} : Disjoint t (⋃ i, s i) ↔ ∀ i, Disjoint t (s i) := disjoint_iSup_iff theorem disjoint_iUnion₂_left {s : ∀ i, κ i → Set α} {t : Set α} : Disjoint (⋃ (i) (j), s i j) t ↔ ∀ i j, Disjoint (s i j) t := iSup₂_disjoint_iff theorem disjoint_iUnion₂_right {s : Set α} {t : ∀ i, κ i → Set α} : Disjoint s (⋃ (i) (j), t i j) ↔ ∀ i j, Disjoint s (t i j) := disjoint_iSup₂_iff @[simp] theorem disjoint_sUnion_left {S : Set (Set α)} {t : Set α} : Disjoint (⋃₀ S) t ↔ ∀ s ∈ S, Disjoint s t := sSup_disjoint_iff @[simp] theorem disjoint_sUnion_right {s : Set α} {S : Set (Set α)} : Disjoint s (⋃₀ S) ↔ ∀ t ∈ S, Disjoint s t := disjoint_sSup_iff lemma biUnion_compl_eq_of_pairwise_disjoint_of_iUnion_eq_univ {ι : Type*} {Es : ι → Set α} (Es_union : ⋃ i, Es i = univ) (Es_disj : Pairwise fun i j ↦ Disjoint (Es i) (Es j)) (I : Set ι) : (⋃ i ∈ I, Es i)ᶜ = ⋃ i ∈ Iᶜ, Es i := by ext x obtain ⟨i, hix⟩ : ∃ i, x ∈ Es i := by simp [← mem_iUnion, Es_union] have obs : ∀ (J : Set ι), x ∈ ⋃ j ∈ J, Es j ↔ i ∈ J := by refine fun J ↦ ⟨?_, fun i_in_J ↦ by simpa only [mem_iUnion, exists_prop] using ⟨i, i_in_J, hix⟩⟩ intro x_in_U simp only [mem_iUnion, exists_prop] at x_in_U obtain ⟨j, j_in_J, hjx⟩ := x_in_U rwa [show i = j by by_contra i_ne_j; exact Disjoint.ne_of_mem (Es_disj i_ne_j) hix hjx rfl] have obs' : ∀ (J : Set ι), x ∈ (⋃ j ∈ J, Es j)ᶜ ↔ i ∉ J := fun J ↦ by simpa only [mem_compl_iff, not_iff_not] using obs J rw [obs, obs', mem_compl_iff] end Set end Disjoint /-! ### Intervals -/ namespace Set lemma nonempty_iInter_Iic_iff [Preorder α] {f : ι → α} : (⋂ i, Iic (f i)).Nonempty ↔ BddBelow (range f) := by have : (⋂ (i : ι), Iic (f i)) = lowerBounds (range f) := by ext c; simp [lowerBounds] simp [this, BddBelow] lemma nonempty_iInter_Ici_iff [Preorder α] {f : ι → α} : (⋂ i, Ici (f i)).Nonempty ↔ BddAbove (range f) := nonempty_iInter_Iic_iff (α := αᵒᵈ) variable [CompleteLattice α] theorem Ici_iSup (f : ι → α) : Ici (⨆ i, f i) = ⋂ i, Ici (f i) := ext fun _ => by simp only [mem_Ici, iSup_le_iff, mem_iInter] theorem Iic_iInf (f : ι → α) : Iic (⨅ i, f i) = ⋂ i, Iic (f i) := ext fun _ => by simp only [mem_Iic, le_iInf_iff, mem_iInter] theorem Ici_iSup₂ (f : ∀ i, κ i → α) : Ici (⨆ (i) (j), f i j) = ⋂ (i) (j), Ici (f i j) := by simp_rw [Ici_iSup] theorem Iic_iInf₂ (f : ∀ i, κ i → α) : Iic (⨅ (i) (j), f i j) = ⋂ (i) (j), Iic (f i j) := by simp_rw [Iic_iInf] theorem Ici_sSup (s : Set α) : Ici (sSup s) = ⋂ a ∈ s, Ici a := by rw [sSup_eq_iSup, Ici_iSup₂] theorem Iic_sInf (s : Set α) : Iic (sInf s) = ⋂ a ∈ s, Iic a := by rw [sInf_eq_iInf, Iic_iInf₂] end Set namespace Set variable (t : α → Set β) theorem biUnion_diff_biUnion_subset (s₁ s₂ : Set α) : ((⋃ x ∈ s₁, t x) \ ⋃ x ∈ s₂, t x) ⊆ ⋃ x ∈ s₁ \ s₂, t x := by simp only [diff_subset_iff, ← biUnion_union] apply biUnion_subset_biUnion_left rw [union_diff_self] apply subset_union_right /-- If `t` is an indexed family of sets, then there is a natural map from `Σ i, t i` to `⋃ i, t i` sending `⟨i, x⟩` to `x`. -/ def sigmaToiUnion (x : Σ i, t i) : ⋃ i, t i := ⟨x.2, mem_iUnion.2 ⟨x.1, x.2.2⟩⟩ theorem sigmaToiUnion_surjective : Surjective (sigmaToiUnion t) | ⟨b, hb⟩ => have : ∃ a, b ∈ t a := by simpa using hb let ⟨a, hb⟩ := this ⟨⟨a, b, hb⟩, rfl⟩ theorem sigmaToiUnion_injective (h : Pairwise (Disjoint on t)) : Injective (sigmaToiUnion t) | ⟨a₁, b₁, h₁⟩, ⟨a₂, b₂, h₂⟩, eq => have b_eq : b₁ = b₂ := congr_arg Subtype.val eq have a_eq : a₁ = a₂ := by_contradiction fun ne => have : b₁ ∈ t a₁ ∩ t a₂ := ⟨h₁, b_eq.symm ▸ h₂⟩ (h ne).le_bot this Sigma.eq a_eq <| Subtype.eq <| by subst b_eq; subst a_eq; rfl theorem sigmaToiUnion_bijective (h : Pairwise (Disjoint on t)) : Bijective (sigmaToiUnion t) := ⟨sigmaToiUnion_injective t h, sigmaToiUnion_surjective t⟩ /-- Equivalence from the disjoint union of a family of sets forming a partition of `β`, to `β` itself. -/ noncomputable def sigmaEquiv (s : α → Set β) (hs : ∀ b, ∃! i, b ∈ s i) : (Σ i, s i) ≃ β where toFun | ⟨_, b⟩ => b invFun b := ⟨(hs b).choose, b, (hs b).choose_spec.1⟩ left_inv | ⟨i, b, hb⟩ => Sigma.subtype_ext ((hs b).choose_spec.2 i hb).symm rfl /-- Equivalence between a disjoint union and a dependent sum. -/ noncomputable def unionEqSigmaOfDisjoint {t : α → Set β} (h : Pairwise (Disjoint on t)) : (⋃ i, t i) ≃ Σ i, t i := (Equiv.ofBijective _ <| sigmaToiUnion_bijective t h).symm @[simp] lemma coe_unionEqSigmaOfDisjoint_symm_apply {α β : Type*} {t : α → Set β} (h : Pairwise (Disjoint on t)) (x : (i : α) × t i) : ((Set.unionEqSigmaOfDisjoint h).symm x : β) = x.2 := by rfl @[simp] lemma coe_snd_unionEqSigmaOfDisjoint {α β : Type*} {t : α → Set β} (h : Pairwise (Disjoint on t)) (x : ⋃ (i : α), t i) : ((Set.unionEqSigmaOfDisjoint h x).snd : β) = x := by conv => right; rw [← unionEqSigmaOfDisjoint h |>.symm_apply_apply x] rfl theorem iUnion_ge_eq_iUnion_nat_add (u : ℕ → Set α) (n : ℕ) : ⋃ i ≥ n, u i = ⋃ i, u (i + n) := iSup_ge_eq_iSup_nat_add u n theorem iInter_ge_eq_iInter_nat_add (u : ℕ → Set α) (n : ℕ) : ⋂ i ≥ n, u i = ⋂ i, u (i + n) := iInf_ge_eq_iInf_nat_add u n theorem _root_.Monotone.iUnion_nat_add {f : ℕ → Set α} (hf : Monotone f) (k : ℕ) : ⋃ n, f (n + k) = ⋃ n, f n := hf.iSup_nat_add k theorem _root_.Antitone.iInter_nat_add {f : ℕ → Set α} (hf : Antitone f) (k : ℕ) : ⋂ n, f (n + k) = ⋂ n, f n := hf.iInf_nat_add k @[simp] theorem iUnion_iInter_ge_nat_add (f : ℕ → Set α) (k : ℕ) : ⋃ n, ⋂ i ≥ n, f (i + k) = ⋃ n, ⋂ i ≥ n, f i := iSup_iInf_ge_nat_add f k theorem union_iUnion_nat_succ (u : ℕ → Set α) : (u 0 ∪ ⋃ i, u (i + 1)) = ⋃ i, u i := sup_iSup_nat_succ u theorem inter_iInter_nat_succ (u : ℕ → Set α) : (u 0 ∩ ⋂ i, u (i + 1)) = ⋂ i, u i := inf_iInf_nat_succ u end Set open Set variable [CompleteLattice β] theorem iSup_iUnion (s : ι → Set α) (f : α → β) : ⨆ a ∈ ⋃ i, s i, f a = ⨆ (i) (a ∈ s i), f a := by rw [iSup_comm] simp_rw [mem_iUnion, iSup_exists] theorem iInf_iUnion (s : ι → Set α) (f : α → β) : ⨅ a ∈ ⋃ i, s i, f a = ⨅ (i) (a ∈ s i), f a := iSup_iUnion (β := βᵒᵈ) s f theorem sSup_iUnion (t : ι → Set β) : sSup (⋃ i, t i) = ⨆ i, sSup (t i) := by simp_rw [sSup_eq_iSup, iSup_iUnion] theorem sSup_sUnion (s : Set (Set β)) : sSup (⋃₀ s) = ⨆ t ∈ s, sSup t := by simp only [sUnion_eq_biUnion, sSup_eq_iSup, iSup_iUnion] theorem sInf_sUnion (s : Set (Set β)) : sInf (⋃₀ s) = ⨅ t ∈ s, sInf t := sSup_sUnion (β := βᵒᵈ) s lemma iSup_sUnion (S : Set (Set α)) (f : α → β) : (⨆ x ∈ ⋃₀ S, f x) = ⨆ (s ∈ S) (x ∈ s), f x := by rw [sUnion_eq_iUnion, iSup_iUnion, ← iSup_subtype''] lemma iInf_sUnion (S : Set (Set α)) (f : α → β) : (⨅ x ∈ ⋃₀ S, f x) = ⨅ (s ∈ S) (x ∈ s), f x := by rw [sUnion_eq_iUnion, iInf_iUnion, ← iInf_subtype''] lemma forall_sUnion {S : Set (Set α)} {p : α → Prop} : (∀ x ∈ ⋃₀ S, p x) ↔ ∀ s ∈ S, ∀ x ∈ s, p x := by simp_rw [← iInf_Prop_eq, iInf_sUnion] lemma exists_sUnion {S : Set (Set α)} {p : α → Prop} : (∃ x ∈ ⋃₀ S, p x) ↔ ∃ s ∈ S, ∃ x ∈ s, p x := by simp_rw [← exists_prop, ← iSup_Prop_eq, iSup_sUnion]
HomComplex.lean
/- Copyright (c) 2023 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import Mathlib.Algebra.Category.Grp.Preadditive import Mathlib.Algebra.Homology.Homotopy import Mathlib.Algebra.Module.Pi import Mathlib.Algebra.Ring.NegOnePow import Mathlib.CategoryTheory.Linear.LinearFunctor import Mathlib.Tactic.Linarith /-! The cochain complex of homomorphisms between cochain complexes If `F` and `G` are cochain complexes (indexed by `ℤ`) in a preadditive category, there is a cochain complex of abelian groups whose `0`-cocycles identify to morphisms `F ⟶ G`. Informally, in degree `n`, this complex shall consist of cochains of degree `n` from `F` to `G`, i.e. arbitrary families for morphisms `F.X p ⟶ G.X (p + n)`. This complex shall be denoted `HomComplex F G`. In order to avoid type theoretic issues, a cochain of degree `n : ℤ` (i.e. a term of type of `Cochain F G n`) shall be defined here as the data of a morphism `F.X p ⟶ G.X q` for all triplets `⟨p, q, hpq⟩` where `p` and `q` are integers and `hpq : p + n = q`. If `α : Cochain F G n`, we shall define `α.v p q hpq : F.X p ⟶ G.X q`. We follow the signs conventions appearing in the introduction of [Brian Conrad's book *Grothendieck duality and base change*][conrad2000]. ## References * [Brian Conrad, Grothendieck duality and base change][conrad2000] -/ assert_not_exists TwoSidedIdeal open CategoryTheory Category Limits Preadditive universe v u variable {C : Type u} [Category.{v} C] [Preadditive C] {R : Type*} [Ring R] [Linear R C] namespace CochainComplex variable {F G K L : CochainComplex C ℤ} (n m : ℤ) namespace HomComplex /-- A term of type `HomComplex.Triplet n` consists of two integers `p` and `q` such that `p + n = q`. (This type is introduced so that the instance `AddCommGroup (Cochain F G n)` defined below can be found automatically.) -/ structure Triplet (n : ℤ) where /-- a first integer -/ p : ℤ /-- a second integer -/ q : ℤ /-- the condition on the two integers -/ hpq : p + n = q variable (F G) /-- A cochain of degree `n : ℤ` between to cochain complexes `F` and `G` consists of a family of morphisms `F.X p ⟶ G.X q` whenever `p + n = q`, i.e. for all triplets in `HomComplex.Triplet n`. -/ def Cochain := ∀ (T : Triplet n), F.X T.p ⟶ G.X T.q instance : AddCommGroup (Cochain F G n) := by dsimp only [Cochain] infer_instance instance : Module R (Cochain F G n) := by dsimp only [Cochain] infer_instance namespace Cochain variable {F G n} /-- A practical constructor for cochains. -/ def mk (v : ∀ (p q : ℤ) (_ : p + n = q), F.X p ⟶ G.X q) : Cochain F G n := fun ⟨p, q, hpq⟩ => v p q hpq /-- The value of a cochain on a triplet `⟨p, q, hpq⟩`. -/ def v (γ : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : F.X p ⟶ G.X q := γ ⟨p, q, hpq⟩ @[simp] lemma mk_v (v : ∀ (p q : ℤ) (_ : p + n = q), F.X p ⟶ G.X q) (p q : ℤ) (hpq : p + n = q) : (Cochain.mk v).v p q hpq = v p q hpq := rfl lemma congr_v {z₁ z₂ : Cochain F G n} (h : z₁ = z₂) (p q : ℤ) (hpq : p + n = q) : z₁.v p q hpq = z₂.v p q hpq := by subst h; rfl @[ext] lemma ext (z₁ z₂ : Cochain F G n) (h : ∀ (p q hpq), z₁.v p q hpq = z₂.v p q hpq) : z₁ = z₂ := by funext ⟨p, q, hpq⟩ apply h @[ext 1100] lemma ext₀ (z₁ z₂ : Cochain F G 0) (h : ∀ (p : ℤ), z₁.v p p (add_zero p) = z₂.v p p (add_zero p)) : z₁ = z₂ := by ext grind @[simp] lemma zero_v {n : ℤ} (p q : ℤ) (hpq : p + n = q) : (0 : Cochain F G n).v p q hpq = 0 := rfl @[simp] lemma add_v {n : ℤ} (z₁ z₂ : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : (z₁ + z₂).v p q hpq = z₁.v p q hpq + z₂.v p q hpq := rfl @[simp] lemma sub_v {n : ℤ} (z₁ z₂ : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : (z₁ - z₂).v p q hpq = z₁.v p q hpq - z₂.v p q hpq := rfl @[simp] lemma neg_v {n : ℤ} (z : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : (-z).v p q hpq = - (z.v p q hpq) := rfl @[simp] lemma smul_v {n : ℤ} (k : R) (z : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : (k • z).v p q hpq = k • (z.v p q hpq) := rfl @[simp] lemma units_smul_v {n : ℤ} (k : Rˣ) (z : Cochain F G n) (p q : ℤ) (hpq : p + n = q) : (k • z).v p q hpq = k • (z.v p q hpq) := rfl /-- A cochain of degree `0` from `F` to `G` can be constructed from a family of morphisms `F.X p ⟶ G.X p` for all `p : ℤ`. -/ def ofHoms (ψ : ∀ (p : ℤ), F.X p ⟶ G.X p) : Cochain F G 0 := Cochain.mk (fun p q hpq => ψ p ≫ eqToHom (by rw [← hpq, add_zero])) @[simp] lemma ofHoms_v (ψ : ∀ (p : ℤ), F.X p ⟶ G.X p) (p : ℤ) : (ofHoms ψ).v p p (add_zero p) = ψ p := by simp only [ofHoms, mk_v, eqToHom_refl, comp_id] @[simp] lemma ofHoms_zero : ofHoms (fun p => (0 : F.X p ⟶ G.X p)) = 0 := by cat_disch @[simp] lemma ofHoms_v_comp_d (ψ : ∀ (p : ℤ), F.X p ⟶ G.X p) (p q q' : ℤ) (hpq : p + 0 = q) : (ofHoms ψ).v p q hpq ≫ G.d q q' = ψ p ≫ G.d p q' := by rw [add_zero] at hpq subst hpq rw [ofHoms_v] @[simp] lemma d_comp_ofHoms_v (ψ : ∀ (p : ℤ), F.X p ⟶ G.X p) (p' p q : ℤ) (hpq : p + 0 = q) : F.d p' p ≫ (ofHoms ψ).v p q hpq = F.d p' q ≫ ψ q := by rw [add_zero] at hpq subst hpq rw [ofHoms_v] /-- The `0`-cochain attached to a morphism of cochain complexes. -/ def ofHom (φ : F ⟶ G) : Cochain F G 0 := ofHoms (fun p => φ.f p) variable (F G) @[simp] lemma ofHom_zero : ofHom (0 : F ⟶ G) = 0 := by simp only [ofHom, HomologicalComplex.zero_f_apply, ofHoms_zero] variable {F G} @[simp] lemma ofHom_v (φ : F ⟶ G) (p : ℤ) : (ofHom φ).v p p (add_zero p) = φ.f p := by simp only [ofHom, ofHoms_v] @[simp] lemma ofHom_v_comp_d (φ : F ⟶ G) (p q q' : ℤ) (hpq : p + 0 = q) : (ofHom φ).v p q hpq ≫ G.d q q' = φ.f p ≫ G.d p q' := by simp only [ofHom, ofHoms_v_comp_d] @[simp] lemma d_comp_ofHom_v (φ : F ⟶ G) (p' p q : ℤ) (hpq : p + 0 = q) : F.d p' p ≫ (ofHom φ).v p q hpq = F.d p' q ≫ φ.f q := by simp only [ofHom, d_comp_ofHoms_v] @[simp] lemma ofHom_add (φ₁ φ₂ : F ⟶ G) : Cochain.ofHom (φ₁ + φ₂) = Cochain.ofHom φ₁ + Cochain.ofHom φ₂ := by cat_disch @[simp] lemma ofHom_sub (φ₁ φ₂ : F ⟶ G) : Cochain.ofHom (φ₁ - φ₂) = Cochain.ofHom φ₁ - Cochain.ofHom φ₂ := by cat_disch @[simp] lemma ofHom_neg (φ : F ⟶ G) : Cochain.ofHom (-φ) = -Cochain.ofHom φ := by cat_disch /-- The cochain of degree `-1` given by an homotopy between two morphism of complexes. -/ def ofHomotopy {φ₁ φ₂ : F ⟶ G} (ho : Homotopy φ₁ φ₂) : Cochain F G (-1) := Cochain.mk (fun p q _ => ho.hom p q) @[simp] lemma ofHomotopy_ofEq {φ₁ φ₂ : F ⟶ G} (h : φ₁ = φ₂) : ofHomotopy (Homotopy.ofEq h) = 0 := rfl @[simp] lemma ofHomotopy_refl (φ : F ⟶ G) : ofHomotopy (Homotopy.refl φ) = 0 := rfl @[reassoc] lemma v_comp_XIsoOfEq_hom (γ : Cochain F G n) (p q q' : ℤ) (hpq : p + n = q) (hq' : q = q') : γ.v p q hpq ≫ (HomologicalComplex.XIsoOfEq G hq').hom = γ.v p q' (by rw [← hq', hpq]) := by subst hq' simp only [HomologicalComplex.XIsoOfEq, eqToIso_refl, Iso.refl_hom, comp_id] @[reassoc] lemma v_comp_XIsoOfEq_inv (γ : Cochain F G n) (p q q' : ℤ) (hpq : p + n = q) (hq' : q' = q) : γ.v p q hpq ≫ (HomologicalComplex.XIsoOfEq G hq').inv = γ.v p q' (by rw [hq', hpq]) := by subst hq' simp only [HomologicalComplex.XIsoOfEq, eqToIso_refl, Iso.refl_inv, comp_id] /-- The composition of cochains. -/ def comp {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : Cochain F K n₁₂ := Cochain.mk (fun p q hpq => z₁.v p (p + n₁) rfl ≫ z₂.v (p + n₁) q (by omega)) /-! If `z₁` is a cochain of degree `n₁` and `z₂` is a cochain of degree `n₂`, and that we have a relation `h : n₁ + n₂ = n₁₂`, then `z₁.comp z₂ h` is a cochain of degree `n₁₂`. The following lemma `comp_v` computes the value of this composition `z₁.comp z₂ h` on a triplet `⟨p₁, p₃, _⟩` (with `p₁ + n₁₂ = p₃`). In order to use this lemma, we need to provide an intermediate integer `p₂` such that `p₁ + n₁ = p₂`. It is advisable to use a `p₂` that has good definitional properties (i.e. `p₁ + n₁` is not always the best choice.) When `z₁` or `z₂` is a `0`-cochain, there is a better choice of `p₂`, and this leads to the two simplification lemmas `comp_zero_cochain_v` and `zero_cochain_comp_v`. -/ lemma comp_v {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) (p₁ p₂ p₃ : ℤ) (h₁ : p₁ + n₁ = p₂) (h₂ : p₂ + n₂ = p₃) : (z₁.comp z₂ h).v p₁ p₃ (by rw [← h₂, ← h₁, ← h, add_assoc]) = z₁.v p₁ p₂ h₁ ≫ z₂.v p₂ p₃ h₂ := by subst h₁; rfl @[simp] lemma comp_zero_cochain_v (z₁ : Cochain F G n) (z₂ : Cochain G K 0) (p q : ℤ) (hpq : p + n = q) : (z₁.comp z₂ (add_zero n)).v p q hpq = z₁.v p q hpq ≫ z₂.v q q (add_zero q) := comp_v z₁ z₂ (add_zero n) p q q hpq (add_zero q) @[simp] lemma zero_cochain_comp_v (z₁ : Cochain F G 0) (z₂ : Cochain G K n) (p q : ℤ) (hpq : p + n = q) : (z₁.comp z₂ (zero_add n)).v p q hpq = z₁.v p p (add_zero p) ≫ z₂.v p q hpq := comp_v z₁ z₂ (zero_add n) p p q (add_zero p) hpq /-- The associativity of the composition of cochains. -/ lemma comp_assoc {n₁ n₂ n₃ n₁₂ n₂₃ n₁₂₃ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (z₃ : Cochain K L n₃) (h₁₂ : n₁ + n₂ = n₁₂) (h₂₃ : n₂ + n₃ = n₂₃) (h₁₂₃ : n₁ + n₂ + n₃ = n₁₂₃) : (z₁.comp z₂ h₁₂).comp z₃ (show n₁₂ + n₃ = n₁₂₃ by rw [← h₁₂, h₁₂₃]) = z₁.comp (z₂.comp z₃ h₂₃) (by rw [← h₂₃, ← h₁₂₃, add_assoc]) := by substs h₁₂ h₂₃ h₁₂₃ ext p q hpq rw [comp_v _ _ rfl p (p + n₁ + n₂) q (add_assoc _ _ _).symm (by omega), comp_v z₁ z₂ rfl p (p + n₁) (p + n₁ + n₂) (by omega) (by omega), comp_v z₁ (z₂.comp z₃ rfl) (add_assoc n₁ n₂ n₃).symm p (p + n₁) q (by omega) (by omega), comp_v z₂ z₃ rfl (p + n₁) (p + n₁ + n₂) q (by omega) (by omega), assoc] /-! The formulation of the associativity of the composition of cochains given by the lemma `comp_assoc` often requires a careful selection of degrees with good definitional properties. In a few cases, like when one of the three cochains is a `0`-cochain, there are better choices, which provides the following simplification lemmas. -/ @[simp] lemma comp_assoc_of_first_is_zero_cochain {n₂ n₃ n₂₃ : ℤ} (z₁ : Cochain F G 0) (z₂ : Cochain G K n₂) (z₃ : Cochain K L n₃) (h₂₃ : n₂ + n₃ = n₂₃) : (z₁.comp z₂ (zero_add n₂)).comp z₃ h₂₃ = z₁.comp (z₂.comp z₃ h₂₃) (zero_add n₂₃) := comp_assoc _ _ _ _ _ (by omega) @[simp] lemma comp_assoc_of_second_is_zero_cochain {n₁ n₃ n₁₃ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K 0) (z₃ : Cochain K L n₃) (h₁₃ : n₁ + n₃ = n₁₃) : (z₁.comp z₂ (add_zero n₁)).comp z₃ h₁₃ = z₁.comp (z₂.comp z₃ (zero_add n₃)) h₁₃ := comp_assoc _ _ _ _ _ (by omega) @[simp] lemma comp_assoc_of_third_is_zero_cochain {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (z₃ : Cochain K L 0) (h₁₂ : n₁ + n₂ = n₁₂) : (z₁.comp z₂ h₁₂).comp z₃ (add_zero n₁₂) = z₁.comp (z₂.comp z₃ (add_zero n₂)) h₁₂ := comp_assoc _ _ _ _ _ (by omega) @[simp] lemma comp_assoc_of_second_degree_eq_neg_third_degree {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K (-n₂)) (z₃ : Cochain K L n₂) (h₁₂ : n₁ + (-n₂) = n₁₂) : (z₁.comp z₂ h₁₂).comp z₃ (show n₁₂ + n₂ = n₁ by rw [← h₁₂, add_assoc, neg_add_cancel, add_zero]) = z₁.comp (z₂.comp z₃ (neg_add_cancel n₂)) (add_zero n₁) := comp_assoc _ _ _ _ _ (by omega) @[simp] protected lemma zero_comp {n₁ n₂ n₁₂ : ℤ} (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (0 : Cochain F G n₁).comp z₂ h = 0 := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), zero_v, zero_comp] @[simp] protected lemma add_comp {n₁ n₂ n₁₂ : ℤ} (z₁ z₁' : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (z₁ + z₁').comp z₂ h = z₁.comp z₂ h + z₁'.comp z₂ h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), add_v, add_comp] @[simp] protected lemma sub_comp {n₁ n₂ n₁₂ : ℤ} (z₁ z₁' : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (z₁ - z₁').comp z₂ h = z₁.comp z₂ h - z₁'.comp z₂ h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), sub_v, sub_comp] @[simp] protected lemma neg_comp {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (-z₁).comp z₂ h = -z₁.comp z₂ h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), neg_v, neg_comp] @[simp] protected lemma smul_comp {n₁ n₂ n₁₂ : ℤ} (k : R) (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (k • z₁).comp z₂ h = k • (z₁.comp z₂ h) := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), smul_v, Linear.smul_comp] @[simp] lemma units_smul_comp {n₁ n₂ n₁₂ : ℤ} (k : Rˣ) (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : (k • z₁).comp z₂ h = k • (z₁.comp z₂ h) := by apply Cochain.smul_comp @[simp] protected lemma id_comp {n : ℤ} (z₂ : Cochain F G n) : (Cochain.ofHom (𝟙 F)).comp z₂ (zero_add n) = z₂ := by ext p q hpq simp only [zero_cochain_comp_v, ofHom_v, HomologicalComplex.id_f, id_comp] @[simp] protected lemma comp_zero {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (h : n₁ + n₂ = n₁₂) : z₁.comp (0 : Cochain G K n₂) h = 0 := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), zero_v, comp_zero] @[simp] protected lemma comp_add {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ z₂' : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : z₁.comp (z₂ + z₂') h = z₁.comp z₂ h + z₁.comp z₂' h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), add_v, comp_add] @[simp] protected lemma comp_sub {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ z₂' : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : z₁.comp (z₂ - z₂') h = z₁.comp z₂ h - z₁.comp z₂' h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), sub_v, comp_sub] @[simp] protected lemma comp_neg {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : z₁.comp (-z₂) h = -z₁.comp z₂ h := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), neg_v, comp_neg] @[simp] protected lemma comp_smul {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (k : R) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : z₁.comp (k • z₂) h = k • (z₁.comp z₂ h) := by ext p q hpq simp only [comp_v _ _ h p _ q rfl (by omega), smul_v, Linear.comp_smul] @[simp] lemma comp_units_smul {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (k : Rˣ) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) : z₁.comp (k • z₂) h = k • (z₁.comp z₂ h) := by apply Cochain.comp_smul @[simp] protected lemma comp_id {n : ℤ} (z₁ : Cochain F G n) : z₁.comp (Cochain.ofHom (𝟙 G)) (add_zero n) = z₁ := by ext p q hpq simp only [comp_zero_cochain_v, ofHom_v, HomologicalComplex.id_f, comp_id] @[simp] lemma ofHoms_comp (φ : ∀ (p : ℤ), F.X p ⟶ G.X p) (ψ : ∀ (p : ℤ), G.X p ⟶ K.X p) : (ofHoms φ).comp (ofHoms ψ) (zero_add 0) = ofHoms (fun p => φ p ≫ ψ p) := by cat_disch @[simp] lemma ofHom_comp (f : F ⟶ G) (g : G ⟶ K) : ofHom (f ≫ g) = (ofHom f).comp (ofHom g) (zero_add 0) := by simp only [ofHom, HomologicalComplex.comp_f, ofHoms_comp] variable (K) /-- The differential on a cochain complex, as a cochain of degree `1`. -/ def diff : Cochain K K 1 := Cochain.mk (fun p q _ => K.d p q) @[simp] lemma diff_v (p q : ℤ) (hpq : p + 1 = q) : (diff K).v p q hpq = K.d p q := rfl end Cochain variable {F G} /-- The differential on the complex of morphisms between cochain complexes. -/ def δ (z : Cochain F G n) : Cochain F G m := Cochain.mk (fun p q hpq => z.v p (p + n) rfl ≫ G.d (p + n) q + m.negOnePow • F.d p (p + m - n) ≫ z.v (p + m - n) q (by rw [hpq, sub_add_cancel])) /-! Similarly as for the composition of cochains, if `z : Cochain F G n`, we usually need to carefully select intermediate indices with good definitional properties in order to obtain a suitable expansion of the morphisms which constitute `δ n m z : Cochain F G m` (when `n + 1 = m`, otherwise it shall be zero). The basic equational lemma is `δ_v` below. -/ lemma δ_v (hnm : n + 1 = m) (z : Cochain F G n) (p q : ℤ) (hpq : p + m = q) (q₁ q₂ : ℤ) (hq₁ : q₁ = q - 1) (hq₂ : p + 1 = q₂) : (δ n m z).v p q hpq = z.v p q₁ (by rw [hq₁, ← hpq, ← hnm, ← add_assoc, add_sub_cancel_right]) ≫ G.d q₁ q + m.negOnePow • F.d p q₂ ≫ z.v q₂ q (by rw [← hq₂, add_assoc, add_comm 1, hnm, hpq]) := by obtain rfl : q₁ = p + n := by omega obtain rfl : q₂ = p + m - n := by omega rfl lemma δ_shape (hnm : ¬ n + 1 = m) (z : Cochain F G n) : δ n m z = 0 := by ext p q hpq dsimp only [δ] rw [Cochain.mk_v, Cochain.zero_v, F.shape, G.shape, comp_zero, zero_add, zero_comp, smul_zero] all_goals simp only [ComplexShape.up_Rel] exact fun _ => hnm (by omega) variable (F G) (R) /-- The differential on the complex of morphisms between cochain complexes, as a linear map. -/ @[simps!] def δ_hom : Cochain F G n →ₗ[R] Cochain F G m where toFun := δ n m map_add' α β := by by_cases h : n + 1 = m · ext p q hpq dsimp simp only [δ_v n m h _ p q hpq _ _ rfl rfl, Cochain.add_v, add_comp, comp_add, smul_add] abel · simp only [δ_shape _ _ h, add_zero] map_smul' r a := by by_cases h : n + 1 = m · ext p q hpq dsimp simp only [δ_v n m h _ p q hpq _ _ rfl rfl, Cochain.smul_v, Linear.comp_smul, Linear.smul_comp, smul_add, smul_comm m.negOnePow r] · simp only [δ_shape _ _ h, smul_zero] variable {F G R} @[simp] lemma δ_add (z₁ z₂ : Cochain F G n) : δ n m (z₁ + z₂) = δ n m z₁ + δ n m z₂ := (δ_hom ℤ F G n m).map_add z₁ z₂ @[simp] lemma δ_sub (z₁ z₂ : Cochain F G n) : δ n m (z₁ - z₂) = δ n m z₁ - δ n m z₂ := (δ_hom ℤ F G n m).map_sub z₁ z₂ @[simp] lemma δ_zero : δ n m (0 : Cochain F G n) = 0 := (δ_hom ℤ F G n m).map_zero @[simp] lemma δ_neg (z : Cochain F G n) : δ n m (-z) = - δ n m z := (δ_hom ℤ F G n m).map_neg z @[simp] lemma δ_smul (k : R) (z : Cochain F G n) : δ n m (k • z) = k • δ n m z := (δ_hom R F G n m).map_smul k z @[simp] lemma δ_units_smul (k : Rˣ) (z : Cochain F G n) : δ n m (k • z) = k • δ n m z := δ_smul .. lemma δ_δ (n₀ n₁ n₂ : ℤ) (z : Cochain F G n₀) : δ n₁ n₂ (δ n₀ n₁ z) = 0 := by by_cases h₁₂ : n₁ + 1 = n₂; swap · rw [δ_shape _ _ h₁₂] by_cases h₀₁ : n₀ + 1 = n₁; swap · rw [δ_shape _ _ h₀₁, δ_zero] ext p q hpq dsimp simp only [δ_v n₁ n₂ h₁₂ _ p q hpq _ _ rfl rfl, δ_v n₀ n₁ h₀₁ z p (q-1) (by omega) (q-2) _ (by omega) rfl, δ_v n₀ n₁ h₀₁ z (p+1) q (by omega) _ (p+2) rfl (by omega), ← h₁₂, Int.negOnePow_succ, add_comp, assoc, HomologicalComplex.d_comp_d, comp_zero, zero_add, comp_add, HomologicalComplex.d_comp_d_assoc, zero_comp, smul_zero, add_zero, add_neg_cancel, Units.neg_smul, Linear.units_smul_comp, Linear.comp_units_smul] lemma δ_comp {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) (m₁ m₂ m₁₂ : ℤ) (h₁₂ : n₁₂ + 1 = m₁₂) (h₁ : n₁ + 1 = m₁) (h₂ : n₂ + 1 = m₂) : δ n₁₂ m₁₂ (z₁.comp z₂ h) = z₁.comp (δ n₂ m₂ z₂) (by rw [← h₁₂, ← h₂, ← h, add_assoc]) + n₂.negOnePow • (δ n₁ m₁ z₁).comp z₂ (by rw [← h₁₂, ← h₁, ← h, add_assoc, add_comm 1, add_assoc]) := by subst h₁₂ h₁ h₂ h ext p q hpq dsimp rw [z₁.comp_v _ (add_assoc n₁ n₂ 1).symm p _ q rfl (by omega), Cochain.comp_v _ _ (show n₁ + 1 + n₂ = n₁ + n₂ + 1 by omega) p (p+n₁+1) q (by omega) (by omega), δ_v (n₁ + n₂) _ rfl (z₁.comp z₂ rfl) p q hpq (p + n₁ + n₂) _ (by omega) rfl, z₁.comp_v z₂ rfl p _ _ rfl rfl, z₁.comp_v z₂ rfl (p+1) (p+n₁+1) q (by omega) (by omega), δ_v n₂ (n₂+1) rfl z₂ (p+n₁) q (by omega) (p+n₁+n₂) _ (by omega) rfl, δ_v n₁ (n₁+1) rfl z₁ p (p+n₁+1) (by omega) (p+n₁) _ (by omega) rfl] simp only [assoc, comp_add, add_comp, Int.negOnePow_succ, Int.negOnePow_add n₁ n₂, Units.neg_smul, comp_neg, neg_comp, smul_neg, smul_smul, Linear.units_smul_comp, mul_comm n₁.negOnePow n₂.negOnePow, Linear.comp_units_smul, smul_add] abel lemma δ_zero_cochain_comp {n₂ : ℤ} (z₁ : Cochain F G 0) (z₂ : Cochain G K n₂) (m₂ : ℤ) (h₂ : n₂ + 1 = m₂) : δ n₂ m₂ (z₁.comp z₂ (zero_add n₂)) = z₁.comp (δ n₂ m₂ z₂) (zero_add m₂) + n₂.negOnePow • ((δ 0 1 z₁).comp z₂ (by rw [add_comm, h₂])) := δ_comp z₁ z₂ (zero_add n₂) 1 m₂ m₂ h₂ (zero_add 1) h₂ lemma δ_comp_zero_cochain {n₁ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K 0) (m₁ : ℤ) (h₁ : n₁ + 1 = m₁) : δ n₁ m₁ (z₁.comp z₂ (add_zero n₁)) = z₁.comp (δ 0 1 z₂) h₁ + (δ n₁ m₁ z₁).comp z₂ (add_zero m₁) := by simp only [δ_comp z₁ z₂ (add_zero n₁) m₁ 1 m₁ h₁ h₁ (zero_add 1), one_smul, Int.negOnePow_zero] @[simp] lemma δ_zero_cochain_v (z : Cochain F G 0) (p q : ℤ) (hpq : p + 1 = q) : (δ 0 1 z).v p q hpq = z.v p p (add_zero p) ≫ G.d p q - F.d p q ≫ z.v q q (add_zero q) := by simp only [δ_v 0 1 (zero_add 1) z p q hpq p q (by omega) hpq, Int.negOnePow_one, Units.neg_smul, one_smul, sub_eq_add_neg] @[simp] lemma δ_ofHom {p : ℤ} (φ : F ⟶ G) : δ 0 p (Cochain.ofHom φ) = 0 := by by_cases h : p = 1 · subst h ext simp · rw [δ_shape] omega @[simp] lemma δ_ofHomotopy {φ₁ φ₂ : F ⟶ G} (h : Homotopy φ₁ φ₂) : δ (-1) 0 (Cochain.ofHomotopy h) = Cochain.ofHom φ₁ - Cochain.ofHom φ₂ := by ext p have eq := h.comm p rw [dNext_eq h.hom (show (ComplexShape.up ℤ).Rel p (p+1) by simp), prevD_eq h.hom (show (ComplexShape.up ℤ).Rel (p-1) p by simp)] at eq rw [Cochain.ofHomotopy, δ_v (-1) 0 (neg_add_cancel 1) _ p p (add_zero p) (p-1) (p+1) rfl rfl] simp only [Cochain.mk_v, one_smul, Int.negOnePow_zero, Cochain.sub_v, Cochain.ofHom_v, eq] abel lemma δ_neg_one_cochain (z : Cochain F G (-1)) : δ (-1) 0 z = Cochain.ofHom (Homotopy.nullHomotopicMap' (fun i j hij => z.v i j (by dsimp at hij; rw [← hij, add_neg_cancel_right]))) := by ext p rw [δ_v (-1) 0 (neg_add_cancel 1) _ p p (add_zero p) (p-1) (p+1) rfl rfl] simp only [one_smul, Cochain.ofHom_v, Int.negOnePow_zero] rw [Homotopy.nullHomotopicMap'_f (show (ComplexShape.up ℤ).Rel (p-1) p by simp) (show (ComplexShape.up ℤ).Rel p (p+1) by simp)] abel end HomComplex variable (F G) open HomComplex /-- The cochain complex of homomorphisms between two cochain complexes `F` and `G`. In degree `n : ℤ`, it consists of the abelian group `HomComplex.Cochain F G n`. -/ @[simps! X d_hom_apply] def HomComplex : CochainComplex AddCommGrp ℤ where X i := AddCommGrp.of (Cochain F G i) d i j := AddCommGrp.ofHom (δ_hom ℤ F G i j) shape _ _ hij := by ext; simp [δ_shape _ _ hij] d_comp_d' _ _ _ _ _ := by ext; simp [δ_δ] namespace HomComplex /-- The subgroup of cocycles in `Cochain F G n`. -/ def cocycle : AddSubgroup (Cochain F G n) := AddMonoidHom.ker (δ_hom ℤ F G n (n + 1)).toAddMonoidHom /-- The type of `n`-cocycles, as a subtype of `Cochain F G n`. -/ def Cocycle : Type v := cocycle F G n instance : AddCommGroup (Cocycle F G n) := by dsimp only [Cocycle] infer_instance namespace Cocycle variable {F G} lemma mem_iff (hnm : n + 1 = m) (z : Cochain F G n) : z ∈ cocycle F G n ↔ δ n m z = 0 := by subst hnm; rfl variable {n} instance : Coe (Cocycle F G n) (Cochain F G n) where coe x := x.1 @[ext] lemma ext (z₁ z₂ : Cocycle F G n) (h : (z₁ : Cochain F G n) = z₂) : z₁ = z₂ := Subtype.ext h instance : SMul R (Cocycle F G n) where smul r z := ⟨r • z.1, by have hz := z.2 rw [mem_iff n (n + 1) rfl] at hz ⊢ simp only [δ_smul, hz, smul_zero]⟩ variable (F G n) @[simp] lemma coe_zero : (↑(0 : Cocycle F G n) : Cochain F G n) = 0 := by rfl variable {F G n} @[simp] lemma coe_add (z₁ z₂ : Cocycle F G n) : (↑(z₁ + z₂) : Cochain F G n) = (z₁ : Cochain F G n) + (z₂ : Cochain F G n) := rfl @[simp] lemma coe_neg (z : Cocycle F G n) : (↑(-z) : Cochain F G n) = -(z : Cochain F G n) := rfl @[simp] lemma coe_smul (z : Cocycle F G n) (x : R) : (↑(x • z) : Cochain F G n) = x • (z : Cochain F G n) := rfl @[simp] lemma coe_units_smul (z : Cocycle F G n) (x : Rˣ) : (↑(x • z) : Cochain F G n) = x • (z : Cochain F G n) := rfl @[simp] lemma coe_sub (z₁ z₂ : Cocycle F G n) : (↑(z₁ - z₂) : Cochain F G n) = (z₁ : Cochain F G n) - (z₂ : Cochain F G n) := rfl instance : Module R (Cocycle F G n) where one_smul _ := by aesop mul_smul _ _ _ := by ext; dsimp; rw [smul_smul] smul_zero _ := by aesop smul_add _ _ _ := by aesop add_smul _ _ _ := by ext; dsimp; rw [add_smul] zero_smul := by aesop /-- Constructor for `Cocycle F G n`, taking as inputs `z : Cochain F G n`, an integer `m : ℤ` such that `n + 1 = m`, and the relation `δ n m z = 0`. -/ @[simps] def mk (z : Cochain F G n) (m : ℤ) (hnm : n + 1 = m) (h : δ n m z = 0) : Cocycle F G n := ⟨z, by simpa only [mem_iff n m hnm z] using h⟩ @[simp] lemma δ_eq_zero {n : ℤ} (z : Cocycle F G n) (m : ℤ) : δ n m (z : Cochain F G n) = 0 := by by_cases h : n + 1 = m · rw [← mem_iff n m h] exact z.2 · exact δ_shape n m h _ /-- The `0`-cocycle associated to a morphism in `CochainComplex C ℤ`. -/ @[simps!] def ofHom (φ : F ⟶ G) : Cocycle F G 0 := mk (Cochain.ofHom φ) 1 (zero_add 1) (by simp) /-- The morphism in `CochainComplex C ℤ` associated to a `0`-cocycle. -/ @[simps] def homOf (z : Cocycle F G 0) : F ⟶ G where f i := (z : Cochain _ _ _).v i i (add_zero i) comm' := by rintro i j rfl rcases z with ⟨z, hz⟩ dsimp rw [mem_iff 0 1 (zero_add 1)] at hz simpa only [δ_zero_cochain_v, Cochain.zero_v, sub_eq_zero] using Cochain.congr_v hz i (i + 1) rfl @[simp] lemma homOf_ofHom_eq_self (φ : F ⟶ G) : homOf (ofHom φ) = φ := by cat_disch @[simp] lemma ofHom_homOf_eq_self (z : Cocycle F G 0) : ofHom (homOf z) = z := by cat_disch @[simp] lemma cochain_ofHom_homOf_eq_coe (z : Cocycle F G 0) : Cochain.ofHom (homOf z) = (z : Cochain F G 0) := by simpa only [Cocycle.ext_iff] using ofHom_homOf_eq_self z variable (F G) /-- The additive equivalence between morphisms in `CochainComplex C ℤ` and `0`-cocycles. -/ @[simps] def equivHom : (F ⟶ G) ≃+ Cocycle F G 0 where toFun := ofHom invFun := homOf left_inv := homOf_ofHom_eq_self right_inv := ofHom_homOf_eq_self map_add' := by cat_disch variable (K) /-- The `1`-cocycle given by the differential on a cochain complex. -/ @[simps!] def diff : Cocycle K K 1 := Cocycle.mk (Cochain.diff K) 2 rfl (by ext p q hpq simp only [Cochain.zero_v, δ_v 1 2 rfl _ p q hpq _ _ rfl rfl, Cochain.diff_v, HomologicalComplex.d_comp_d, smul_zero, add_zero]) end Cocycle variable {F G} @[simp] lemma δ_comp_zero_cocycle {n : ℤ} (z₁ : Cochain F G n) (z₂ : Cocycle G K 0) (m : ℤ) : δ n m (z₁.comp z₂.1 (add_zero n)) = (δ n m z₁).comp z₂.1 (add_zero m) := by by_cases hnm : n + 1 = m · simp [δ_comp_zero_cochain _ _ _ hnm] · simp [δ_shape _ _ hnm] @[simp] lemma δ_comp_ofHom {n : ℤ} (z₁ : Cochain F G n) (f : G ⟶ K) (m : ℤ) : δ n m (z₁.comp (Cochain.ofHom f) (add_zero n)) = (δ n m z₁).comp (Cochain.ofHom f) (add_zero m) := by rw [← Cocycle.ofHom_coe, δ_comp_zero_cocycle] @[simp] lemma δ_zero_cocycle_comp {n : ℤ} (z₁ : Cocycle F G 0) (z₂ : Cochain G K n) (m : ℤ) : δ n m (z₁.1.comp z₂ (zero_add n)) = z₁.1.comp (δ n m z₂) (zero_add m) := by by_cases hnm : n + 1 = m · simp [δ_zero_cochain_comp _ _ _ hnm] · simp [δ_shape _ _ hnm] @[simp] lemma δ_ofHom_comp {n : ℤ} (f : F ⟶ G) (z : Cochain G K n) (m : ℤ) : δ n m ((Cochain.ofHom f).comp z (zero_add n)) = (Cochain.ofHom f).comp (δ n m z) (zero_add m) := by rw [← Cocycle.ofHom_coe, δ_zero_cocycle_comp] namespace Cochain /-- Given two morphisms of complexes `φ₁ φ₂ : F ⟶ G`, the datum of an homotopy between `φ₁` and `φ₂` is equivalent to the datum of a `1`-cochain `z` such that `δ (-1) 0 z` is the difference of the zero cochains associated to `φ₂` and `φ₁`. -/ @[simps] def equivHomotopy (φ₁ φ₂ : F ⟶ G) : Homotopy φ₁ φ₂ ≃ { z : Cochain F G (-1) // Cochain.ofHom φ₁ = δ (-1) 0 z + Cochain.ofHom φ₂ } where toFun ho := ⟨Cochain.ofHomotopy ho, by simp only [δ_ofHomotopy, sub_add_cancel]⟩ invFun z := { hom := fun i j => if hij : i + (-1) = j then z.1.v i j hij else 0 zero := fun i j (hij : j + 1 ≠ i) => dif_neg (fun _ => hij (by omega)) comm := fun p => by have eq := Cochain.congr_v z.2 p p (add_zero p) have h₁ : (ComplexShape.up ℤ).Rel (p - 1) p := by simp have h₂ : (ComplexShape.up ℤ).Rel p (p + 1) := by simp simp only [δ_neg_one_cochain, Cochain.ofHom_v, ComplexShape.up_Rel, Cochain.add_v, Homotopy.nullHomotopicMap'_f h₁ h₂] at eq rw [dNext_eq _ h₂, prevD_eq _ h₁, eq, dif_pos, dif_pos] } left_inv := fun ho => by ext i j dsimp split_ifs with h · rfl · rw [ho.zero i j (fun h' => h (by dsimp at h'; omega))] right_inv := fun z => by ext p q hpq dsimp [Cochain.ofHomotopy] rw [dif_pos hpq] @[simp] lemma equivHomotopy_apply_of_eq {φ₁ φ₂ : F ⟶ G} (h : φ₁ = φ₂) : (equivHomotopy _ _ (Homotopy.ofEq h)).1 = 0 := rfl lemma ofHom_injective {f₁ f₂ : F ⟶ G} (h : ofHom f₁ = ofHom f₂) : f₁ = f₂ := (Cocycle.equivHom F G).injective (by ext1; exact h) end Cochain section variable {n} {D : Type*} [Category D] [Preadditive D] (z z' : Cochain K L n) (f : K ⟶ L) (Φ : C ⥤ D) [Φ.Additive] namespace Cochain /-- If `Φ : C ⥤ D` is an additive functor, a cochain `z : Cochain K L n` between cochain complexes in `C` can be mapped to a cochain between the cochain complexes in `D` obtained by applying the functor `Φ.mapHomologicalComplex _ : CochainComplex C ℤ ⥤ CochainComplex D ℤ`. -/ def map : Cochain ((Φ.mapHomologicalComplex _).obj K) ((Φ.mapHomologicalComplex _).obj L) n := Cochain.mk (fun p q hpq => Φ.map (z.v p q hpq)) @[simp] lemma map_v (p q : ℤ) (hpq : p + n = q) : (z.map Φ).v p q hpq = Φ.map (z.v p q hpq) := rfl @[simp] protected lemma map_add : (z + z').map Φ = z.map Φ + z'.map Φ := by cat_disch @[simp] protected lemma map_neg : (-z).map Φ = -z.map Φ := by cat_disch @[simp] protected lemma map_sub : (z - z').map Φ = z.map Φ - z'.map Φ := by cat_disch variable (K L n) @[simp] protected lemma map_zero : (0 : Cochain K L n).map Φ = 0 := by cat_disch @[simp] lemma map_comp {n₁ n₂ n₁₂ : ℤ} (z₁ : Cochain F G n₁) (z₂ : Cochain G K n₂) (h : n₁ + n₂ = n₁₂) (Φ : C ⥤ D) [Φ.Additive] : (Cochain.comp z₁ z₂ h).map Φ = Cochain.comp (z₁.map Φ) (z₂.map Φ) h := by ext p q hpq dsimp simp only [map_v, comp_v _ _ h p _ q rfl (by omega), Φ.map_comp] @[simp] lemma map_ofHom : (Cochain.ofHom f).map Φ = Cochain.ofHom ((Φ.mapHomologicalComplex _).map f) := by cat_disch end Cochain variable (n) @[simp] lemma δ_map : δ n m (z.map Φ) = (δ n m z).map Φ := by by_cases hnm : n + 1 = m · ext p q hpq dsimp simp only [δ_v n m hnm _ p q hpq (q-1) (p+1) rfl rfl, Functor.map_add, Functor.map_comp, Functor.map_units_smul, Cochain.map_v, Functor.mapHomologicalComplex_obj_d] · simp only [δ_shape _ _ hnm, Cochain.map_zero] end end HomComplex end CochainComplex
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, Mario Carneiro, Yury Kudryashov -/ import Mathlib.Topology.Algebra.InfiniteSum.Defs import Mathlib.Topology.Order.Real /-! # Definitions of an outer measure and the corresponding `FunLike` class In this file we define `MeasureTheory.OuterMeasure α` to be the type of outer measures on `α`. An outer measure is a function `μ : Set α → ℝ≥0∞`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. We also define a typeclass `MeasureTheory.OuterMeasureClass`. ## References <https://en.wikipedia.org/wiki/Outer_measure> ## Tags outer measure -/ assert_not_exists Module.Basis IsTopologicalRing UniformSpace open scoped ENNReal variable {α : Type*} namespace MeasureTheory open scoped Function -- required for scoped `on` notation /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure OuterMeasure (α : Type*) where /-- Outer measure function. Use automatic coercion instead. -/ protected measureOf : Set α → ℝ≥0∞ protected empty : measureOf ∅ = 0 protected mono : ∀ {s₁ s₂}, s₁ ⊆ s₂ → measureOf s₁ ≤ measureOf s₂ protected iUnion_nat : ∀ s : ℕ → Set α, Pairwise (Disjoint on s) → measureOf (⋃ i, s i) ≤ ∑' i, measureOf (s i) /-- A mixin class saying that elements `μ : F` are outer measures on `α`. This typeclass is used to unify some API for outer measures and measures. -/ class OuterMeasureClass (F : Type*) (α : outParam Type*) [FunLike F (Set α) ℝ≥0∞] : Prop where protected measure_empty (f : F) : f ∅ = 0 protected measure_mono (f : F) {s t} : s ⊆ t → f s ≤ f t protected measure_iUnion_nat_le (f : F) (s : ℕ → Set α) : Pairwise (Disjoint on s) → f (⋃ i, s i) ≤ ∑' i, f (s i) namespace OuterMeasure instance : FunLike (OuterMeasure α) (Set α) ℝ≥0∞ where coe m := m.measureOf coe_injective' | ⟨_, _, _, _⟩, ⟨_, _, _, _⟩, rfl => rfl @[simp] theorem measureOf_eq_coe (m : OuterMeasure α) : m.measureOf = m := rfl instance : OuterMeasureClass (OuterMeasure α) α where measure_empty f := f.empty measure_mono f := f.mono measure_iUnion_nat_le f := f.iUnion_nat end OuterMeasure end MeasureTheory
FunctorCategory.lean
/- Copyright (c) 2024 Dagur Asgeirsson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Dagur Asgeirsson -/ import Mathlib.CategoryTheory.Abelian.GrothendieckAxioms.Basic /-! # AB axioms in functor categories This file proves that, when the relevant limits and colimits exist, exactness of limits and colimits carries over from `A` to the functor category `C ⥤ A` -/ namespace CategoryTheory open CategoryTheory Limits Opposite variable {A C J : Type*} [Category A] [Category C] [Category J] instance [HasColimitsOfShape J A] [HasExactColimitsOfShape J A] [HasFiniteLimits A] : HasExactColimitsOfShape J (C ⥤ A) where preservesFiniteLimits := { preservesFiniteLimits _ := inferInstance } instance [HasLimitsOfShape J A] [HasExactLimitsOfShape J A] [HasFiniteColimits A] : HasExactLimitsOfShape J (C ⥤ A) where preservesFiniteColimits := { preservesFiniteColimits _ := inferInstance } end CategoryTheory
IdealSheaf.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.IdealSheaf.Subscheme deprecated_module (since := "2025-04-13")
cyclic.v
(* (c) Copyright 2006-2016 Microsoft Corporation and Inria. *) (* Distributed under the terms of CeCILL-B. *) From HB Require Import structures. From mathcomp Require Import ssreflect ssrbool ssrfun eqtype ssrnat seq choice. From mathcomp Require Import div fintype bigop prime finset fingroup morphism. From mathcomp Require Import perm automorphism quotient gproduct ssralg. From mathcomp Require Import finalg zmodp poly. (******************************************************************************) (* Properties of cyclic groups. *) (* Definitions: *) (* Defined in fingroup.v: *) (* <[x]> == the cycle (cyclic group) generated by x. *) (* #[x] == the order of x, i.e., the cardinal of <[x]>. *) (* Defined in prime.v: *) (* totient n == Euler's totient function *) (* Definitions in this file: *) (* cyclic G <=> G is a cyclic group. *) (* metacyclic G <=> G is a metacyclic group (i.e., a cyclic extension of a *) (* cyclic group). *) (* generator G x <=> x is a generator of the (cyclic) group G. *) (* Zpm x == the isomorphism mapping the additive group of integers *) (* mod #[x] to the cyclic group <[x]>. *) (* cyclem x n == the endomorphism y |-> y ^+ n of <[x]>. *) (* Zp_unitm x == the isomorphism mapping the multiplicative group of the *) (* units of the ring of integers mod #[x] to the group of *) (* automorphisms of <[x]> (i.e., Aut <[x]>). *) (* Zp_unitm x maps u to cyclem x u. *) (* eltm dvd_y_x == the smallest morphism (with domain <[x]>) mapping x to *) (* y, given a proof dvd_y_x : #[y] %| #[x]. *) (* expg_invn G k == if coprime #|G| k, the inverse of exponent k in G. *) (* Basic results for these notions, plus the classical result that any finite *) (* group isomorphic to a subgroup of a field is cyclic, hence that Aut G is *) (* cyclic when G is of prime order. *) (******************************************************************************) Set Implicit Arguments. Unset Strict Implicit. Unset Printing Implicit Defensive. Import GroupScope GRing.Theory. (***********************************************************************) (* Cyclic groups. *) (***********************************************************************) Section Cyclic. Variable gT : finGroupType. Implicit Types (a x y : gT) (A B : {set gT}) (G K H : {group gT}). Definition cyclic A := [exists x, A == <[x]>]. Lemma cyclicP A : reflect (exists x, A = <[x]>) (cyclic A). Proof. exact: exists_eqP. Qed. Lemma cycle_cyclic x : cyclic <[x]>. Proof. by apply/cyclicP; exists x. Qed. Lemma cyclic1 : cyclic [1 gT]. Proof. by rewrite -cycle1 cycle_cyclic. Qed. (***********************************************************************) (* Isomorphism with the additive group *) (***********************************************************************) Section Zpm. Variable a : gT. Definition Zpm (i : 'Z_#[a]) := a ^+ i. Lemma ZpmM : {in Zp #[a] &, {morph Zpm : x y / x * y}}. Proof. rewrite /Zpm; case: (eqVneq a 1) => [-> | nta] i j _ _. by rewrite !expg1n ?mulg1. by rewrite /= {3}Zp_cast ?order_gt1 // expg_mod_order expgD. Qed. Canonical Zpm_morphism := Morphism ZpmM. Lemma im_Zpm : Zpm @* Zp #[a] = <[a]>. Proof. apply/eqP; rewrite eq_sym eqEcard cycle_subG /= andbC morphimEdom. rewrite (leq_trans (leq_imset_card _ _)) ?card_Zp //= /Zp order_gt1. case: eqP => /= [a1 | _]; first by rewrite imset_set1 morph1 a1 set11. by apply/imsetP; exists 1%R; rewrite ?expg1 ?inE. Qed. Lemma injm_Zpm : 'injm Zpm. Proof. apply/injmP/dinjectiveP/card_uniqP. rewrite size_map -cardE card_Zp //= {7}/order -im_Zpm morphimEdom /=. by apply: eq_card => x; apply/imageP/imsetP=> [] [i Zp_i ->]; exists i. Qed. Lemma eq_expg_mod_order m n : (a ^+ m == a ^+ n) = (m == n %[mod #[a]]). Proof. have [->|] := eqVneq a 1; first by rewrite order1 !modn1 !expg1n eqxx. rewrite -order_gt1 => lt1a; have ZpT: Zp #[a] = setT by rewrite /Zp lt1a. have: injective Zpm by move=> i j; apply (injmP injm_Zpm); rewrite /= ZpT inE. move/inj_eq=> eqZ; symmetry; rewrite -(Zp_cast lt1a). by rewrite -[_ == _](eqZ (inZp m) (inZp n)) /Zpm /= Zp_cast ?expg_mod_order. Qed. Lemma eq_expg_ord d (m n : 'I_d) : d <= #[a]%g -> (a ^+ m == a ^+ n) = (m == n). Proof. by move=> d_leq; rewrite eq_expg_mod_order !modn_small// (leq_trans _ d_leq). Qed. Lemma expgD_Zp d (n m : 'Z_d) : (d > 0)%N -> #[a]%g %| d -> a ^+ (n + m)%R = a ^+ n * a ^+ m. Proof. move=> d_gt0 xdvd; apply/eqP; rewrite -expgD eq_expg_mod_order/= modn_dvdm//. by case: d d_gt0 {m n} xdvd => [|[|[]]]//= _; rewrite dvdn1 => /eqP->. Qed. Lemma Zp_isom : isom (Zp #[a]) <[a]> Zpm. Proof. by apply/isomP; rewrite injm_Zpm im_Zpm. Qed. Lemma Zp_isog : isog (Zp #[a]) <[a]>. Proof. exact: isom_isog Zp_isom. Qed. End Zpm. (***********************************************************************) (* Central and direct product of cycles *) (***********************************************************************) Lemma cyclic_abelian A : cyclic A -> abelian A. Proof. by case/cyclicP=> a ->; apply: cycle_abelian. Qed. Lemma cycleMsub a b : commute a b -> coprime #[a] #[b] -> <[a]> \subset <[a * b]>. Proof. move=> cab co_ab; apply/subsetP=> _ /cycleP[k ->]. apply/cycleP; exists (chinese #[a] #[b] k 0); symmetry. rewrite expgMn // -expg_mod_order chinese_modl // expg_mod_order. by rewrite /chinese addn0 -mulnA mulnCA expgM expg_order expg1n mulg1. Qed. Lemma cycleM a b : commute a b -> coprime #[a] #[b] -> <[a * b]> = <[a]> * <[b]>. Proof. move=> cab co_ab; apply/eqP; rewrite eqEsubset -(cent_joinEl (cents_cycle cab)). rewrite join_subG {3}cab !cycleMsub // 1?coprime_sym //. by rewrite -genM_join cycle_subG mem_gen // imset2_f ?cycle_id. Qed. Lemma cyclicM A B : cyclic A -> cyclic B -> B \subset 'C(A) -> coprime #|A| #|B| -> cyclic (A * B). Proof. move=> /cyclicP[a ->] /cyclicP[b ->]; rewrite cent_cycle cycle_subG => cab coab. by rewrite -cycleM ?cycle_cyclic //; apply/esym/cent1P. Qed. Lemma cyclicY K H : cyclic K -> cyclic H -> H \subset 'C(K) -> coprime #|K| #|H| -> cyclic (K <*> H). Proof. by move=> cycK cycH cKH coKH; rewrite cent_joinEr // cyclicM. Qed. (***********************************************************************) (* Order properties *) (***********************************************************************) Lemma order_dvdn a n : #[a] %| n = (a ^+ n == 1). Proof. by rewrite (eq_expg_mod_order a n 0) mod0n. Qed. Lemma order_inf a n : a ^+ n.+1 == 1 -> #[a] <= n.+1. Proof. by rewrite -order_dvdn; apply: dvdn_leq. Qed. Lemma order_dvdG G a : a \in G -> #[a] %| #|G|. Proof. by move=> Ga; apply: cardSg; rewrite cycle_subG. Qed. Lemma expg_cardG G a : a \in G -> a ^+ #|G| = 1. Proof. by move=> Ga; apply/eqP; rewrite -order_dvdn order_dvdG. Qed. Lemma expg_znat G x k : x \in G -> x ^+ (k%:R : 'Z_(#|G|))%R = x ^+ k. Proof. case: (eqsVneq G 1) => [-> /set1P-> | ntG Gx]; first by rewrite !expg1n. apply/eqP; rewrite val_Zp_nat ?cardG_gt1 // eq_expg_mod_order. by rewrite modn_dvdm ?order_dvdG. Qed. Lemma expg_zneg G x (k : 'Z_(#|G|)) : x \in G -> x ^+ (- k)%R = x ^- k. Proof. move=> Gx; apply/eqP; rewrite eq_sym eq_invg_mul -expgD. by rewrite -(expg_znat _ Gx) natrD natr_Zp natr_negZp subrr. Qed. Lemma nt_gen_prime G x : prime #|G| -> x \in G^# -> G :=: <[x]>. Proof. move=> Gpr /setD1P[]; rewrite -cycle_subG -cycle_eq1 => ntX sXG. apply/eqP; rewrite eqEsubset sXG andbT. by apply: contraR ntX => /(prime_TIg Gpr); rewrite (setIidPr sXG) => ->. Qed. Lemma nt_prime_order p x : prime p -> x ^+ p = 1 -> x != 1 -> #[x] = p. Proof. move=> p_pr xp ntx; apply/prime_nt_dvdP; rewrite ?order_eq1 //. by rewrite order_dvdn xp. Qed. Lemma orderXdvd a n : #[a ^+ n] %| #[a]. Proof. by apply: order_dvdG; apply: mem_cycle. Qed. Lemma orderXgcd a n : #[a ^+ n] = #[a] %/ gcdn #[a] n. Proof. apply/eqP; rewrite eqn_dvd; apply/andP; split. rewrite order_dvdn -expgM -muln_divCA_gcd //. by rewrite expgM expg_order expg1n. have [-> | n_gt0] := posnP n; first by rewrite gcdn0 divnn order_gt0 dvd1n. rewrite -(dvdn_pmul2r n_gt0) divn_mulAC ?dvdn_gcdl // dvdn_lcm. by rewrite order_dvdn mulnC expgM expg_order eqxx dvdn_mulr. Qed. Lemma orderXdiv a n : n %| #[a] -> #[a ^+ n] = #[a] %/ n. Proof. by case/dvdnP=> q defq; rewrite orderXgcd {2}defq gcdnC gcdnMl. Qed. Lemma orderXexp p m n x : #[x] = (p ^ n)%N -> #[x ^+ (p ^ m)] = (p ^ (n - m))%N. Proof. move=> ox; have [n_le_m | m_lt_n] := leqP n m. rewrite -(subnKC n_le_m) subnDA subnn expnD expgM -ox. by rewrite expg_order expg1n order1. rewrite orderXdiv ox ?dvdn_exp2l ?expnB ?(ltnW m_lt_n) //. by have:= order_gt0 x; rewrite ox expn_gt0 orbC -(ltn_predK m_lt_n). Qed. Lemma orderXpfactor p k n x : #[x ^+ (p ^ k)] = n -> prime p -> p %| n -> #[x] = (p ^ k * n)%N. Proof. move=> oxp p_pr dv_p_n. suffices pk_x: p ^ k %| #[x] by rewrite -oxp orderXdiv // mulnC divnK. rewrite pfactor_dvdn // leqNgt; apply: contraL dv_p_n => lt_x_k. rewrite -oxp -p'natE // -(subnKC (ltnW lt_x_k)) expnD expgM. rewrite (pnat_dvd (orderXdvd _ _)) // -p_part // orderXdiv ?dvdn_part //. by rewrite -{1}[#[x]](partnC p) // mulKn // part_pnat. Qed. Lemma orderXprime p n x : #[x ^+ p] = n -> prime p -> p %| n -> #[x] = (p * n)%N. Proof. exact: (@orderXpfactor p 1). Qed. Lemma orderXpnat m n x : #[x ^+ m] = n -> \pi(n).-nat m -> #[x] = (m * n)%N. Proof. move=> oxm n_m; have [m_gt0 _] := andP n_m. suffices m_x: m %| #[x] by rewrite -oxm orderXdiv // mulnC divnK. apply/dvdn_partP=> // p; rewrite mem_primes => /and3P[p_pr _ p_m]. have n_p: p \in \pi(n) by apply: (pnatP _ _ n_m). have p_oxm: p %| #[x ^+ (p ^ logn p m)]. apply: dvdn_trans (orderXdvd _ m`_p^'); rewrite -expgM -p_part ?partnC //. by rewrite oxm; rewrite mem_primes in n_p; case/and3P: n_p. by rewrite (orderXpfactor (erefl _) p_pr p_oxm) p_part // dvdn_mulr. Qed. Lemma orderM a b : commute a b -> coprime #[a] #[b] -> #[a * b] = (#[a] * #[b])%N. Proof. by move=> cab co_ab; rewrite -coprime_cardMg -?cycleM. Qed. Definition expg_invn A k := (egcdn k #|A|).1. Lemma expgK G k : coprime #|G| k -> {in G, cancel (expgn^~ k) (expgn^~ (expg_invn G k))}. Proof. move=> coGk x /order_dvdG Gx; apply/eqP. rewrite -expgM (eq_expg_mod_order _ _ 1) -(modn_dvdm 1 Gx). by rewrite -(chinese_modl coGk 1 0) /chinese mul1n addn0 modn_dvdm. Qed. Lemma cyclic_dprod K H G : K \x H = G -> cyclic K -> cyclic H -> cyclic G = coprime #|K| #|H| . Proof. case/dprodP=> _ defKH cKH tiKH cycK cycH; pose m := lcmn #|K| #|H|. apply/idP/idP=> [/cyclicP[x defG] | coKH]; last by rewrite -defKH cyclicM. rewrite /coprime -dvdn1 -(@dvdn_pmul2l m) ?lcmn_gt0 ?cardG_gt0 //. rewrite muln_lcm_gcd muln1 -TI_cardMg // defKH defG order_dvdn. have /mulsgP[y z Ky Hz ->]: x \in K * H by rewrite defKH defG cycle_id. rewrite -[1]mulg1 expgMn; last exact/commute_sym/(centsP cKH). apply/eqP; congr (_ * _); apply/eqP; rewrite -order_dvdn. exact: dvdn_trans (order_dvdG Ky) (dvdn_lcml _ _). exact: dvdn_trans (order_dvdG Hz) (dvdn_lcmr _ _). Qed. (***********************************************************************) (* Generator *) (***********************************************************************) Definition generator (A : {set gT}) a := A == <[a]>. Lemma generator_cycle a : generator <[a]> a. Proof. exact: eqxx. Qed. Lemma cycle_generator a x : generator <[a]> x -> x \in <[a]>. Proof. by move/(<[a]> =P _)->; apply: cycle_id. Qed. Lemma generator_order a b : generator <[a]> b -> #[a] = #[b]. Proof. by rewrite /order => /(<[a]> =P _)->. Qed. End Cyclic. Arguments cyclic {gT} A%_g. Arguments generator {gT} A%_g a%_g. Arguments expg_invn {gT} A%_g k%_N. Arguments cyclicP {gT A}. Prenex Implicits cyclic Zpm. (* Euler's theorem *) Theorem Euler_exp_totient a n : coprime a n -> a ^ totient n = 1 %[mod n]. Proof. (case: n => [|[|n']] //; [by rewrite !modn1 | set n := n'.+2]) => co_a_n. have{co_a_n} Ua: coprime n (inZp a : 'I_n) by rewrite coprime_sym coprime_modl. have: FinRing.unit 'Z_n Ua ^+ totient n == 1. by rewrite -card_units_Zp // -order_dvdn order_dvdG ?inE. by rewrite -2!val_eqE unit_Zp_expg /= -/n modnXm => /eqP. Qed. Section Eltm. Variables (aT rT : finGroupType) (x : aT) (y : rT). Definition eltm of #[y] %| #[x] := fun x_i => y ^+ invm (injm_Zpm x) x_i. Hypothesis dvd_y_x : #[y] %| #[x]. Lemma eltmE i : eltm dvd_y_x (x ^+ i) = y ^+ i. Proof. apply/eqP; rewrite eq_expg_mod_order. have [x_le1 | x_gt1] := leqP #[x] 1. suffices: #[y] %| 1 by rewrite dvdn1 => /eqP->; rewrite !modn1. by rewrite (dvdn_trans dvd_y_x) // dvdn1 order_eq1 -cycle_eq1 trivg_card_le1. rewrite -(expg_znat i (cycle_id x)) invmE /=; last by rewrite /Zp x_gt1 inE. by rewrite val_Zp_nat // modn_dvdm. Qed. Lemma eltm_id : eltm dvd_y_x x = y. Proof. exact: (eltmE 1). Qed. Lemma eltmM : {in <[x]> &, {morph eltm dvd_y_x : x_i x_j / x_i * x_j}}. Proof. move=> _ _ /cycleP[i ->] /cycleP[j ->]. by apply/eqP; rewrite -expgD !eltmE expgD. Qed. Canonical eltm_morphism := Morphism eltmM. Lemma im_eltm : eltm dvd_y_x @* <[x]> = <[y]>. Proof. by rewrite morphim_cycle ?cycle_id //= eltm_id. Qed. Lemma ker_eltm : 'ker (eltm dvd_y_x) = <[x ^+ #[y]]>. Proof. apply/eqP; rewrite eq_sym eqEcard cycle_subG 3!inE mem_cycle /= eltmE. rewrite expg_order eqxx (orderE y) -im_eltm card_morphim setIid -orderE. by rewrite orderXdiv ?dvdn_indexg //= leq_divRL ?indexg_gt0 ?Lagrange ?subsetIl. Qed. Lemma injm_eltm : 'injm (eltm dvd_y_x) = (#[x] %| #[y]). Proof. by rewrite ker_eltm subG1 cycle_eq1 -order_dvdn. Qed. End Eltm. Section CycleSubGroup. Variable gT : finGroupType. (* Gorenstein, 1.3.1 (i) *) Lemma cycle_sub_group (a : gT) m : m %| #[a] -> [set H : {group gT} | H \subset <[a]> & #|H| == m] = [set <[a ^+ (#[a] %/ m)]>%G]. Proof. move=> m_dv_a; have m_gt0: 0 < m by apply: dvdn_gt0 m_dv_a. have oam: #|<[a ^+ (#[a] %/ m)]>| = m. apply/eqP; rewrite [#|_|]orderXgcd -(divnMr m_gt0) muln_gcdl divnK //. by rewrite gcdnC gcdnMr mulKn. apply/eqP; rewrite eqEsubset sub1set inE /= cycleX oam eqxx !andbT. apply/subsetP=> X; rewrite in_set1 inE -val_eqE /= eqEcard oam. case/andP=> sXa /eqP oX; rewrite oX leqnn andbT. apply/subsetP=> x Xx; case/cycleP: (subsetP sXa _ Xx) => k def_x. have: (x ^+ m == 1)%g by rewrite -oX -order_dvdn cardSg // gen_subG sub1set. rewrite {x Xx}def_x -expgM -order_dvdn -[#[a]](Lagrange sXa) -oX mulnC. rewrite dvdn_pmul2r // mulnK // => /dvdnP[i ->]. by rewrite mulnC expgM groupX // cycle_id. Qed. Lemma cycle_subgroup_char a (H : {group gT}) : H \subset <[a]> -> H \char <[a]>. Proof. move=> sHa; apply: lone_subgroup_char => // J sJa isoJH. have dvHa: #|H| %| #[a] by apply: cardSg. have{dvHa} /setP Huniq := esym (cycle_sub_group dvHa). move: (Huniq H) (Huniq J); rewrite !inE /=. by rewrite sHa sJa (card_isog isoJH) eqxx => /eqP<- /eqP<-. Qed. End CycleSubGroup. (***********************************************************************) (* Reflected boolean property and morphic image, injection, bijection *) (***********************************************************************) Section MorphicImage. Variables aT rT : finGroupType. Variables (D : {group aT}) (f : {morphism D >-> rT}) (x : aT). Hypothesis Dx : x \in D. Lemma morph_order : #[f x] %| #[x]. Proof. by rewrite order_dvdn -morphX // expg_order morph1. Qed. Lemma morph_generator A : generator A x -> generator (f @* A) (f x). Proof. by move/(A =P _)->; rewrite /generator morphim_cycle. Qed. End MorphicImage. Section CyclicProps. Variables gT : finGroupType. Implicit Types (aT rT : finGroupType) (G H K : {group gT}). Lemma cyclicS G H : H \subset G -> cyclic G -> cyclic H. Proof. move=> sHG /cyclicP[x defG]; apply/cyclicP. exists (x ^+ (#[x] %/ #|H|)); apply/congr_group/set1P. by rewrite -cycle_sub_group /order -defG ?cardSg // inE sHG eqxx. Qed. Lemma cyclicJ G x : cyclic (G :^ x) = cyclic G. Proof. apply/cyclicP/cyclicP=> [[y /(canRL (conjsgK x))] | [y ->]]. by rewrite -cycleJ; exists (y ^ x^-1). by exists (y ^ x); rewrite cycleJ. Qed. Lemma eq_subG_cyclic G H K : cyclic G -> H \subset G -> K \subset G -> (H :==: K) = (#|H| == #|K|). Proof. case/cyclicP=> x -> sHx sKx; apply/eqP/eqP=> [-> //| eqHK]. have def_GHx := cycle_sub_group (cardSg sHx); set GHx := [set _] in def_GHx. have []: H \in GHx /\ K \in GHx by rewrite -def_GHx !inE sHx sKx eqHK /=. by do 2!move/set1P->. Qed. Lemma cardSg_cyclic G H K : cyclic G -> H \subset G -> K \subset G -> (#|H| %| #|K|) = (H \subset K). Proof. move=> cycG sHG sKG; apply/idP/idP; last exact: cardSg. case/cyclicP: (cyclicS sKG cycG) => x defK; rewrite {K}defK in sKG *. case/dvdnP=> k ox; suffices ->: H :=: <[x ^+ k]> by apply: cycleX. apply/eqP; rewrite (eq_subG_cyclic cycG) ?(subset_trans (cycleX _ _)) //. rewrite -orderE orderXdiv orderE ox ?dvdn_mulr ?mulKn //. by have:= order_gt0 x; rewrite orderE ox; case k. Qed. Lemma sub_cyclic_char G H : cyclic G -> (H \char G) = (H \subset G). Proof. case/cyclicP=> x ->; apply/idP/idP => [/andP[] //|]. exact: cycle_subgroup_char. Qed. Lemma morphim_cyclic rT G H (f : {morphism G >-> rT}) : cyclic H -> cyclic (f @* H). Proof. move=> cycH; wlog sHG: H cycH / H \subset G. by rewrite -morphimIdom; apply; rewrite (cyclicS _ cycH, subsetIl) ?subsetIr. case/cyclicP: cycH sHG => x ->; rewrite gen_subG sub1set => Gx. by apply/cyclicP; exists (f x); rewrite morphim_cycle. Qed. Lemma quotient_cycle x H : x \in 'N(H) -> <[x]> / H = <[coset H x]>. Proof. exact: morphim_cycle. Qed. Lemma quotient_cyclic G H : cyclic G -> cyclic (G / H). Proof. exact: morphim_cyclic. Qed. Lemma quotient_generator x G H : x \in 'N(H) -> generator G x -> generator (G / H) (coset H x). Proof. by move=> Nx; apply: morph_generator. Qed. Lemma prime_cyclic G : prime #|G| -> cyclic G. Proof. case/primeP; rewrite ltnNge -trivg_card_le1. case/trivgPn=> x Gx ntx /(_ _ (order_dvdG Gx)). rewrite order_eq1 (negbTE ntx) => /eqnP oxG; apply/cyclicP. by exists x; apply/eqP; rewrite eq_sym eqEcard -oxG cycle_subG Gx leqnn. Qed. Lemma dvdn_prime_cyclic G p : prime p -> #|G| %| p -> cyclic G. Proof. move=> p_pr pG; case: (eqsVneq G 1) => [-> | ntG]; first exact: cyclic1. by rewrite prime_cyclic // (prime_nt_dvdP p_pr _ pG) -?trivg_card1. Qed. Lemma cyclic_small G : #|G| <= 3 -> cyclic G. Proof. rewrite 4!(ltnS, leq_eqVlt) -trivg_card_le1 orbA orbC. case/predU1P=> [-> | oG]; first exact: cyclic1. by apply: prime_cyclic; case/pred2P: oG => ->. Qed. End CyclicProps. Section IsoCyclic. Variables gT rT : finGroupType. Implicit Types (G H : {group gT}) (M : {group rT}). Lemma injm_cyclic G H (f : {morphism G >-> rT}) : 'injm f -> H \subset G -> cyclic (f @* H) = cyclic H. Proof. move=> injf sHG; apply/idP/idP; last exact: morphim_cyclic. by rewrite -{2}(morphim_invm injf sHG); apply: morphim_cyclic. Qed. Lemma isog_cyclic G M : G \isog M -> cyclic G = cyclic M. Proof. by case/isogP=> f injf <-; rewrite injm_cyclic. Qed. Lemma isog_cyclic_card G M : cyclic G -> isog G M = cyclic M && (#|M| == #|G|). Proof. move=> cycG; apply/idP/idP=> [isoGM | ]. by rewrite (card_isog isoGM) -(isog_cyclic isoGM) cycG /=. case/cyclicP: cycG => x ->{G} /andP[/cyclicP[y ->] /eqP oy]. by apply: isog_trans (isog_symr _) (Zp_isog y); rewrite /order oy Zp_isog. Qed. Lemma injm_generator G H (f : {morphism G >-> rT}) x : 'injm f -> x \in G -> H \subset G -> generator (f @* H) (f x) = generator H x. Proof. move=> injf Gx sHG; apply/idP/idP; last exact: morph_generator. rewrite -{2}(morphim_invm injf sHG) -{2}(invmE injf Gx). by apply: morph_generator; apply: mem_morphim. Qed. End IsoCyclic. (* Metacyclic groups. *) Section Metacyclic. Variable gT : finGroupType. Implicit Types (A : {set gT}) (G H : {group gT}). Definition metacyclic A := [exists H : {group gT}, [&& cyclic H, H <| A & cyclic (A / H)]]. Lemma metacyclicP A : reflect (exists H : {group gT}, [/\ cyclic H, H <| A & cyclic (A / H)]) (metacyclic A). Proof. exact: 'exists_and3P. Qed. Lemma metacyclic1 : metacyclic 1. Proof. by apply/existsP; exists 1%G; rewrite normal1 trivg_quotient !cyclic1. Qed. Lemma cyclic_metacyclic A : cyclic A -> metacyclic A. Proof. case/cyclicP=> x ->; apply/existsP; exists (<[x]>)%G. by rewrite normal_refl cycle_cyclic trivg_quotient cyclic1. Qed. Lemma metacyclicS G H : H \subset G -> metacyclic G -> metacyclic H. Proof. move=> sHG /metacyclicP[K [cycK nsKG cycGq]]; apply/metacyclicP. exists (H :&: K)%G; rewrite (cyclicS (subsetIr H K)) ?(normalGI sHG) //=. rewrite setIC (isog_cyclic (second_isog _)) ?(cyclicS _ cycGq) ?quotientS //. by rewrite (subset_trans sHG) ?normal_norm. Qed. End Metacyclic. Arguments metacyclic {gT} A%_g. Arguments metacyclicP {gT A}. (* Automorphisms of cyclic groups. *) Section CyclicAutomorphism. Variable gT : finGroupType. Section CycleAutomorphism. Variable a : gT. Section CycleMorphism. Variable n : nat. Definition cyclem of gT := fun x : gT => x ^+ n. Lemma cyclemM : {in <[a]> & , {morph cyclem a : x y / x * y}}. Proof. by move=> x y ax ay; apply: expgMn; apply: (centsP (cycle_abelian a)). Qed. Canonical cyclem_morphism := Morphism cyclemM. End CycleMorphism. Section ZpUnitMorphism. Variable u : {unit 'Z_#[a]}. Lemma injm_cyclem : 'injm (cyclem (val u) a). Proof. apply/subsetP=> x /setIdP[ax]; rewrite !inE -order_dvdn. have [a1 | nta] := eqVneq a 1; first by rewrite a1 cycle1 inE in ax. rewrite -order_eq1 -dvdn1; move/eqnP: (valP u) => /= <-. by rewrite dvdn_gcd [in X in X && _]Zp_cast ?order_gt1 // order_dvdG. Qed. Lemma im_cyclem : cyclem (val u) a @* <[a]> = <[a]>. Proof. apply/morphim_fixP=> //; first exact: injm_cyclem. by rewrite morphim_cycle ?cycle_id ?cycleX. Qed. Definition Zp_unitm := aut injm_cyclem im_cyclem. End ZpUnitMorphism. Lemma Zp_unitmM : {in units_Zp #[a] &, {morph Zp_unitm : u v / u * v}}. Proof. move=> u v _ _; apply: (eq_Aut (Aut_aut _ _)) => [|x a_x]. by rewrite groupM ?Aut_aut. rewrite permM !autE ?groupX //= /cyclem -expgM. rewrite -expg_mod_order modn_dvdm ?expg_mod_order //. case: (leqP #[a] 1) => [lea1 | lt1a]; last by rewrite Zp_cast ?order_dvdG. by rewrite card_le1_trivg // in a_x; rewrite (set1P a_x) order1 dvd1n. Qed. Canonical Zp_unit_morphism := Morphism Zp_unitmM. Lemma injm_Zp_unitm : 'injm Zp_unitm. Proof. have [a1 | nta] := eqVneq a 1. by rewrite subIset //= card_le1_trivg ?subxx // card_units_Zp a1 order1. apply/subsetP=> /= u /morphpreP[_ /set1P/= um1]. have{um1}: Zp_unitm u a == Zp_unitm 1 a by rewrite um1 morph1. rewrite !autE ?cycle_id // eq_expg_mod_order. by rewrite -[n in _ == _ %[mod n]]Zp_cast ?order_gt1 // !modZp inE. Qed. Lemma generator_coprime m : generator <[a]> (a ^+ m) = coprime #[a] m. Proof. rewrite /generator eq_sym eqEcard cycleX -/#[a] [#|_|]orderXgcd /=. apply/idP/idP=> [le_a_am|co_am]; last by rewrite (eqnP co_am) divn1. have am_gt0: 0 < gcdn #[a] m by rewrite gcdn_gt0 order_gt0. by rewrite /coprime eqn_leq am_gt0 andbT -(@leq_pmul2l #[a]) ?muln1 -?leq_divRL. Qed. Lemma im_Zp_unitm : Zp_unitm @* units_Zp #[a] = Aut <[a]>. Proof. rewrite morphimEdom; apply/setP=> f; pose n := invm (injm_Zpm a) (f a). apply/imsetP/idP=> [[u _ ->] | Af]; first exact: Aut_aut. have [a1 | nta] := eqVneq a 1. by rewrite a1 cycle1 Aut1 in Af; exists 1; rewrite // morph1 (set1P Af). have a_fa: <[a]> = <[f a]>. by rewrite -(autmE Af) -morphim_cycle ?im_autm ?cycle_id. have def_n: a ^+ n = f a. by rewrite -/(Zpm n) invmK // im_Zpm a_fa cycle_id. have co_a_n: coprime #[a].-2.+2 n. by rewrite {1}Zp_cast ?order_gt1 // -generator_coprime def_n; apply/eqP. exists (FinRing.unit 'Z_#[a] co_a_n); rewrite ?inE //. apply: eq_Aut (Af) (Aut_aut _ _) _ => x ax. rewrite autE //= /cyclem; case/cycleP: ax => k ->{x}. by rewrite -(autmE Af) morphX ?cycle_id //= autmE -def_n -!expgM mulnC. Qed. Lemma Zp_unit_isom : isom (units_Zp #[a]) (Aut <[a]>) Zp_unitm. Proof. by apply/isomP; rewrite ?injm_Zp_unitm ?im_Zp_unitm. Qed. Lemma Zp_unit_isog : isog (units_Zp #[a]) (Aut <[a]>). Proof. exact: isom_isog Zp_unit_isom. Qed. Lemma card_Aut_cycle : #|Aut <[a]>| = totient #[a]. Proof. by rewrite -(card_isog Zp_unit_isog) card_units_Zp. Qed. Lemma totient_gen : totient #[a] = #|[set x | generator <[a]> x]|. Proof. have [lea1 | lt1a] := leqP #[a] 1. rewrite /order card_le1_trivg // cards1 (@eq_card1 _ 1) // => x. by rewrite !inE -cycle_eq1 eq_sym. rewrite -(card_injm (injm_invm (injm_Zpm a))) /= ?im_Zpm; last first. by apply/subsetP=> x /[1!inE]; apply: cycle_generator. rewrite -card_units_Zp // cardsE card_sub morphim_invmE; apply: eq_card => /= d. by rewrite !inE /= qualifE /= /Zp lt1a inE /= generator_coprime {1}Zp_cast. Qed. Lemma Aut_cycle_abelian : abelian (Aut <[a]>). Proof. by rewrite -im_Zp_unitm morphim_abelian ?units_Zp_abelian. Qed. End CycleAutomorphism. Variable G : {group gT}. Lemma Aut_cyclic_abelian : cyclic G -> abelian (Aut G). Proof. by case/cyclicP=> x ->; apply: Aut_cycle_abelian. Qed. Lemma card_Aut_cyclic : cyclic G -> #|Aut G| = totient #|G|. Proof. by case/cyclicP=> x ->; apply: card_Aut_cycle. Qed. Lemma sum_ncycle_totient : \sum_(d < #|G|.+1) #|[set <[x]> | x in G & #[x] == d]| * totient d = #|G|. Proof. pose h (x : gT) : 'I_#|G|.+1 := inord #[x]. symmetry; rewrite -{1}sum1_card (partition_big h xpredT) //=. apply: eq_bigr => d _; set Gd := finset _. rewrite -sum_nat_const sum1dep_card -sum1_card (_ : finset _ = Gd); last first. apply/setP=> x /[!inE]; apply: andb_id2l => Gx. by rewrite /eq_op /= inordK // ltnS subset_leq_card ?cycle_subG. rewrite (partition_big_imset cycle) {}/Gd; apply: eq_bigr => C /=. case/imsetP=> x /setIdP[Gx /eqP <-] -> {C d}. rewrite sum1dep_card totient_gen; apply: eq_card => y; rewrite !inE /generator. move: Gx; rewrite andbC eq_sym -!cycle_subG /order. by case: eqP => // -> ->; rewrite eqxx. Qed. End CyclicAutomorphism. Lemma sum_totient_dvd n : \sum_(d < n.+1 | d %| n) totient d = n. Proof. case: n => [|[|n']]; try by rewrite big_mkcond !big_ord_recl big_ord0. set n := n'.+2; pose x1 : 'Z_n := 1%R. have ox1: #[x1] = n by rewrite /order -Zp_cycle card_Zp. rewrite -[rhs in _ = rhs]ox1 -[#[_]]sum_ncycle_totient [#|_|]ox1 big_mkcond /=. apply: eq_bigr => d _; rewrite -{2}ox1; case: ifP => [|ndv_dG]; last first. rewrite eq_card0 // => C; apply/imsetP=> [[x /setIdP[Gx oxd] _{C}]]. by rewrite -(eqP oxd) order_dvdG in ndv_dG. move/cycle_sub_group; set Gd := [set _] => def_Gd. rewrite (_ : _ @: _ = @gval _ @: Gd); first by rewrite imset_set1 cards1 mul1n. apply/setP=> C; apply/idP/imsetP=> [| [gC GdC ->{C}]]. case/imsetP=> x /setIdP[_ oxd] ->; exists <[x]>%G => //. by rewrite -def_Gd inE -Zp_cycle subsetT. have:= GdC; rewrite -def_Gd => /setIdP[_ /eqP <-]. by rewrite (set1P GdC) /= imset_f // inE eqxx (mem_cycle x1). Qed. Section FieldMulCyclic. (***********************************************************************) (* A classic application to finite multiplicative subgroups of fields. *) (***********************************************************************) Import GRing.Theory. Variables (gT : finGroupType) (G : {group gT}). Lemma order_inj_cyclic : {in G &, forall x y, #[x] = #[y] -> <[x]> = <[y]>} -> cyclic G. Proof. move=> ucG; apply: negbNE (contra _ (negbT (ltnn #|G|))) => ncG. rewrite -{2}[#|G|]sum_totient_dvd big_mkcond (bigD1 ord_max) ?dvdnn //=. rewrite -{1}[#|G|]sum_ncycle_totient (bigD1 ord_max) //= -addSn leq_add //. rewrite eq_card0 ?totient_gt0 ?cardG_gt0 // => C. apply/imsetP=> [[x /setIdP[Gx /eqP oxG]]]; case/cyclicP: ncG. by exists x; apply/eqP; rewrite eq_sym eqEcard cycle_subG Gx -oxG /=. elim/big_ind2: _ => // [m1 n1 m2 n2 | d _]; first exact: leq_add. set Gd := _ @: _; case: (set_0Vmem Gd) => [-> | [C]]; first by rewrite cards0. rewrite {}/Gd => /imsetP[x /setIdP[Gx /eqP <-] _ {C d}]. rewrite order_dvdG // (@eq_card1 _ <[x]>) ?mul1n // => C. apply/idP/eqP=> [|-> {C}]; last by rewrite imset_f // inE Gx eqxx. by case/imsetP=> y /setIdP[Gy /eqP/ucG->]. Qed. Lemma div_ring_mul_group_cyclic (R : unitRingType) (f : gT -> R) : f 1 = 1%R -> {in G &, {morph f : u v / u * v >-> (u * v)%R}} -> {in G^#, forall x, f x - 1 \in GRing.unit}%R -> abelian G -> cyclic G. Proof. move=> f1 fM f1P abelG. have fX n: {in G, {morph f : u / u ^+ n >-> (u ^+ n)%R}}. by case: n => // n x Gx; elim: n => //= n IHn; rewrite expgS fM ?groupX ?IHn. have fU x: x \in G -> f x \in GRing.unit. by move=> Gx; apply/unitrP; exists (f x^-1); rewrite -!fM ?groupV ?gsimp. apply: order_inj_cyclic => x y Gx Gy; set n := #[x] => yn. apply/eqP; rewrite eq_sym eqEcard -[#|_|]/n yn leqnn andbT cycle_subG /=. suff{y Gy yn} ->: <[x]> = G :&: [set z | #[z] %| n] by rewrite !inE Gy yn /=. apply/eqP; rewrite eqEcard subsetI cycle_subG {}Gx /= cardE; set rs := enum _. apply/andP; split; first by apply/subsetP=> y xy; rewrite inE order_dvdG. pose P : {poly R} := ('X^n - 1)%R; have n_gt0: n > 0 by apply: order_gt0. have szP : size P = n.+1. by rewrite size_polyDl size_polyXn ?size_polyN ?size_poly1. rewrite -ltnS -szP -(size_map f) max_ring_poly_roots -?size_poly_eq0 ?{}szP //. apply/allP=> fy /mapP[y]; rewrite mem_enum !inE order_dvdn => /andP[Gy]. move/eqP=> yn1 ->{fy}; apply/eqP. by rewrite !(hornerE, hornerXn) -fX // yn1 f1 subrr. have: uniq rs by apply: enum_uniq. have: all [in G] rs by apply/allP=> y; rewrite mem_enum; case/setIP. elim: rs => //= y rs IHrs /andP[Gy Grs] /andP[y_rs]; rewrite andbC. move/IHrs=> -> {IHrs}//; apply/allP=> _ /mapP[z rs_z ->]. have{Grs} Gz := allP Grs z rs_z; rewrite /diff_roots -!fM // (centsP abelG) //. rewrite eqxx -[f y]mul1r -(mulgKV y z) fM ?groupM ?groupV //=. rewrite -mulNr -mulrDl unitrMl ?fU ?f1P // !inE. by rewrite groupM ?groupV // andbT -eq_mulgV1; apply: contra y_rs; move/eqP <-. Qed. Lemma field_mul_group_cyclic (F : fieldType) (f : gT -> F) : {in G &, {morph f : u v / u * v >-> (u * v)%R}} -> {in G, forall x, f x = 1%R <-> x = 1} -> cyclic G. Proof. move=> fM f1P; have f1 : f 1 = 1%R by apply/f1P. apply: (div_ring_mul_group_cyclic f1 fM) => [x|]. case/setD1P=> x1 Gx; rewrite unitfE; apply: contra x1. by rewrite subr_eq0 => /eqP/f1P->. apply/centsP=> x Gx y Gy; apply/commgP/eqP. apply/f1P; rewrite ?fM ?groupM ?groupV //. by rewrite mulrCA -!fM ?groupM ?groupV // mulKg mulVg. Qed. End FieldMulCyclic. Lemma field_unit_group_cyclic (F : finFieldType) (G : {group {unit F}}) : cyclic G. Proof. apply: field_mul_group_cyclic FinRing.uval _ _ => // u _. by split=> /eqP ?; apply/eqP. Qed. Lemma units_Zp_cyclic p : prime p -> cyclic (units_Zp p). Proof. by move/pdiv_id <-; exact: field_unit_group_cyclic. Qed. Section PrimitiveRoots. Open Scope ring_scope. Import GRing.Theory. (* This subproof has been extracted out of [has_prim_root] for performance reasons. See github PR #1059 for further documentation and investigation on this problem. *) Lemma has_prim_root_subproof (F : fieldType) (n : nat) (rs : seq F) (n_gt0 : n > 0) (rsn1 : all n.-unity_root rs) (Urs : uniq rs) (sz_rs : size rs = n) (r := fun s => val (s : seq_sub rs)) (rn1 : forall x : seq_sub rs, r x ^+ n = 1) (prim_r : forall z : F, z ^+ n = 1 -> z \in rs) (r' := (fun s (e : s ^+ n = 1) => {| ssval := s; ssvalP := prim_r s e |}) : forall s : F, s ^+ n = 1 -> seq_sub rs) (sG_1 := r' 1 (expr1n F n) : seq_sub rs) (sG_VP : forall s : seq_sub rs, r s ^+ n.-1 ^+ n = 1) (sG_MP : forall s s0 : seq_sub rs, (r s * r s0) ^+ n = 1) (sG_V := (fun s : seq_sub rs => r' (r s ^+ n.-1) (sG_VP s)) : seq_sub rs -> seq_sub rs) (sG_M := (fun s s0 : seq_sub rs => r' (r s * r s0) (sG_MP s s0)) : seq_sub rs -> seq_sub rs -> seq_sub rs) (sG_Ag : associative sG_M) (sG_1g : left_id sG_1 sG_M) (sG_Vg : left_inverse sG_1 sG_V sG_M) : has n.-primitive_root rs. Proof. pose ssMG : isMulGroup (seq_sub rs) := isMulGroup.Build (seq_sub rs) sG_Ag sG_1g sG_Vg. pose gT : finGroupType := HB.pack (seq_sub rs) ssMG. have /cyclicP[x gen_x]: @cyclic gT setT. apply: (@field_mul_group_cyclic gT [set: _] F r) => // x _. by split=> [ri1 | ->]; first apply: val_inj. apply/hasP; exists (r x); first exact: (valP x). have [m prim_x dvdmn] := prim_order_exists n_gt0 (rn1 x). rewrite -((m =P n) _) // eqn_dvd {}dvdmn -sz_rs -(card_seq_sub Urs) -cardsT. rewrite gen_x (@order_dvdn gT) /(_ == _) /= -{prim_x}(prim_expr_order prim_x). by apply/eqP; elim: m => //= m IHm; rewrite exprS expgS /= -IHm. Qed. Lemma has_prim_root (F : fieldType) (n : nat) (rs : seq F) : n > 0 -> all n.-unity_root rs -> uniq rs -> size rs >= n -> has n.-primitive_root rs. Proof. move=> n_gt0 rsn1 Urs; rewrite leq_eqVlt ltnNge max_unity_roots // orbF eq_sym. move/eqP=> sz_rs; pose r := val (_ : seq_sub rs). have rn1 x: r x ^+ n = 1. by apply/eqP; rewrite -unity_rootE (allP rsn1) ?(valP x). have prim_r z: z ^+ n = 1 -> z \in rs. by move/eqP; rewrite -unity_rootE -(mem_unity_roots n_gt0). pose r' := SeqSub (prim_r _ _); pose sG_1 := r' _ (expr1n _ _). have sG_VP: r _ ^+ n.-1 ^+ n = 1. by move=> x; rewrite -exprM mulnC exprM rn1 expr1n. have sG_MP: (r _ * r _) ^+ n = 1 by move=> x y; rewrite exprMn !rn1 mul1r. pose sG_V := r' _ (sG_VP _); pose sG_M := r' _ (sG_MP _ _). have sG_Ag: associative sG_M by move=> x y z; apply: val_inj; rewrite /= mulrA. have sG_1g: left_id sG_1 sG_M by move=> x; apply: val_inj; rewrite /= mul1r. have sG_Vg: left_inverse sG_1 sG_V sG_M. by move=> x; apply: val_inj; rewrite /= -exprSr prednK ?rn1. exact: has_prim_root_subproof. Qed. End PrimitiveRoots. (***********************************************************************) (* Cycles of prime order *) (***********************************************************************) Section AutPrime. Variable gT : finGroupType. Lemma Aut_prime_cycle_cyclic (a : gT) : prime #[a] -> cyclic (Aut <[a]>). Proof. move=> pr_a; have inj_um := injm_Zp_unitm a. have /eq_S/eq_S eq_a := Fp_Zcast pr_a. pose fm := cast_ord (esym eq_a) \o val \o invm inj_um. apply: (@field_mul_group_cyclic _ _ _ fm) => [f g Af Ag | f Af] /=. by apply: val_inj; rewrite /= morphM ?im_Zp_unitm //= eq_a. split=> [/= fm1 |->]; last by apply: val_inj; rewrite /= morph1. apply: (injm1 (injm_invm inj_um)); first by rewrite /= im_Zp_unitm. by do 2!apply: val_inj; move/(congr1 val): fm1. Qed. Lemma Aut_prime_cyclic (G : {group gT}) : prime #|G| -> cyclic (Aut G). Proof. move=> pr_G; case/cyclicP: (prime_cyclic pr_G) (pr_G) => x ->. exact: Aut_prime_cycle_cyclic. Qed. End AutPrime.
Invertible.lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import Mathlib.Algebra.Order.Ring.Defs import Mathlib.Algebra.Ring.Invertible import Mathlib.Data.Nat.Cast.Order.Ring /-! # Lemmas about `invOf` in ordered (semi)rings. -/ variable {R : Type*} [Semiring R] [LinearOrder R] [IsStrictOrderedRing R] {a : R} @[simp] theorem invOf_pos [Invertible a] : 0 < ⅟a ↔ 0 < a := haveI : 0 < a * ⅟a := by simp only [mul_invOf_self, zero_lt_one] ⟨fun h => pos_of_mul_pos_left this h.le, fun h => pos_of_mul_pos_right this h.le⟩ @[simp] theorem invOf_nonpos [Invertible a] : ⅟a ≤ 0 ↔ a ≤ 0 := by simp only [← not_lt, invOf_pos] @[simp] theorem invOf_nonneg [Invertible a] : 0 ≤ ⅟a ↔ 0 ≤ a := haveI : 0 < a * ⅟a := by simp only [mul_invOf_self, zero_lt_one] ⟨fun h => (pos_of_mul_pos_left this h).le, fun h => (pos_of_mul_pos_right this h).le⟩ @[simp] theorem invOf_lt_zero [Invertible a] : ⅟a < 0 ↔ a < 0 := by simp only [← not_le, invOf_nonneg] @[simp] theorem invOf_le_one [Invertible a] (h : 1 ≤ a) : ⅟a ≤ 1 := mul_invOf_self a ▸ le_mul_of_one_le_left (invOf_nonneg.2 <| zero_le_one.trans h) h theorem pos_invOf_of_invertible_cast [Nontrivial R] (n : ℕ) [Invertible (n : R)] : 0 < ⅟(n : R) := invOf_pos.2 <| Nat.cast_pos.2 <| pos_of_invertible_cast (R := R) n