blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
139
content_id
stringlengths
40
40
detected_licenses
listlengths
0
16
license_type
stringclasses
2 values
repo_name
stringlengths
7
55
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
6 values
visit_date
int64
1,471B
1,694B
revision_date
int64
1,378B
1,694B
committer_date
int64
1,378B
1,694B
github_id
float64
1.33M
604M
star_events_count
int64
0
43.5k
fork_events_count
int64
0
1.5k
gha_license_id
stringclasses
6 values
gha_event_created_at
int64
1,402B
1,695B
gha_created_at
int64
1,359B
1,637B
gha_language
stringclasses
19 values
src_encoding
stringclasses
2 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
3
6.4M
extension
stringclasses
4 values
content
stringlengths
3
6.12M
2771cee5f53f8cd102fe8bfd778f51d0c965880d
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/model_theory/direct_limit.lean
7833595665f8518c6c321e7063617c58b245e6dc
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
14,855
lean
/- Copyright (c) 2022 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.fintype.order import algebra.direct_limit import model_theory.quotients import model_theory.finitely_generated /-! # Direct Limits of First-Order Structures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file constructs the direct limit of a directed system of first-order embeddings. ## Main Definitions * `first_order.language.direct_limit G f` is the direct limit of the directed system `f` of first-order embeddings between the structures indexed by `G`. -/ universes v w u₁ u₂ open_locale first_order namespace first_order namespace language open Structure set variables {L : language} {ι : Type v} [preorder ι] variables {G : ι → Type w} [Π i, L.Structure (G i)] variables (f : Π i j, i ≤ j → G i ↪[L] G j) namespace directed_system /-- A copy of `directed_system.map_self` specialized to `L`-embeddings, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma map_self [directed_system G (λ i j h, f i j h)] (i x h) : f i i h x = x := directed_system.map_self (λ i j h, f i j h) i x h /-- A copy of `directed_system.map_map` specialized to `L`-embeddings, as otherwise the `λ i j h, f i j h` can confuse the simplifier. -/ lemma map_map [directed_system G (λ i j h, f i j h)] {i j k} (hij hjk x) : f j k hjk (f i j hij x) = f i k (le_trans hij hjk) x := directed_system.map_map (λ i j h, f i j h) hij hjk x variables {G' : ℕ → Type w} [Π i, L.Structure (G' i)] (f' : Π (n : ℕ), G' n ↪[L] G' (n + 1)) /-- Given a chain of embeddings of structures indexed by `ℕ`, defines a `directed_system` by composing them. -/ def nat_le_rec (m n : ℕ) (h : m ≤ n) : G' m ↪[L] G' n := nat.le_rec_on h (λ k g, (f' k).comp g) (embedding.refl L _) @[simp] lemma coe_nat_le_rec (m n : ℕ) (h : m ≤ n) : (nat_le_rec f' m n h : G' m → G' n) = nat.le_rec_on h (λ n, f' n) := begin obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le h, ext x, induction k with k ih, { rw [nat_le_rec, nat.le_rec_on_self, embedding.refl_apply, nat.le_rec_on_self] }, { rw [nat.le_rec_on_succ le_self_add, nat_le_rec, nat.le_rec_on_succ le_self_add, ← nat_le_rec, embedding.comp_apply, ih] } end instance nat_le_rec.directed_system : directed_system G' (λ i j h, nat_le_rec f' i j h) := ⟨λ i x h, congr (congr rfl (nat.le_rec_on_self _)) rfl, λ i j k ij jk, by simp [nat.le_rec_on_trans ij jk]⟩ end directed_system namespace direct_limit /-- Raises a family of elements in the `Σ`-type to the same level along the embeddings. -/ def unify {α : Type*} (x : α → (Σ i, G i)) (i : ι) (h : i ∈ upper_bounds (range (sigma.fst ∘ x))) (a : α) : G i := f (x a).1 i (h (mem_range_self a)) (x a).2 variable [directed_system G (λ i j h, f i j h)] @[simp] lemma unify_sigma_mk_self {α : Type*} {i : ι} {x : α → G i} : unify f (sigma.mk i ∘ x) i (λ j ⟨a, hj⟩, trans (le_of_eq hj.symm) (refl _)) = x := begin ext a, simp only [unify, directed_system.map_self], end lemma comp_unify {α : Type*} {x : α → (Σ i, G i)} {i j : ι} (ij : i ≤ j) (h : i ∈ upper_bounds (range (sigma.fst ∘ x))) : (f i j ij) ∘ (unify f x i h) = unify f x j (λ k hk, trans (mem_upper_bounds.1 h k hk) ij) := begin ext a, simp [unify, directed_system.map_map], end end direct_limit variables (G) namespace direct_limit /-- The directed limit glues together the structures along the embeddings. -/ def setoid [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] : setoid (Σ i, G i) := { r := λ ⟨i, x⟩ ⟨j, y⟩, ∃ (k : ι) (ik : i ≤ k) (jk : j ≤ k), f i k ik x = f j k jk y, iseqv := ⟨λ ⟨i, x⟩, ⟨i, refl i, refl i, rfl⟩, λ ⟨i, x⟩ ⟨j, y⟩ ⟨k, ik, jk, h⟩, ⟨k, jk, ik, h.symm⟩, λ ⟨i, x⟩ ⟨j, y⟩ ⟨k, z⟩ ⟨ij, hiij, hjij, hij⟩ ⟨jk, hjjk, hkjk, hjk⟩, begin obtain ⟨ijk, hijijk, hjkijk⟩ := (directed_of (≤) ij jk), refine ⟨ijk, le_trans hiij hijijk, le_trans hkjk hjkijk, _⟩, rw [← directed_system.map_map, hij, directed_system.map_map], symmetry, rw [← directed_system.map_map, ← hjk, directed_system.map_map], end ⟩ } /-- The structure on the `Σ`-type which becomes the structure on the direct limit after quotienting. -/ noncomputable def sigma_structure [is_directed ι (≤)] [nonempty ι] : L.Structure (Σ i, G i) := { fun_map := λ n F x, ⟨_, fun_map F (unify f x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) (classical.some_spec (fintype.bdd_above_range (λ a, (x a).1))))⟩, rel_map := λ n R x, rel_map R (unify f x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) (classical.some_spec (fintype.bdd_above_range (λ a, (x a).1)))) } end direct_limit /-- The direct limit of a directed system is the structures glued together along the embeddings. -/ def direct_limit [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] := quotient (direct_limit.setoid G f) local attribute [instance] direct_limit.setoid instance [directed_system G (λ i j h, f i j h)] [is_directed ι (≤)] [inhabited ι] [inhabited (G default)] : inhabited (direct_limit G f) := ⟨⟦⟨default, default⟩⟧⟩ namespace direct_limit variables [is_directed ι (≤)] [directed_system G (λ i j h, f i j h)] lemma equiv_iff {x y : Σ i, G i} {i : ι} (hx : x.1 ≤ i) (hy : y.1 ≤ i) : x ≈ y ↔ (f x.1 i hx) x.2 = (f y.1 i hy) y.2 := begin cases x, cases y, refine ⟨λ xy, _, λ xy, ⟨i, hx, hy, xy⟩⟩, obtain ⟨j, _, _, h⟩ := xy, obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, have h := congr_arg (f j k jk) h, apply (f i k ik).injective, rw [directed_system.map_map, directed_system.map_map] at *, exact h end lemma fun_map_unify_equiv {n : ℕ} (F : L.functions n) (x : (fin n) → (Σ i, G i)) (i j : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hj : j ∈ upper_bounds (range (sigma.fst ∘ x))) : (⟨i, fun_map F (unify f x i hi)⟩ : Σ i, G i) ≈ ⟨j, fun_map F (unify f x j hj)⟩ := begin obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, refine ⟨k, ik, jk, _⟩, rw [(f i k ik).map_fun, (f j k jk).map_fun, comp_unify, comp_unify], end lemma rel_map_unify_equiv {n : ℕ} (R : L.relations n) (x : (fin n) → (Σ i, G i)) (i j : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hj : j ∈ upper_bounds (range (sigma.fst ∘ x))) : rel_map R (unify f x i hi) = rel_map R (unify f x j hj) := begin obtain ⟨k, ik, jk⟩ := directed_of (≤) i j, rw [← (f i k ik).map_rel, comp_unify, ← (f j k jk).map_rel, comp_unify], end variable [nonempty ι] lemma exists_unify_eq {α : Type*} [fintype α] {x y : α → (Σ i, G i)} (xy : x ≈ y) : ∃ (i : ι) (hx : i ∈ upper_bounds (range (sigma.fst ∘ x))) (hy : i ∈ upper_bounds (range (sigma.fst ∘ y))), unify f x i hx = unify f y i hy := begin obtain ⟨i, hi⟩ := fintype.bdd_above_range (sum.elim (λ a, (x a).1) (λ a, (y a).1)), rw [sum.elim_range, upper_bounds_union] at hi, simp_rw [← function.comp_apply sigma.fst _] at hi, exact ⟨i, hi.1, hi.2, funext (λ a, (equiv_iff G f _ _).1 (xy a))⟩, end lemma fun_map_equiv_unify {n : ℕ} (F : L.functions n) (x : (fin n) → (Σ i, G i)) (i : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) : @fun_map _ _ (sigma_structure G f) _ F x ≈ ⟨_, fun_map F (unify f x i hi)⟩ := fun_map_unify_equiv G f F x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) i _ hi lemma rel_map_equiv_unify {n : ℕ} (R : L.relations n) (x : (fin n) → (Σ i, G i)) (i : ι) (hi : i ∈ upper_bounds (range (sigma.fst ∘ x))) : @rel_map _ _ (sigma_structure G f) _ R x = rel_map R (unify f x i hi) := rel_map_unify_equiv G f R x (classical.some (fintype.bdd_above_range (λ a, (x a).1))) i _ hi /-- The direct limit `setoid` respects the structure `sigma_structure`, so quotienting by it gives rise to a valid structure. -/ noncomputable instance prestructure : L.prestructure (direct_limit.setoid G f) := { to_structure := sigma_structure G f, fun_equiv := λ n F x y xy, begin obtain ⟨i, hx, hy, h⟩ := exists_unify_eq G f xy, refine setoid.trans (fun_map_equiv_unify G f F x i hx) (setoid.trans _ (setoid.symm (fun_map_equiv_unify G f F y i hy))), rw h, end, rel_equiv := λ n R x y xy, begin obtain ⟨i, hx, hy, h⟩ := exists_unify_eq G f xy, refine trans (rel_map_equiv_unify G f R x i hx) (trans _ (symm (rel_map_equiv_unify G f R y i hy))), rw h, end } /-- The `L.Structure` on a direct limit of `L.Structure`s. -/ noncomputable instance Structure : L.Structure (direct_limit G f) := language.quotient_structure @[simp] lemma fun_map_quotient_mk_sigma_mk {n : ℕ} {F : L.functions n} {i : ι} {x : fin n → G i} : fun_map F (λ a, (⟦⟨i, x a⟩⟧ : direct_limit G f)) = ⟦⟨i, fun_map F x⟩⟧ := begin simp only [function.comp_app, fun_map_quotient_mk, quotient.eq], obtain ⟨k, ik, jk⟩ := directed_of (≤) i (classical.some (fintype.bdd_above_range (λ (a : fin n), i))), refine ⟨k, jk, ik, _⟩, simp only [embedding.map_fun, comp_unify], refl end @[simp] lemma rel_map_quotient_mk_sigma_mk {n : ℕ} {R : L.relations n} {i : ι} {x : fin n → G i} : rel_map R (λ a, (⟦⟨i, x a⟩⟧ : direct_limit G f)) = rel_map R x := begin rw [rel_map_quotient_mk], obtain ⟨k, ik, jk⟩ := directed_of (≤) i (classical.some (fintype.bdd_above_range (λ (a : fin n), i))), rw [rel_map_equiv_unify G f R (λ a, ⟨i, x a⟩) i, unify_sigma_mk_self], end lemma exists_quotient_mk_sigma_mk_eq {α : Type*} [fintype α] (x : α → direct_limit G f) : ∃ (i : ι) (y : α → G i), x = quotient.mk ∘ (sigma.mk i) ∘ y := begin obtain ⟨i, hi⟩ := fintype.bdd_above_range (λ a, (x a).out.1), refine ⟨i, unify f (quotient.out ∘ x) i hi, _⟩, ext a, rw [quotient.eq_mk_iff_out, function.comp_app, unify, equiv_iff G f _], { simp only [directed_system.map_self] }, { refl } end variables (L ι) /-- The canonical map from a component to the direct limit. -/ def of (i : ι) : G i ↪[L] direct_limit G f := { to_fun := quotient.mk ∘ sigma.mk i, inj' := λ x y h, begin simp only [quotient.eq] at h, obtain ⟨j, h1, h2, h3⟩ := h, exact (f i j h1).injective h3, end } variables {L ι G f} @[simp] lemma of_apply {i : ι} {x : G i} : of L ι G f i x = ⟦⟨i, x⟩⟧ := rfl @[simp] lemma of_f {i j : ι} {hij : i ≤ j} {x : G i} : (of L ι G f j (f i j hij x)) = of L ι G f i x := begin simp only [of_apply, quotient.eq], refine setoid.symm ⟨j, hij, refl j, _⟩, simp only [directed_system.map_self], end /-- Every element of the direct limit corresponds to some element in some component of the directed system. -/ theorem exists_of (z : direct_limit G f) : ∃ i x, of L ι G f i x = z := ⟨z.out.1, z.out.2, by simp⟩ @[elab_as_eliminator] protected theorem induction_on {C : direct_limit G f → Prop} (z : direct_limit G f) (ih : ∀ i x, C (of L ι G f i x)) : C z := let ⟨i, x, h⟩ := exists_of z in h ▸ ih i x variables {P : Type u₁} [L.Structure P] (g : Π i, G i ↪[L] P) variables (Hg : ∀ i j hij x, g j (f i j hij x) = g i x) include Hg variables (L ι G f) /-- The universal property of the direct limit: maps from the components to another module that respect the directed system structure (i.e. make some diagram commute) give rise to a unique map out of the direct limit. -/ def lift : direct_limit G f ↪[L] P := { to_fun := quotient.lift (λ (x : Σ i, G i), (g x.1) x.2) (λ x y xy, begin simp only, obtain ⟨i, hx, hy⟩ := directed_of (≤) x.1 y.1, rw [← Hg x.1 i hx, ← Hg y.1 i hy], exact congr_arg _ ((equiv_iff _ _ _ _).1 xy), end), inj' := λ x y xy, begin rw [← quotient.out_eq x, ← quotient.out_eq y, quotient.lift_mk, quotient.lift_mk] at xy, obtain ⟨i, hx, hy⟩ := directed_of (≤) x.out.1 y.out.1, rw [← Hg x.out.1 i hx, ← Hg y.out.1 i hy] at xy, rw [← quotient.out_eq x, ← quotient.out_eq y, quotient.eq, equiv_iff G f hx hy], exact (g i).injective xy, end, map_fun' := λ n F x, begin obtain ⟨i, y, rfl⟩ := exists_quotient_mk_sigma_mk_eq G f x, rw [fun_map_quotient_mk_sigma_mk, ← function.comp.assoc, quotient.lift_comp_mk], simp only [quotient.lift_mk, embedding.map_fun], end, map_rel' := λ n R x, begin obtain ⟨i, y, rfl⟩ := exists_quotient_mk_sigma_mk_eq G f x, rw [rel_map_quotient_mk_sigma_mk G f, ← (g i).map_rel R y, ← function.comp.assoc, quotient.lift_comp_mk], end } variables {L ι G f} omit Hg @[simp] lemma lift_quotient_mk_sigma_mk {i} (x : G i) : lift L ι G f g Hg (⟦⟨i, x⟩⟧) = (g i) x := begin change (lift L ι G f g Hg).to_fun (⟦⟨i, x⟩⟧) = _, simp only [lift, quotient.lift_mk], end lemma lift_of {i} (x : G i) : lift L ι G f g Hg (of L ι G f i x) = g i x := by simp theorem lift_unique (F : direct_limit G f ↪[L] P) (x) : F x = lift L ι G f (λ i, F.comp $ of L ι G f i) (λ i j hij x, by rw [F.comp_apply, F.comp_apply, of_f]) x := direct_limit.induction_on x $ λ i x, by rw lift_of; refl /-- The direct limit of countably many countably generated structures is countably generated. -/ theorem cg {ι : Type*} [encodable ι] [preorder ι] [is_directed ι (≤)] [nonempty ι] {G : ι → Type w} [Π i, L.Structure (G i)] (f : Π i j, i ≤ j → G i ↪[L] G j) (h : ∀ i, Structure.cg L (G i)) [directed_system G (λ i j h, f i j h)] : Structure.cg L (direct_limit G f) := begin refine ⟨⟨⋃ i, direct_limit.of L ι G f i '' (classical.some (h i).out), _, _⟩⟩, { exact set.countable_Union (λ i, set.countable.image (classical.some_spec (h i).out).1 _) }, { rw [eq_top_iff, substructure.closure_Union], simp_rw [← embedding.coe_to_hom, substructure.closure_image], rw le_supr_iff, intros S hS x hx, let out := @quotient.out _ (direct_limit.setoid G f), refine hS (out x).1 ⟨(out x).2, _, _⟩, { rw [(classical.some_spec (h (out x).1).out).2], simp only [substructure.coe_top] }, { simp only [embedding.coe_to_hom, direct_limit.of_apply, sigma.eta, quotient.out_eq] } } end instance cg' {ι : Type*} [encodable ι] [preorder ι] [is_directed ι (≤)] [nonempty ι] {G : ι → Type w} [Π i, L.Structure (G i)] (f : Π i j, i ≤ j → G i ↪[L] G j) [h : ∀ i, Structure.cg L (G i)] [directed_system G (λ i j h, f i j h)] : Structure.cg L (direct_limit G f) := cg f h end direct_limit end language end first_order
6cf924d780c481c7546f8ec7ce47d8f2eccda3f3
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/tests/lean/run/meta4.lean
2e67b1580fa74a663190e027dc5faf01ab067073
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,356
lean
import Lean.Meta open Lean open Lean.Meta def print (msg : MessageData) : MetaM Unit := trace! `Meta.debug msg def checkM (x : MetaM Bool) : MetaM Unit := unless (← x) do throwError "check failed" axiom Ax : forall (α β : Type), α → β → DecidableEq β set_option trace.Meta.debug true def tst1 : MetaM Unit := do let cinfo ← getConstInfo `Ax; let (_, _, e) ← forallMetaTelescopeReducing cinfo.type (some 0); checkM (pure (!e.hasMVar)); print e; let (_, _, e) ← forallMetaTelescopeReducing cinfo.type (some 1); checkM (pure e.hasMVar); checkM (pure e.isForall); print e; let (_, _, e) ← forallMetaTelescopeReducing cinfo.type (some 5); checkM (pure e.hasMVar); checkM (pure e.isForall); print e; let (_, _, e) ← forallMetaTelescopeReducing cinfo.type (some 6); checkM (pure e.hasMVar); checkM (pure (!e.isForall)); print e; let (_, _, e') ← forallMetaTelescopeReducing cinfo.type; print e'; checkM (isDefEq e e'); forallBoundedTelescope cinfo.type (some 0) $ fun xs body => checkM (pure (xs.size == 0)); forallBoundedTelescope cinfo.type (some 1) $ fun xs body => checkM (pure (xs.size == 1)); forallBoundedTelescope cinfo.type (some 6) $ fun xs body => do { print xs; checkM (pure (xs.size == 6)) }; forallBoundedTelescope cinfo.type (some 10) $ fun xs body => do { print xs; checkM (pure (xs.size == 6)) }; pure () #eval tst1
41a7ab7837e73af1d4d0e795d10aa47ae118ef81
137c667471a40116a7afd7261f030b30180468c2
/src/group_theory/congruence.lean
026951ec3bb040f96de0654adbe94a8061d9b77a
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,887
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import data.setoid.basic import algebra.group.pi import algebra.group.prod import data.equiv.mul_add import group_theory.submonoid.operations /-! # Congruence relations This file defines congruence relations: equivalence relations that preserve a binary operation, which in this case is multiplication or addition. The principal definition is a `structure` extending a `setoid` (an equivalence relation), and the inductive definition of the smallest congruence relation containing a binary relation is also given (see `con_gen`). The file also proves basic properties of the quotient of a type by a congruence relation, and the complete lattice of congruence relations on a type. We then establish an order-preserving bijection between the set of congruence relations containing a congruence relation `c` and the set of congruence relations on the quotient by `c`. The second half of the file concerns congruence relations on monoids, in which case the quotient by the congruence relation is also a monoid. There are results about the universal property of quotients of monoids, and the isomorphism theorems for monoids. ## Implementation notes The inductive definition of a congruence relation could be a nested inductive type, defined using the equivalence closure of a binary relation `eqv_gen`, but the recursor generated does not work. A nested inductive definition could conceivably shorten proofs, because they would allow invocation of the corresponding lemmas about `eqv_gen`. The lemmas `refl`, `symm` and `trans` are not tagged with `@[refl]`, `@[symm]`, and `@[trans]` respectively as these tags do not work on a structure coerced to a binary relation. There is a coercion from elements of a type to the element's equivalence class under a congruence relation. A congruence relation on a monoid `M` can be thought of as a submonoid of `M × M` for which membership is an equivalence relation, but whilst this fact is established in the file, it is not used, since this perspective adds more layers of definitional unfolding. ## Tags congruence, congruence relation, quotient, quotient by congruence relation, monoid, quotient monoid, isomorphism theorems -/ variables (M : Type*) {N : Type*} {P : Type*} set_option old_structure_cmd true open function setoid /-- A congruence relation on a type with an addition is an equivalence relation which preserves addition. -/ structure add_con [has_add M] extends setoid M := (add' : ∀ {w x y z}, r w x → r y z → r (w + y) (x + z)) /-- A congruence relation on a type with a multiplication is an equivalence relation which preserves multiplication. -/ @[to_additive add_con] structure con [has_mul M] extends setoid M := (mul' : ∀ {w x y z}, r w x → r y z → r (w * y) (x * z)) /-- The equivalence relation underlying an additive congruence relation. -/ add_decl_doc add_con.to_setoid /-- The equivalence relation underlying a multiplicative congruence relation. -/ add_decl_doc con.to_setoid variables {M} /-- The inductively defined smallest additive congruence relation containing a given binary relation. -/ inductive add_con_gen.rel [has_add M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → add_con_gen.rel x y | refl : Π x, add_con_gen.rel x x | symm : Π x y, add_con_gen.rel x y → add_con_gen.rel y x | trans : Π x y z, add_con_gen.rel x y → add_con_gen.rel y z → add_con_gen.rel x z | add : Π w x y z, add_con_gen.rel w x → add_con_gen.rel y z → add_con_gen.rel (w + y) (x + z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen.rel] inductive con_gen.rel [has_mul M] (r : M → M → Prop) : M → M → Prop | of : Π x y, r x y → con_gen.rel x y | refl : Π x, con_gen.rel x x | symm : Π x y, con_gen.rel x y → con_gen.rel y x | trans : Π x y z, con_gen.rel x y → con_gen.rel y z → con_gen.rel x z | mul : Π w x y z, con_gen.rel w x → con_gen.rel y z → con_gen.rel (w * y) (x * z) /-- The inductively defined smallest multiplicative congruence relation containing a given binary relation. -/ @[to_additive add_con_gen "The inductively defined smallest additive congruence relation containing a given binary relation."] def con_gen [has_mul M] (r : M → M → Prop) : con M := ⟨con_gen.rel r, ⟨con_gen.rel.refl, con_gen.rel.symm, con_gen.rel.trans⟩, con_gen.rel.mul⟩ namespace con section variables [has_mul M] [has_mul N] [has_mul P] (c : con M) @[to_additive] instance : inhabited (con M) := ⟨con_gen empty_relation⟩ /-- A coercion from a congruence relation to its underlying binary relation. -/ @[to_additive "A coercion from an additive congruence relation to its underlying binary relation."] instance : has_coe_to_fun (con M) := ⟨_, λ c, λ x y, c.r x y⟩ @[simp, to_additive] lemma rel_eq_coe (c : con M) : c.r = c := rfl /-- Congruence relations are reflexive. -/ @[to_additive "Additive congruence relations are reflexive."] protected lemma refl (x) : c x x := c.2.1 x /-- Congruence relations are symmetric. -/ @[to_additive "Additive congruence relations are symmetric."] protected lemma symm : ∀ {x y}, c x y → c y x := λ _ _ h, c.2.2.1 h /-- Congruence relations are transitive. -/ @[to_additive "Additive congruence relations are transitive."] protected lemma trans : ∀ {x y z}, c x y → c y z → c x z := λ _ _ _ h, c.2.2.2 h /-- Multiplicative congruence relations preserve multiplication. -/ @[to_additive "Additive congruence relations preserve addition."] protected lemma mul : ∀ {w x y z}, c w x → c y z → c (w * y) (x * z) := λ _ _ _ _ h1 h2, c.3 h1 h2 /-- Given a type `M` with a multiplication, a congruence relation `c` on `M`, and elements of `M` `x, y`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`. -/ @[to_additive "Given a type `M` with an addition, `x, y ∈ M`, and an additive congruence relation `c` on `M`, `(x, y) ∈ M × M` iff `x` is related to `y` by `c`."] instance : has_mem (M × M) (con M) := ⟨λ x c, c x.1 x.2⟩ variables {c} /-- The map sending a congruence relation to its underlying binary relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying binary relation is injective."] lemma ext' {c d : con M} (H : c.r = d.r) : c = d := by cases c; cases d; simpa using H /-- Extensionality rule for congruence relations. -/ @[ext, to_additive "Extensionality rule for additive congruence relations."] lemma ext {c d : con M} (H : ∀ x y, c x y ↔ d x y) : c = d := ext' $ by ext; apply H attribute [ext] add_con.ext /-- The map sending a congruence relation to its underlying equivalence relation is injective. -/ @[to_additive "The map sending an additive congruence relation to its underlying equivalence relation is injective."] lemma to_setoid_inj {c d : con M} (H : c.to_setoid = d.to_setoid) : c = d := ext $ ext_iff.1 H /-- Iff version of extensionality rule for congruence relations. -/ @[to_additive "Iff version of extensionality rule for additive congruence relations."] lemma ext_iff {c d : con M} : (∀ x y, c x y ↔ d x y) ↔ c = d := ⟨ext, λ h _ _, h ▸ iff.rfl⟩ /-- Two congruence relations are equal iff their underlying binary relations are equal. -/ @[to_additive "Two additive congruence relations are equal iff their underlying binary relations are equal."] lemma ext'_iff {c d : con M} : c.r = d.r ↔ c = d := ⟨ext', λ h, h ▸ rfl⟩ /-- The kernel of a multiplication-preserving function as a congruence relation. -/ @[to_additive "The kernel of an addition-preserving function as an additive congruence relation."] def mul_ker (f : M → P) (h : ∀ x y, f (x * y) = f x * f y) : con M := { r := λ x y, f x = f y, iseqv := ⟨λ _, rfl, λ _ _, eq.symm, λ _ _ _, eq.trans⟩, mul' := λ _ _ _ _ h1 h2, by rw [h, h1, h2, h] } /-- Given types with multiplications `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`. -/ @[to_additive prod "Given types with additions `M, N`, the product of two congruence relations `c` on `M` and `d` on `N`: `(x₁, x₂), (y₁, y₂) ∈ M × N` are related by `c.prod d` iff `x₁` is related to `y₁` by `c` and `x₂` is related to `y₂` by `d`."] protected def prod (c : con M) (d : con N) : con (M × N) := { mul' := λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩, ..c.to_setoid.prod d.to_setoid } /-- The product of an indexed collection of congruence relations. -/ @[to_additive "The product of an indexed collection of additive congruence relations."] def pi {ι : Type*} {f : ι → Type*} [Π i, has_mul (f i)] (C : Π i, con (f i)) : con (Π i, f i) := { mul' := λ _ _ _ _ h1 h2 i, (C i).mul (h1 i) (h2 i), ..@pi_setoid _ _ $ λ i, (C i).to_setoid } variables (c) @[simp, to_additive] lemma coe_eq : c.to_setoid.r = c := rfl -- Quotients /-- Defining the quotient by a congruence relation of a type with a multiplication. -/ @[to_additive "Defining the quotient by an additive congruence relation of a type with an addition."] protected def quotient := quotient $ c.to_setoid /-- Coercion from a type with a multiplication to its quotient by a congruence relation. See Note [use has_coe_t]. -/ @[to_additive "Coercion from a type with an addition to its quotient by an additive congruence relation", priority 0] instance : has_coe_t M c.quotient := ⟨@quotient.mk _ c.to_setoid⟩ /-- The quotient by a decidable congruence relation has decidable equality. -/ @[to_additive "The quotient by a decidable additive congruence relation has decidable equality."] instance [d : ∀ a b, decidable (c a b)] : decidable_eq c.quotient := @quotient.decidable_eq M c.to_setoid d /-- The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected def lift_on {β} {c : con M} (q : c.quotient) (f : M → β) (h : ∀ a b, c a b → f a = f b) : β := quotient.lift_on' q f h /-- The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes. -/ @[elab_as_eliminator, to_additive "The binary function on the quotient by a congruence relation `c` induced by a binary function that is constant on `c`'s equivalence classes."] protected def lift_on₂ {β} {c : con M} (q r : c.quotient) (f : M → M → β) (h : ∀ a₁ a₂ b₁ b₂, c a₁ b₁ → c a₂ b₂ → f a₁ a₂ = f b₁ b₂) : β := quotient.lift_on₂' q r f h variables {c} /-- The inductive principle used to prove propositions about the elements of a quotient by a congruence relation. -/ @[elab_as_eliminator, to_additive "The inductive principle used to prove propositions about the elements of a quotient by an additive congruence relation."] protected lemma induction_on {C : c.quotient → Prop} (q : c.quotient) (H : ∀ x : M, C x) : C q := quotient.induction_on' q H /-- A version of `con.induction_on` for predicates which take two arguments. -/ @[elab_as_eliminator, to_additive "A version of `add_con.induction_on` for predicates which take two arguments."] protected lemma induction_on₂ {d : con N} {C : c.quotient → d.quotient → Prop} (p : c.quotient) (q : d.quotient) (H : ∀ (x : M) (y : N), C x y) : C p q := quotient.induction_on₂' p q H variables (c) /-- Two elements are related by a congruence relation `c` iff they are represented by the same element of the quotient by `c`. -/ @[simp, to_additive "Two elements are related by an additive congruence relation `c` iff they are represented by the same element of the quotient by `c`."] protected lemma eq {a b : M} : (a : c.quotient) = b ↔ c a b := quotient.eq' /-- The multiplication induced on the quotient by a congruence relation on a type with a multiplication. -/ @[to_additive "The addition induced on the quotient by an additive congruence relation on a type with an addition."] instance has_mul : has_mul c.quotient := ⟨λ x y, quotient.lift_on₂' x y (λ w z, ((w * z : M) : c.quotient)) $ λ _ _ _ _ h1 h2, c.eq.2 $ c.mul h1 h2⟩ /-- The kernel of the quotient map induced by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the quotient map induced by an additive congruence relation `c` equals `c`."] lemma mul_ker_mk_eq : mul_ker (coe : M → c.quotient) (λ x y, rfl) = c := ext $ λ x y, quotient.eq' variables {c} /-- The coercion to the quotient of a congruence relation commutes with multiplication (by definition). -/ @[simp, to_additive "The coercion to the quotient of an additive congruence relation commutes with addition (by definition)."] lemma coe_mul (x y : M) : (↑(x * y) : c.quotient) = ↑x * ↑y := rfl /-- Definition of the function on the quotient by a congruence relation `c` induced by a function that is constant on `c`'s equivalence classes. -/ @[simp, to_additive "Definition of the function on the quotient by an additive congruence relation `c` induced by a function that is constant on `c`'s equivalence classes."] protected lemma lift_on_coe {β} (c : con M) (f : M → β) (h : ∀ a b, c a b → f a = f b) (x : M) : con.lift_on (x : c.quotient) f h = f x := rfl /-- Makes an isomorphism of quotients by two congruence relations, given that the relations are equal. -/ @[to_additive "Makes an additive isomorphism of quotients by two additive congruence relations, given that the relations are equal."] protected def congr {c d : con M} (h : c = d) : c.quotient ≃* d.quotient := { map_mul' := λ x y, by rcases x; rcases y; refl, ..quotient.congr (equiv.refl M) $ by apply ext_iff.2 h } -- The complete lattice of congruence relations on a type /-- For congruence relations `c, d` on a type `M` with a multiplication, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`. -/ @[to_additive "For additive congruence relations `c, d` on a type `M` with an addition, `c ≤ d` iff `∀ x y ∈ M`, `x` is related to `y` by `d` if `x` is related to `y` by `c`."] instance : has_le (con M) := ⟨λ c d, ∀ ⦃x y⦄, c x y → d x y⟩ /-- Definition of `≤` for congruence relations. -/ @[to_additive "Definition of `≤` for additive congruence relations."] theorem le_def {c d : con M} : c ≤ d ↔ ∀ {x y}, c x y → d x y := iff.rfl /-- The infimum of a set of congruence relations on a given type with a multiplication. -/ @[to_additive "The infimum of a set of additive congruence relations on a given type with an addition."] instance : has_Inf (con M) := ⟨λ S, ⟨λ x y, ∀ c : con M, c ∈ S → c x y, ⟨λ x c hc, c.refl x, λ _ _ h c hc, c.symm $ h c hc, λ _ _ _ h1 h2 c hc, c.trans (h1 c hc) $ h2 c hc⟩, λ _ _ _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying equivalence relation."] lemma Inf_to_setoid (S : set (con M)) : (Inf S).to_setoid = Inf (to_setoid '' S) := setoid.ext' $ λ x y, ⟨λ h r ⟨c, hS, hr⟩, by rw ←hr; exact h c hS, λ h c hS, h c.to_setoid ⟨c, hS, rfl⟩⟩ /-- The infimum of a set of congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The infimum of a set of additive congruence relations is the same as the infimum of the set's image under the map to the underlying binary relation."] lemma Inf_def (S : set (con M)) : (Inf S).r = Inf (r '' S) := by { ext, simp only [Inf_image, infi_apply, infi_Prop_eq], refl } @[to_additive] instance : partial_order (con M) := { le := (≤), lt := λ c d, c ≤ d ∧ ¬d ≤ c, le_refl := λ c _ _, id, le_trans := λ c1 c2 c3 h1 h2 x y h, h2 $ h1 h, lt_iff_le_not_le := λ _ _, iff.rfl, le_antisymm := λ c d hc hd, ext $ λ x y, ⟨λ h, hc h, λ h, hd h⟩ } /-- The complete lattice of congruence relations on a given type with a multiplication. -/ @[to_additive "The complete lattice of additive congruence relations on a given type with an addition."] instance : complete_lattice (con M) := { inf := λ c d, ⟨(c.to_setoid ⊓ d.to_setoid).1, (c.to_setoid ⊓ d.to_setoid).2, λ _ _ _ _ h1 h2, ⟨c.mul h1.1 h2.1, d.mul h1.2 h2.2⟩⟩, inf_le_left := λ _ _ _ _ h, h.1, inf_le_right := λ _ _ _ _ h, h.2, le_inf := λ _ _ _ hb hc _ _ h, ⟨hb h, hc h⟩, top := { mul' := by tauto, ..setoid.complete_lattice.top}, le_top := λ _ _ _ h, trivial, bot := { mul' := λ _ _ _ _ h1 h2, h1 ▸ h2 ▸ rfl, ..setoid.complete_lattice.bot}, bot_le := λ c x y h, h ▸ c.refl x, .. complete_lattice_of_Inf (con M) $ assume s, ⟨λ r hr x y h, (h : ∀ r ∈ s, (r : con M) x y) r hr, λ r hr x y h r' hr', hr hr' h⟩ } /-- The infimum of two congruence relations equals the infimum of the underlying binary operations. -/ @[to_additive "The infimum of two additive congruence relations equals the infimum of the underlying binary operations."] lemma inf_def {c d : con M} : (c ⊓ d).r = c.r ⊓ d.r := rfl /-- Definition of the infimum of two congruence relations. -/ @[to_additive "Definition of the infimum of two additive congruence relations."] theorem inf_iff_and {c d : con M} {x y} : (c ⊓ d) x y ↔ c x y ∧ d x y := iff.rfl /-- The inductively defined smallest congruence relation containing a binary relation `r` equals the infimum of the set of congruence relations containing `r`. -/ @[to_additive add_con_gen_eq "The inductively defined smallest additive congruence relation containing a binary relation `r` equals the infimum of the set of additive congruence relations containing `r`."] theorem con_gen_eq (r : M → M → Prop) : con_gen r = Inf {s : con M | ∀ x y, r x y → s x y} := le_antisymm (λ x y H, con_gen.rel.rec_on H (λ _ _ h _ hs, hs _ _ h) (con.refl _) (λ _ _ _, con.symm _) (λ _ _ _ _ _, con.trans _) $ λ w x y z _ _ h1 h2 c hc, c.mul (h1 c hc) $ h2 c hc) (Inf_le (λ _ _, con_gen.rel.of _ _)) /-- The smallest congruence relation containing a binary relation `r` is contained in any congruence relation containing `r`. -/ @[to_additive add_con_gen_le "The smallest additive congruence relation containing a binary relation `r` is contained in any additive congruence relation containing `r`."] theorem con_gen_le {r : M → M → Prop} {c : con M} (h : ∀ x y, r x y → c.r x y) : con_gen r ≤ c := by rw con_gen_eq; exact Inf_le h /-- Given binary relations `r, s` with `r` contained in `s`, the smallest congruence relation containing `s` contains the smallest congruence relation containing `r`. -/ @[to_additive add_con_gen_mono "Given binary relations `r, s` with `r` contained in `s`, the smallest additive congruence relation containing `s` contains the smallest additive congruence relation containing `r`."] theorem con_gen_mono {r s : M → M → Prop} (h : ∀ x y, r x y → s x y) : con_gen r ≤ con_gen s := con_gen_le $ λ x y hr, con_gen.rel.of _ _ $ h x y hr /-- Congruence relations equal the smallest congruence relation in which they are contained. -/ @[simp, to_additive add_con_gen_of_add_con "Additive congruence relations equal the smallest additive congruence relation in which they are contained."] lemma con_gen_of_con (c : con M) : con_gen c = c := le_antisymm (by rw con_gen_eq; exact Inf_le (λ _ _, id)) con_gen.rel.of /-- The map sending a binary relation to the smallest congruence relation in which it is contained is idempotent. -/ @[simp, to_additive add_con_gen_idem "The map sending a binary relation to the smallest additive congruence relation in which it is contained is idempotent."] lemma con_gen_idem (r : M → M → Prop) : con_gen (con_gen r) = con_gen r := con_gen_of_con _ /-- The supremum of congruence relations `c, d` equals the smallest congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'. -/ @[to_additive sup_eq_add_con_gen "The supremum of additive congruence relations `c, d` equals the smallest additive congruence relation containing the binary relation '`x` is related to `y` by `c` or `d`'."] lemma sup_eq_con_gen (c d : con M) : c ⊔ d = con_gen (λ x y, c x y ∨ d x y) := begin rw con_gen_eq, apply congr_arg Inf, simp only [le_def, or_imp_distrib, ← forall_and_distrib] end /-- The supremum of two congruence relations equals the smallest congruence relation containing the supremum of the underlying binary operations. -/ @[to_additive "The supremum of two additive congruence relations equals the smallest additive congruence relation containing the supremum of the underlying binary operations."] lemma sup_def {c d : con M} : c ⊔ d = con_gen (c.r ⊔ d.r) := by rw sup_eq_con_gen; refl /-- The supremum of a set of congruence relations `S` equals the smallest congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'. -/ @[to_additive Sup_eq_add_con_gen "The supremum of a set of additive congruence relations `S` equals the smallest additive congruence relation containing the binary relation 'there exists `c ∈ S` such that `x` is related to `y` by `c`'."] lemma Sup_eq_con_gen (S : set (con M)) : Sup S = con_gen (λ x y, ∃ c : con M, c ∈ S ∧ c x y) := begin rw con_gen_eq, apply congr_arg Inf, ext, exact ⟨λ h _ _ ⟨r, hr⟩, h hr.1 hr.2, λ h r hS _ _ hr, h _ _ ⟨r, hS, hr⟩⟩, end /-- The supremum of a set of congruence relations is the same as the smallest congruence relation containing the supremum of the set's image under the map to the underlying binary relation. -/ @[to_additive "The supremum of a set of additive congruence relations is the same as the smallest additive congruence relation containing the supremum of the set's image under the map to the underlying binary relation."] lemma Sup_def {S : set (con M)} : Sup S = con_gen (Sup (r '' S)) := begin rw [Sup_eq_con_gen, Sup_image], congr' with x y, simp only [Sup_image, supr_apply, supr_Prop_eq, exists_prop, rel_eq_coe] end variables (M) /-- There is a Galois insertion of congruence relations on a type with a multiplication `M` into binary relations on `M`. -/ @[to_additive "There is a Galois insertion of additive congruence relations on a type with an addition `M` into binary relations on `M`."] protected noncomputable def gi : @galois_insertion (M → M → Prop) (con M) _ _ con_gen r := { choice := λ r h, con_gen r, gc := λ r c, ⟨λ H _ _ h, H $ con_gen.rel.of _ _ h, λ H, con_gen_of_con c ▸ con_gen_mono H⟩, le_l_u := λ x, (con_gen_of_con x).symm ▸ le_refl x, choice_eq := λ _ _, rfl } variables {M} (c) /-- Given a function `f`, the smallest congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by a congruence relation `c`.' -/ @[to_additive "Given a function `f`, the smallest additive congruence relation containing the binary relation on `f`'s image defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by an additive congruence relation `c`.'"] def map_gen (f : M → N) : con N := con_gen $ λ x y, ∃ a b, f a = x ∧ f b = y ∧ c a b /-- Given a surjective multiplicative-preserving function `f` whose kernel is contained in a congruence relation `c`, the congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.' -/ @[to_additive "Given a surjective addition-preserving function `f` whose kernel is contained in an additive congruence relation `c`, the additive congruence relation on `f`'s codomain defined by '`x ≈ y` iff the elements of `f⁻¹(x)` are related to the elements of `f⁻¹(y)` by `c`.'"] def map_of_surjective (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : con N := { mul' := λ w x y z ⟨a, b, hw, hx, h1⟩ ⟨p, q, hy, hz, h2⟩, ⟨a * p, b * q, by rw [H, hw, hy], by rw [H, hx, hz], c.mul h1 h2⟩, ..c.to_setoid.map_of_surjective f h hf } /-- A specialization of 'the smallest congruence relation containing a congruence relation `c` equals `c`'. -/ @[to_additive "A specialization of 'the smallest additive congruence relation containing an additive congruence relation `c` equals `c`'."] lemma map_of_surjective_eq_map_gen {c : con M} {f : M → N} (H : ∀ x y, f (x * y) = f x * f y) (h : mul_ker f H ≤ c) (hf : surjective f) : c.map_gen f = c.map_of_surjective f H h hf := by rw ←con_gen_of_con (c.map_of_surjective f H h hf); refl /-- Given types with multiplications `M, N` and a congruence relation `c` on `N`, a multiplication-preserving map `f : M → N` induces a congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' -/ @[to_additive "Given types with additions `M, N` and an additive congruence relation `c` on `N`, an addition-preserving map `f : M → N` induces an additive congruence relation on `f`'s domain defined by '`x ≈ y` iff `f(x)` is related to `f(y)` by `c`.' "] def comap (f : M → N) (H : ∀ x y, f (x * y) = f x * f y) (c : con N) : con M := { mul' := λ w x y z h1 h2, show c (f (w * y)) (f (x * z)), by rw [H, H]; exact c.mul h1 h2, ..c.to_setoid.comap f } section open quotient /-- Given a congruence relation `c` on a type `M` with a multiplication, the order-preserving bijection between the set of congruence relations containing `c` and the congruence relations on the quotient of `M` by `c`. -/ @[to_additive "Given an additive congruence relation `c` on a type `M` with an addition, the order-preserving bijection between the set of additive congruence relations containing `c` and the additive congruence relations on the quotient of `M` by `c`."] def correspondence : {d // c ≤ d} ≃o (con c.quotient) := { to_fun := λ d, d.1.map_of_surjective coe _ (by rw mul_ker_mk_eq; exact d.2) $ @exists_rep _ c.to_setoid, inv_fun := λ d, ⟨comap (coe : M → c.quotient) (λ x y, rfl) d, λ _ _ h, show d _ _, by rw c.eq.2 h; exact d.refl _ ⟩, left_inv := λ d, subtype.ext_iff_val.2 $ ext $ λ _ _, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in d.1.trans (d.1.symm $ d.2 $ c.eq.1 hx) $ d.1.trans H $ d.2 $ c.eq.1 hy, λ h, ⟨_, _, rfl, rfl, h⟩⟩, right_inv := λ d, let Hm : mul_ker (coe : M → c.quotient) (λ x y, rfl) ≤ comap (coe : M → c.quotient) (λ x y, rfl) d := λ x y h, show d _ _, by rw mul_ker_mk_eq at h; exact c.eq.2 h ▸ d.refl _ in ext $ λ x y, ⟨λ h, let ⟨a, b, hx, hy, H⟩ := h in hx ▸ hy ▸ H, con.induction_on₂ x y $ λ w z h, ⟨w, z, rfl, rfl, h⟩⟩, map_rel_iff' := λ s t, ⟨λ h _ _ hs, let ⟨a, b, hx, hy, ht⟩ := h ⟨_, _, rfl, rfl, hs⟩ in t.1.trans (t.1.symm $ t.2 $ eq_rel.1 hx) $ t.1.trans ht $ t.2 $ eq_rel.1 hy, λ h _ _ hs, let ⟨a, b, hx, hy, Hs⟩ := hs in ⟨a, b, hx, hy, h Hs⟩⟩ } end end section mul_one_class variables {M} [mul_one_class M] [mul_one_class N] [mul_one_class P] (c : con M) /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance mul_one_class : mul_one_class c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_one := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ mul_one _, one_mul := λ x, quotient.induction_on' x $ λ _, congr_arg coe $ one_mul _ } variables {c} /-- The 1 of the quotient of a monoid by a congruence relation is the equivalence class of the monoid's 1. -/ @[simp, to_additive "The 0 of the quotient of an `add_monoid` by an additive congruence relation is the equivalence class of the `add_monoid`'s 0."] lemma coe_one : ((1 : M) : c.quotient) = 1 := rfl variables (M c) /-- The submonoid of `M × M` defined by a congruence relation on a monoid `M`. -/ @[to_additive "The `add_submonoid` of `M × M` defined by an additive congruence relation on an `add_monoid` `M`."] protected def submonoid : submonoid (M × M) := { carrier := { x | c x.1 x.2 }, one_mem' := c.iseqv.1 1, mul_mem' := λ _ _, c.mul } variables {M c} /-- The congruence relation on a monoid `M` from a submonoid of `M × M` for which membership is an equivalence relation. -/ @[to_additive "The additive congruence relation on an `add_monoid` `M` from an `add_submonoid` of `M × M` for which membership is an equivalence relation."] def of_submonoid (N : submonoid (M × M)) (H : equivalence (λ x y, (x, y) ∈ N)) : con M := { r := λ x y, (x, y) ∈ N, iseqv := H, mul' := λ _ _ _ _, N.mul_mem } /-- Coercion from a congruence relation `c` on a monoid `M` to the submonoid of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`. -/ @[to_additive "Coercion from a congruence relation `c` on an `add_monoid` `M` to the `add_submonoid` of `M × M` whose elements are `(x, y)` such that `x` is related to `y` by `c`."] instance to_submonoid : has_coe (con M) (submonoid (M × M)) := ⟨λ c, c.submonoid M⟩ @[to_additive] lemma mem_coe {c : con M} {x y} : (x, y) ∈ (↑c : submonoid (M × M)) ↔ (x, y) ∈ c := iff.rfl @[to_additive] theorem to_submonoid_inj (c d : con M) (H : (c : submonoid (M × M)) = d) : c = d := ext $ λ x y, show (x, y) ∈ (c : submonoid (M × M)) ↔ (x, y) ∈ ↑d, by rw H @[to_additive] lemma le_iff {c d : con M} : c ≤ d ↔ (c : submonoid (M × M)) ≤ d := ⟨λ h x H, h H, λ h x y hc, h $ show (x, y) ∈ c, from hc⟩ /-- The kernel of a monoid homomorphism as a congruence relation. -/ @[to_additive "The kernel of an `add_monoid` homomorphism as an additive congruence relation."] def ker (f : M →* P) : con M := mul_ker f f.3 /-- The definition of the congruence relation defined by a monoid homomorphism's kernel. -/ @[to_additive "The definition of the additive congruence relation defined by an `add_monoid` homomorphism's kernel."] lemma ker_rel (f : M →* P) {x y} : ker f x y ↔ f x = f y := iff.rfl /-- There exists an element of the quotient of a monoid by a congruence relation (namely 1). -/ @[to_additive "There exists an element of the quotient of an `add_monoid` by a congruence relation (namely 0)."] instance quotient.inhabited : inhabited c.quotient := ⟨((1 : M) : c.quotient)⟩ variables (c) /-- The natural homomorphism from a monoid to its quotient by a congruence relation. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation."] def mk' : M →* c.quotient := ⟨coe, rfl, λ _ _, rfl⟩ variables (x y : M) /-- The kernel of the natural homomorphism from a monoid to its quotient by a congruence relation `c` equals `c`. -/ @[simp, to_additive "The kernel of the natural homomorphism from an `add_monoid` to its quotient by an additive congruence relation `c` equals `c`."] lemma mk'_ker : ker c.mk' = c := ext $ λ _ _, c.eq variables {c} /-- The natural homomorphism from a monoid to its quotient by a congruence relation is surjective. -/ @[to_additive "The natural homomorphism from an `add_monoid` to its quotient by a congruence relation is surjective."] lemma mk'_surjective : surjective c.mk' := λ x, by rcases x; exact ⟨x, rfl⟩ @[simp, to_additive] lemma comp_mk'_apply (g : c.quotient →* P) {x} : g.comp c.mk' x = g x := rfl /-- The elements related to `x ∈ M`, `M` a monoid, by the kernel of a monoid homomorphism are those in the preimage of `f(x)` under `f`. -/ @[to_additive "The elements related to `x ∈ M`, `M` an `add_monoid`, by the kernel of an `add_monoid` homomorphism are those in the preimage of `f(x)` under `f`. "] lemma ker_apply_eq_preimage {f : M →* P} (x) : (ker f) x = f ⁻¹' {f x} := set.ext $ λ x, ⟨λ h, set.mem_preimage.2 $ set.mem_singleton_iff.2 h.symm, λ h, (set.mem_singleton_iff.1 $ set.mem_preimage.1 h).symm⟩ /-- Given a monoid homomorphism `f : N → M` and a congruence relation `c` on `M`, the congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`. -/ @[to_additive "Given an `add_monoid` homomorphism `f : N → M` and an additive congruence relation `c` on `M`, the additive congruence relation induced on `N` by `f` equals the kernel of `c`'s quotient homomorphism composed with `f`."] lemma comap_eq {f : N →* M} : comap f f.map_mul c = ker (c.mk'.comp f) := ext $ λ x y, show c _ _ ↔ c.mk' _ = c.mk' _, by rw ←c.eq; refl variables (c) (f : M →* P) /-- The homomorphism on the quotient of a monoid by a congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes. -/ @[to_additive "The homomorphism on the quotient of an `add_monoid` by an additive congruence relation `c` induced by a homomorphism constant on `c`'s equivalence classes."] def lift (H : c ≤ ker f) : c.quotient →* P := { to_fun := λ x, con.lift_on x f $ λ _ _ h, H h, map_one' := by rw ←f.map_one; refl, map_mul' := λ x y, con.induction_on₂ x y $ λ m n, f.map_mul m n ▸ rfl } variables {c f} /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_mk' (H : c ≤ ker f) (x) : c.lift f H (c.mk' x) = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] lemma lift_coe (H : c ≤ ker f) (x : M) : c.lift f H x = f x := rfl /-- The diagram describing the universal property for quotients of monoids commutes. -/ @[simp, to_additive "The diagram describing the universal property for quotients of `add_monoid`s commutes."] theorem lift_comp_mk' (H : c ≤ ker f) : (c.lift f H).comp c.mk' = f := by ext; refl /-- Given a homomorphism `f` from the quotient of a monoid by a congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the monoid to the quotient. -/ @[simp, to_additive "Given a homomorphism `f` from the quotient of an `add_monoid` by an additive congruence relation, `f` equals the homomorphism on the quotient induced by `f` composed with the natural map from the `add_monoid` to the quotient."] lemma lift_apply_mk' (f : c.quotient →* P) : c.lift (f.comp c.mk') (λ x y h, show f ↑x = f ↑y, by rw c.eq.2 h) = f := by ext; rcases x; refl /-- Homomorphisms on the quotient of a monoid by a congruence relation are equal if they are equal on elements that are coercions from the monoid. -/ @[to_additive "Homomorphisms on the quotient of an `add_monoid` by an additive congruence relation are equal if they are equal on elements that are coercions from the `add_monoid`."] lemma lift_funext (f g : c.quotient →* P) (h : ∀ a : M, f a = g a) : f = g := begin rw [←lift_apply_mk' f, ←lift_apply_mk' g], congr' 1, exact monoid_hom.ext_iff.2 h, end /-- The uniqueness part of the universal property for quotients of monoids. -/ @[to_additive "The uniqueness part of the universal property for quotients of `add_monoid`s."] theorem lift_unique (H : c ≤ ker f) (g : c.quotient →* P) (Hg : g.comp c.mk' = f) : g = c.lift f H := lift_funext g (c.lift f H) $ λ x, by rw [lift_coe H, ←comp_mk'_apply, Hg] /-- Given a congruence relation `c` on a monoid and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient. -/ @[to_additive "Given an additive congruence relation `c` on an `add_monoid` and a homomorphism `f` constant on `c`'s equivalence classes, `f` has the same image as the homomorphism that `f` induces on the quotient."] theorem lift_range (H : c ≤ ker f) : (c.lift f H).mrange = f.mrange := submonoid.ext $ λ x, ⟨by rintros ⟨⟨y⟩, hy⟩; exact ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨↑y, hy⟩⟩ /-- Surjective monoid homomorphisms constant on a congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient. -/ @[to_additive "Surjective `add_monoid` homomorphisms constant on an additive congruence relation `c`'s equivalence classes induce a surjective homomorphism on `c`'s quotient."] lemma lift_surjective_of_surjective (h : c ≤ ker f) (hf : surjective f) : surjective (c.lift f h) := λ y, exists.elim (hf y) $ λ w hw, ⟨w, (lift_mk' h w).symm ▸ hw⟩ variables (c f) /-- Given a monoid homomorphism `f` from `M` to `P`, the kernel of `f` is the unique congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective. -/ @[to_additive "Given an `add_monoid` homomorphism `f` from `M` to `P`, the kernel of `f` is the unique additive congruence relation on `M` whose induced map from the quotient of `M` to `P` is injective."] lemma ker_eq_lift_of_injective (H : c ≤ ker f) (h : injective (c.lift f H)) : ker f = c := to_setoid_inj $ ker_eq_lift_of_injective f H h variables {c} /-- The homomorphism induced on the quotient of a monoid by the kernel of a monoid homomorphism. -/ @[to_additive "The homomorphism induced on the quotient of an `add_monoid` by the kernel of an `add_monoid` homomorphism."] def ker_lift : (ker f).quotient →* P := (ker f).lift f $ λ _ _, id variables {f} /-- The diagram described by the universal property for quotients of monoids, when the congruence relation is the kernel of the homomorphism, commutes. -/ @[simp, to_additive "The diagram described by the universal property for quotients of `add_monoid`s, when the additive congruence relation is the kernel of the homomorphism, commutes."] lemma ker_lift_mk (x : M) : ker_lift f x = f x := rfl /-- Given a monoid homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`. -/ @[simp, to_additive "Given an `add_monoid` homomorphism `f`, the induced homomorphism on the quotient by `f`'s kernel has the same image as `f`."] lemma ker_lift_range_eq : (ker_lift f).mrange = f.mrange := lift_range $ λ _ _, id /-- A monoid homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel. -/ @[to_additive "An `add_monoid` homomorphism `f` induces an injective homomorphism on the quotient by `f`'s kernel."] lemma ker_lift_injective (f : M →* P) : injective (ker_lift f) := λ x y, quotient.induction_on₂' x y $ λ _ _, (ker f).eq.2 /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, `d`'s quotient map induces a homomorphism from the quotient by `c` to the quotient by `d`."] def map (c d : con M) (h : c ≤ d) : c.quotient →* d.quotient := c.lift d.mk' $ λ x y hc, show (ker d.mk') x y, from (mk'_ker d).symm ▸ h hc /-- Given congruence relations `c, d` on a monoid such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map. -/ @[to_additive "Given additive congruence relations `c, d` on an `add_monoid` such that `d` contains `c`, the definition of the homomorphism from the quotient by `c` to the quotient by `d` induced by `d`'s quotient map."] lemma map_apply {c d : con M} (h : c ≤ d) (x) : c.map d h x = c.lift d.mk' (λ x y hc, d.eq.2 $ h hc) x := rfl variables (c) /-- The first isomorphism theorem for monoids. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s."] noncomputable def quotient_ker_equiv_range (f : M →* P) : (ker f).quotient ≃* f.mrange := { map_mul' := monoid_hom.map_mul _, ..equiv.of_bijective ((@mul_equiv.to_monoid_hom (ker_lift f).mrange _ _ _ $ mul_equiv.submonoid_congr ker_lift_range_eq).comp (ker_lift f).mrange_restrict) $ (equiv.bijective _).comp ⟨λ x y h, ker_lift_injective f $ by rcases x; rcases y; injections, λ ⟨w, z, hz⟩, ⟨z, by rcases hz; rcases _x; refl⟩⟩ } /-- The first isomorphism theorem for monoids in the case of a homomorphism with right inverse. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a homomorphism with right inverse.", simps] def quotient_ker_equiv_of_right_inverse (f : M →* P) (g : P → M) (hf : function.right_inverse g f) : (ker f).quotient ≃* P := { to_fun := ker_lift f, inv_fun := coe ∘ g, left_inv := λ x, ker_lift_injective _ (by rw [function.comp_app, ker_lift_mk, hf]), right_inv := hf, .. ker_lift f } /-- The first isomorphism theorem for monoids in the case of a surjective homomorphism. For a `computable` version, see `con.quotient_ker_equiv_of_right_inverse`. -/ @[to_additive "The first isomorphism theorem for `add_monoid`s in the case of a surjective homomorphism. For a `computable` version, see `add_con.quotient_ker_equiv_of_right_inverse`. "] noncomputable def quotient_ker_equiv_of_surjective (f : M →* P) (hf : surjective f) : (ker f).quotient ≃* P := quotient_ker_equiv_of_right_inverse _ _ hf.has_right_inverse.some_spec /-- The second isomorphism theorem for monoids. -/ @[to_additive "The second isomorphism theorem for `add_monoid`s."] noncomputable def comap_quotient_equiv (f : N →* M) : (comap f f.map_mul c).quotient ≃* (c.mk'.comp f).mrange := (con.congr comap_eq).trans $ quotient_ker_equiv_range $ c.mk'.comp f /-- The third isomorphism theorem for monoids. -/ @[to_additive "The third isomorphism theorem for `add_monoid`s."] def quotient_quotient_equiv_quotient (c d : con M) (h : c ≤ d) : (ker (c.map d h)).quotient ≃* d.quotient := { map_mul' := λ x y, con.induction_on₂ x y $ λ w z, con.induction_on₂ w z $ λ a b, show _ = d.mk' a * d.mk' b, by rw ←d.mk'.map_mul; refl, ..quotient_quotient_equiv_quotient c.to_setoid d.to_setoid h } end mul_one_class section monoids /-- The quotient of a monoid by a congruence relation is a monoid. -/ @[to_additive "The quotient of an `add_monoid` by an additive congruence relation is an `add_monoid`."] instance monoid {M : Type*} [monoid M] (c : con M): monoid c.quotient := { one := ((1 : M) : c.quotient), mul := (*), mul_assoc := λ x y z, quotient.induction_on₃' x y z $ λ _ _ _, congr_arg coe $ mul_assoc _ _ _, .. c.mul_one_class } /-- The quotient of a `comm_monoid` by a congruence relation is a `comm_monoid`. -/ @[to_additive "The quotient of an `add_comm_monoid` by an additive congruence relation is an `add_comm_monoid`."] instance comm_monoid {M : Type*} [comm_monoid M] (c : con M) : comm_monoid c.quotient := { mul_comm := λ x y, con.induction_on₂ x y $ λ w z, by rw [←coe_mul, ←coe_mul, mul_comm], ..c.monoid} end monoids section groups variables {M} [group M] [group N] [group P] (c : con M) /-- Multiplicative congruence relations preserve inversion. -/ @[to_additive "Additive congruence relations preserve negation."] protected lemma inv : ∀ {w x}, c w x → c w⁻¹ x⁻¹ := λ x y h, by simpa using c.symm (c.mul (c.mul (c.refl x⁻¹) h) (c.refl y⁻¹)) /-- The inversion induced on the quotient by a congruence relation on a type with a inversion. -/ @[to_additive "The negation induced on the quotient by an additive congruence relation on a type with an negation."] instance has_inv : has_inv c.quotient := ⟨λ x, quotient.lift_on' x (λ w, ((w⁻¹ : M) : c.quotient)) $ λ x y h, c.eq.2 $ c.inv h⟩ /-- The quotient of a group by a congruence relation is a group. -/ @[to_additive "The quotient of an `add_group` by an additive congruence relation is an `add_group`."] instance group : group c.quotient := { inv := λ x, x⁻¹, mul_left_inv := λ x, show x⁻¹ * x = 1, from quotient.induction_on' x $ λ _, congr_arg coe $ mul_left_inv _, .. con.monoid c} end groups end con
58454d745b4658980cca1fc5fe1ca7062fc36e24
137c667471a40116a7afd7261f030b30180468c2
/src/algebra/indicator_function.lean
7aa2fa47888a7a8f0c995f05a84a9dffde582923
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,289
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.group.pi import group_theory.group_action import algebra.support import data.finset.lattice /-! # Indicator function - `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise. - `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise. ## Implementation note In mathematics, an indicator function or a characteristic function is a function used to indicate membership of an element in a set `s`, having the value `1` for all elements of `s` and the value `0` otherwise. But since it is usually used to restrict a function to a certain set `s`, we let the indicator function take the value `f x` for some function `f`, instead of `1`. If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`. ## Tags indicator, characteristic -/ noncomputable theory open_locale classical big_operators open function variables {α β ι M N : Type*} namespace set section has_one variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α} /-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/ def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 0 /-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/ @[to_additive] def mul_indicator (s : set α) (f : α → M) : α → M := λ x, if x ∈ s then f x else 1 @[simp, to_additive] lemma piecewise_eq_mul_indicator : s.piecewise f 1 = s.mul_indicator f := rfl @[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) : mul_indicator s f a = if a ∈ s then f a else 1 := rfl @[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) : mul_indicator s f a = f a := if_pos h @[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) : mul_indicator s f a = 1 := if_neg h @[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) : mul_indicator s f a = 1 ∨ mul_indicator s f a = f a := if h : a ∈ s then or.inr (mul_indicator_of_mem h f) else or.inl (mul_indicator_of_not_mem h f) @[simp, to_additive] lemma mul_indicator_apply_eq_self : s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) := ite_eq_left_iff.trans $ by rw [@eq_comm _ (f a)] @[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s := by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm] @[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) : t.mul_indicator f = f := by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 } @[simp, to_additive] lemma mul_indicator_apply_eq_one : mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) := ite_eq_right_iff @[simp, to_additive] lemma mul_indicator_eq_one : mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s := by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support, not_imp_not] @[simp, to_additive] lemma mul_indicator_eq_one' : mul_indicator s f = 1 ↔ disjoint (mul_support f) s := mul_indicator_eq_one @[simp, to_additive] lemma mul_support_mul_indicator : function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f := ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one] /-- If a multiplicative indicator function is not equal to one at a point, then that point is in the set. -/ @[to_additive] lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s := not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h @[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s := λ x hx, mul_indicator_of_mem hx f @[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s := λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f) @[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f := mul_indicator_eq_self.2 subset.rfl @[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) : mul_indicator (range f) g ∘ f = g ∘ f := piecewise_range_comp _ _ _ @[to_additive] lemma mul_indicator_congr (h : eq_on f g s) : mul_indicator s f = mul_indicator s g := funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl } @[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f := mul_indicator_eq_self.2 $ subset_univ _ @[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 := mul_indicator_eq_one.2 $ disjoint_empty _ @[to_additive] lemma mul_indicator_empty' (f : α → M) : mul_indicator (∅ : set α) f = 1 := mul_indicator_empty f variable (M) @[simp, to_additive] lemma mul_indicator_one (s : set α) : mul_indicator s (λx, (1:M)) = λx, (1:M) := mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint] @[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 := mul_indicator_one M s variable {M} @[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) : mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f := funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} } @[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) : mul_indicator (s ∩ mul_support f) f = mul_indicator s f := by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support] @[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α} : h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x := s.apply_piecewise _ _ (λ _, h) @[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} : mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) := by { simp only [mul_indicator], split_ifs; refl } @[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) : mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) := begin funext, simp only [mul_indicator], split_ifs; simp [*] end @[to_additive] lemma comp_mul_indicator_const (c : M) (f : M → N) (hf : f 1 = 1) : (λ x, f (s.mul_indicator (λ x, c) x)) = s.mul_indicator (λ x, f c) := (mul_indicator_comp_of_one hf).symm @[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) : (mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) := piecewise_preimage s f 1 B @[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M) {t : set M} (ht : (1:M) ∉ t) : (mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s := by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht] @[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} : r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm, @eq_comm _ r 1] @[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1) (ha : a ∈ s → r (f a) (g a)) : r (mul_indicator s f a) (mul_indicator s g a) := by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] } end has_one section monoid variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α} @[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) : mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a = mul_indicator s f a * mul_indicator t f a := by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp * @[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) : mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f := funext $ mul_indicator_union_mul_inter_apply f s t @[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) : mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a := by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one] @[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) : mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a := funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h ha) _ @[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) : mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a := by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one } @[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) : mul_indicator sᶜ f a * mul_indicator s f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) : mul_indicator sᶜ f * mul_indicator s f = f := funext $ mul_indicator_compl_mul_self_apply s f @[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) : mul_indicator s f a * mul_indicator sᶜ f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) : mul_indicator s f * mul_indicator sᶜ f = f := funext $ mul_indicator_self_mul_compl_apply s f @[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support f).mul_indicator (f * g) = f := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx), rw [pi.mul_apply, this, mul_one] end @[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support g).mul_indicator (f * g) = g := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx), rw [pi.mul_apply, this, one_mul] end /-- `set.mul_indicator` as a `monoid_hom`. -/ @[to_additive "`set.indicator` as an `add_monoid_hom`."] def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) := { to_fun := mul_indicator s, map_one' := mul_indicator_one M s, map_mul' := mul_indicator_mul s } end monoid section distrib_mul_action variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A] lemma indicator_smul (s : set α) (r : M) (f : α → A) : indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x := by { simp only [indicator], funext, split_ifs, refl, exact (smul_zero r).symm } end distrib_mul_action section group variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α} @[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) : mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ := (mul_indicator_hom G s).map_inv f @[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) : mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ := mul_indicator_inv' s f lemma indicator_sub {G} [add_group G] (s : set α) (f g : α → G) : indicator s (λa, f a - g a) = λa, indicator s f a - indicator s g a := (indicator_hom G s).map_sub f g @[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) : mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) : indicator sᶜ f = f - indicator s f := by rw [sub_eq_add_neg, indicator_compl'] @[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) : mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ by rw [pi.mul_def, ← mul_indicator_union_of_disjoint disjoint_diff.symm f, diff_union_self, union_eq_self_of_subset_right h] lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) : indicator (t \ s) f = indicator t f - indicator s f := by rw [indicator_diff' h, sub_eq_add_neg] end group section comm_monoid variables [comm_monoid M] /-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a function such as `pow`, which maps a second argument of `1` to `1`. Then if `f` is replaced by the corresponding multiplicative indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ @[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N) (g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) : ∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) := begin rw ← finset.prod_subset h _, { apply finset.prod_congr rfl, intros i hi, congr, symmetry, exact mul_indicator_of_mem hi _ }, { refine λ i hi hn, _, convert hg i, exact mul_indicator_of_not_mem hn _ } end /-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a function such as multiplication, which maps a second argument of 0 to 0. (A typical use case would be a weighted sum of `f i * h i` or `f i • h i`, where `f` gives the weights that are multiplied by some other function `h`.) Then if `f` is replaced by the corresponding indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ add_decl_doc set.sum_indicator_subset_of_eq_zero @[to_additive] lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) : ∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i := prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl) /-- Summing an indicator function over a possibly larger `finset` is the same as summing the original function over the original `finset`. -/ add_decl_doc sum_indicator_subset @[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) : mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) := (mul_indicator_hom M s).map_prod _ _ @[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι) (s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) → mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a := begin refine finset.induction_on I _ _, { intro h, funext, simp }, assume a I haI ih hI, funext, rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _], { assume i hi j hj hij, exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij }, simp only [not_exists, exists_prop, mem_Union, mem_inter_eq, not_and], assume hx a' ha', refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx, exact (ne_of_mem_of_not_mem ha' haI).symm end end comm_monoid section mul_zero_class variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α} lemma indicator_mul (s : set α) (f g : α → M) : indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero } lemma indicator_mul_left (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = indicator s f a * g a := by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] } lemma indicator_mul_right (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = f a * indicator s g a := by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] } lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) : (t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x := by { rw [← set.indicator_indicator], simp [indicator] } end mul_zero_class section monoid_with_zero variables [monoid_with_zero M] lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} : (s.prod t).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y := by simp [indicator, ← ite_and] end monoid_with_zero section order variables [has_one M] [preorder M] {s t : set α} {f g : α → M} {a : α} {y : M} @[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) : mul_indicator s f a ≤ y := if ha : a ∈ s then by simpa [ha] using hfg ha else by simpa [ha] using hg ha @[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) : mul_indicator s f ≤ g := λ a, mul_indicator_apply_le' (hfg _) (hg _) @[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) : y ≤ mul_indicator s g a := @mul_indicator_apply_le' α (order_dual M) ‹_› _ _ _ _ _ hfg hf @[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) : f ≤ mul_indicator s g := λ a, le_mul_indicator_apply (hfg _) (hf _) @[to_additive indicator_apply_nonneg] lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a := le_mul_indicator_apply h (λ _, le_rfl) @[to_additive indicator_nonneg] lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a := one_le_mul_indicator_apply (h a) @[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le' h (λ _, le_rfl) @[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le_one (h a) @[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) : mul_indicator s f a ≤ mul_indicator s g a := mul_indicator_rel_mul_indicator (le_refl _) (λ _, h) attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator @[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a) (a : α) : mul_indicator s f a ≤ mul_indicator t f a := mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim)) (λ ha, one_le_mul_indicator_apply (λ _, hf _)) @[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f := mul_indicator_le' (λ _ _, le_refl _) hf @[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M] (h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) : mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x := begin by_cases hx : x ∈ ⋃ i, s i, { rw [mul_indicator_of_mem hx], rw [mem_Union] at hx, refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x), rcases hx with ⟨i, hi⟩, exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) }, { rw [mul_indicator_of_not_mem hx], simp only [mem_Union, not_exists] at hx, simp [hx, ← h1] } end end order section canonically_ordered_monoid variables [canonically_ordered_monoid M] @[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) : mul_indicator s f ≤ f := mul_indicator_le_self' $ λ _ _, one_le _ @[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M} (hfg : a ∈ s → f a ≤ g a) : mul_indicator s f a ≤ g a := mul_indicator_apply_le' hfg $ λ _, one_le _ @[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) : mul_indicator s f ≤ g := mul_indicator_le' hfg $ λ _ _, one_le _ end canonically_ordered_monoid end set @[to_additive] lemma monoid_hom.map_mul_indicator {M N : Type*} [monoid M] [monoid N] (f : M →* N) (s : set α) (g : α → M) (x : α) : f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x := congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
b267f9edd067ed255016dce51184a70748fb865c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finset/slice.lean
5014f7ed74cc531ff868a8d8ea0758ba3ad93451
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
5,275
lean
/- Copyright (c) 2021 Bhavik Mehta, Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Alena Gusakov, Yaël Dillies -/ import algebra.big_operators.basic import data.nat.interval import order.antichain /-! # `r`-sets and slice This file defines the `r`-th slice of a set family and provides a way to say that a set family is made of `r`-sets. An `r`-set is a finset of cardinality `r` (aka of *size* `r`). The `r`-th slice of a set family is the set family made of its `r`-sets. ## Main declarations * `set.sized`: `A.sized r` means that `A` only contains `r`-sets. * `finset.slice`: `A.slice r` is the set of `r`-sets in `A`. ## Notation `A # r` is notation for `A.slice r` in locale `finset_family`. -/ open finset nat open_locale big_operators variables {α : Type*} {ι : Sort*} {κ : ι → Sort*} namespace set variables {A B : set (finset α)} {r : ℕ} /-! ### Families of `r`-sets -/ /-- `sized r A` means that every finset in `A` has size `r`. -/ def sized (r : ℕ) (A : set (finset α)) : Prop := ∀ ⦃x⦄, x ∈ A → card x = r lemma sized.mono (h : A ⊆ B) (hB : B.sized r) : A.sized r := λ x hx, hB $ h hx lemma sized_union : (A ∪ B).sized r ↔ A.sized r ∧ B.sized r := ⟨λ hA, ⟨hA.mono $ subset_union_left _ _, hA.mono $ subset_union_right _ _⟩, λ hA x hx, hx.elim (λ h, hA.1 h) $ λ h, hA.2 h⟩ alias sized_union ↔ _ sized.union --TODO: A `forall_Union` lemma would be handy here. @[simp] lemma sized_Union {f : ι → set (finset α)} : (⋃ i, f i).sized r ↔ ∀ i, (f i).sized r := by { simp_rw [set.sized, set.mem_Union, forall_exists_index], exact forall_swap } @[simp] lemma sized_Union₂ {f : Π i, κ i → set (finset α)} : (⋃ i j, f i j).sized r ↔ ∀ i j, (f i j).sized r := by simp_rw sized_Union protected lemma sized.is_antichain (hA : A.sized r) : is_antichain (⊆) A := λ s hs t ht h hst, h $ finset.eq_of_subset_of_card_le hst ((hA ht).trans (hA hs).symm).le protected lemma sized.subsingleton (hA : A.sized 0) : A.subsingleton := subsingleton_of_forall_eq ∅ $ λ s hs, card_eq_zero.1 $ hA hs lemma sized.subsingleton' [fintype α] (hA : A.sized (fintype.card α)) : A.subsingleton := subsingleton_of_forall_eq finset.univ $ λ s hs, s.card_eq_iff_eq_univ.1 $ hA hs lemma sized.empty_mem_iff (hA : A.sized r) : ∅ ∈ A ↔ A = {∅} := hA.is_antichain.bot_mem_iff lemma sized.univ_mem_iff [fintype α] (hA : A.sized r) : finset.univ ∈ A ↔ A = {finset.univ} := hA.is_antichain.top_mem_iff lemma sized_powerset_len (s : finset α) (r : ℕ) : (powerset_len r s : set (finset α)).sized r := λ t ht, (mem_powerset_len.1 ht).2 end set namespace finset section sized variables [fintype α] {𝒜 : finset (finset α)} {s : finset α} {r : ℕ} lemma subset_powerset_len_univ_iff : 𝒜 ⊆ powerset_len r univ ↔ (𝒜 : set (finset α)).sized r := forall_congr $ λ A, by rw [mem_powerset_len_univ_iff, mem_coe] alias subset_powerset_len_univ_iff ↔ _ _root_.set.sized.subset_powerset_len_univ lemma _root_.set.sized.card_le (h𝒜 : (𝒜 : set (finset α)).sized r) : card 𝒜 ≤ (fintype.card α).choose r := begin rw [fintype.card, ←card_powerset_len], exact card_le_of_subset h𝒜.subset_powerset_len_univ, end end sized /-! ### Slices -/ section slice variables {𝒜 : finset (finset α)} {A A₁ A₂ : finset α} {r r₁ r₂ : ℕ} /-- The `r`-th slice of a set family is the subset of its elements which have cardinality `r`. -/ def slice (𝒜 : finset (finset α)) (r : ℕ) : finset (finset α) := 𝒜.filter (λ i, i.card = r) localized "infix (name := finset.slice) ` # `:90 := finset.slice" in finset_family /-- `A` is in the `r`-th slice of `𝒜` iff it's in `𝒜` and has cardinality `r`. -/ lemma mem_slice : A ∈ 𝒜 # r ↔ A ∈ 𝒜 ∧ A.card = r := mem_filter /-- The `r`-th slice of `𝒜` is a subset of `𝒜`. -/ lemma slice_subset : 𝒜 # r ⊆ 𝒜 := filter_subset _ _ /-- Everything in the `r`-th slice of `𝒜` has size `r`. -/ lemma sized_slice : (𝒜 # r : set (finset α)).sized r := λ _, and.right ∘ mem_slice.mp lemma eq_of_mem_slice (h₁ : A ∈ 𝒜 # r₁) (h₂ : A ∈ 𝒜 # r₂) : r₁ = r₂ := (sized_slice h₁).symm.trans $ sized_slice h₂ /-- Elements in distinct slices must be distinct. -/ lemma ne_of_mem_slice (h₁ : A₁ ∈ 𝒜 # r₁) (h₂ : A₂ ∈ 𝒜 # r₂) : r₁ ≠ r₂ → A₁ ≠ A₂ := mt $ λ h, (sized_slice h₁).symm.trans ((congr_arg card h).trans (sized_slice h₂)) lemma pairwise_disjoint_slice : (set.univ : set ℕ).pairwise_disjoint (slice 𝒜) := λ m _ n _ hmn, disjoint_filter.2 $ λ s hs hm hn, hmn $ hm.symm.trans hn variables [fintype α] (𝒜) @[simp] lemma bUnion_slice [decidable_eq α] : (Iic $ fintype.card α).bUnion 𝒜.slice = 𝒜 := subset.antisymm (bUnion_subset.2 $ λ r _, slice_subset) $ λ s hs, mem_bUnion.2 ⟨s.card, mem_Iic.2 $ s.card_le_univ, mem_slice.2 $ ⟨hs, rfl⟩⟩ @[simp] lemma sum_card_slice : ∑ r in Iic (fintype.card α), (𝒜 # r).card = 𝒜.card := begin letI := classical.dec_eq α, rw [←card_bUnion, bUnion_slice], exact finset.pairwise_disjoint_slice.subset (set.subset_univ _), end end slice end finset
ad07484289cb0a3a9dbbf0106d30deb60604058c
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Tactic/Injection.lean
d693d317be3356cc445fa87d41a65e32fb232128
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,408
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Injection import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic -- optional (" with " >> many1 ident') private def getInjectionNewIds (stx : Syntax) : List Name := if stx.isNone then [] else stx[1].getArgs.toList.map getNameOfIdent' private def checkUnusedIds (mvarId : MVarId) (unusedIds : List Name) : MetaM Unit := unless unusedIds.isEmpty do Meta.throwTacticEx `injection mvarId m!"too many identifiers provided, unused: {unusedIds}" @[builtinTactic «injection»] def evalInjection : Tactic := fun stx => do -- leading_parser nonReservedSymbol "injection " >> termParser >> withIds let fvarId ← elabAsFVar stx[1] let ids := getInjectionNewIds stx[2] liftMetaTactic fun mvarId => do match (← Meta.injection mvarId fvarId ids) with | Meta.InjectionResult.solved => checkUnusedIds mvarId ids; return [] | Meta.InjectionResult.subgoal mvarId' _ unusedIds => checkUnusedIds mvarId unusedIds; return [mvarId'] @[builtinTactic «injections»] def evalInjections : Tactic := fun stx => do liftMetaTactic fun mvarId => do match (← Meta.injections mvarId) with | none => return [] | some mvarId => return [mvarId] end Lean.Elab.Tactic
2cf2ab8b00bb851f525db5f0a199cc10b99243ea
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/bench/rbmap3.lean
d025d84f9f70f54d08773012f556ea68d3f98fcc
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
8,993
lean
prelude import init.core init.system.io init.data.ordering universes u v w inductive Rbcolor | red | black inductive Rbnode (α : Type u) (β : α → Type v) | leaf {} : Rbnode | Node (c : Rbcolor) (lchild : Rbnode) (key : α) (val : β key) (rchild : Rbnode) : Rbnode instance Rbcolor.DecidableEq : DecidableEq Rbcolor := {decEq := fun a b => Rbcolor.casesOn a (Rbcolor.casesOn b (isTrue rfl) (isFalse (fun h => Rbcolor.noConfusion h))) (Rbcolor.casesOn b (isFalse (fun h => Rbcolor.noConfusion h)) (isTrue rfl))} namespace Rbnode variable {α : Type u} {β : α → Type v} {σ : Type w} open Rbcolor def depth (f : Nat → Nat → Nat) : Rbnode α β → Nat | leaf => 0 | Node _ l _ _ r => (f (depth l) (depth r)) + 1 protected def min : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ leaf k v _ => some ⟨k, v⟩ | Node _ l k v _ => min l protected def max : Rbnode α β → Option (Sigma (fun k => β k)) | leaf => none | Node _ _ k v leaf => some ⟨k, v⟩ | Node _ _ k v r => max r @[specialize] def fold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => fold r (f k v (fold l b)) @[specialize] def revFold (f : ∀ (k : α), β k → σ → σ) : Rbnode α β → σ → σ | leaf, b => b | Node _ l k v r, b => revFold l (f k v (revFold r b)) @[specialize] def all (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => true | Node _ l k v r => p k v && all l && all r @[specialize] def any (p : ∀ (k : α), β k → Bool) : Rbnode α β → Bool | leaf => false | Node _ l k v r => p k v || any l || any r def isRed : Rbnode α β → Bool | Node red _ _ _ _ => true | _ => false def rotateLeft : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc hl hk hv (Node red xl xk xv xr)), _ => if !isRed hl then (Node hc (Node red hl hk hv xl) xk xv xr) else n | leaf, h => absurd rfl h | e, _ => e theorem ifNodeNodeNeLeaf {c : Prop} [Decidable c] {l1 l2 : Rbnode α β} {c1 k1 v1 r1 c2 k2 v2 r2} : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) ≠ leaf := fun h => if hc : c then have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c1 l1 k1 v1 r1 from ifPos hc; Rbnode.noConfusion (Eq.trans h1.symm h) else have h1 : (if c then Node c1 l1 k1 v1 r1 else Node c2 l2 k2 v2 r2) = Node c2 l2 k2 v2 r2 from ifNeg hc; Rbnode.noConfusion (Eq.trans h1.symm h) theorem rotateLeftNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateLeft n h ≠ leaf | Node _ hl _ _ (Node red _ _ _ _), _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ _ _ _ (Node black _ _ _ _), _, h => Rbnode.noConfusion h def rotateRight : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node hc (Node red xl xk xv xr) hk hv hr), _ => if isRed xl then (Node hc xl xk xv (Node red xr hk hv hr)) else n | leaf, h => absurd rfl h | e, _ => e theorem rotateRightNeLeaf : ∀ (n : Rbnode α β) (h : n ≠ leaf), rotateRight n h ≠ leaf | Node _ (Node red _ _ _ _) _ _ _, _, h => ifNodeNodeNeLeaf h | leaf, h, _ => absurd rfl h | Node _ (Node black _ _ _ _) _ _ _, _, h => Rbnode.noConfusion h def flip : Rbcolor → Rbcolor | red => black | black => red def flipColor : Rbnode α β → Rbnode α β | Node c l k v r => Node (flip c) l k v r | leaf => leaf def flipColors : ∀ (n : Rbnode α β), n ≠ leaf → Rbnode α β | n@(Node c l k v r), _ => if isRed l ∧ isRed r then Node (flip c) (flipColor l) k v (flipColor r) else n | leaf, h => absurd rfl h def fixup (n : Rbnode α β) (h : n ≠ leaf) : Rbnode α β := let n₁ := rotateLeft n h; let h₁ := (rotateLeftNeLeaf n h); let n₂ := rotateRight n₁ h₁; let h₂ := (rotateRightNeLeaf n₁ h₁); flipColors n₂ h₂ def setBlack : Rbnode α β → Rbnode α β | Node red l k v r => Node black l k v r | n => n section insert variable (lt : α → α → Prop) [DecidableRel lt] def ins (x : α) (vx : β x) : Rbnode α β → Rbnode α β | leaf => Node red leaf x vx leaf | Node c l k v r => if lt x k then fixup (Node c (ins l) k v r) (fun h => Rbnode.noConfusion h) else if lt k x then fixup (Node c l k v (ins r)) (fun h => Rbnode.noConfusion h) else Node c l x vx r def insert (t : Rbnode α β) (k : α) (v : β k) : Rbnode α β := setBlack (ins lt k v t) end insert section membership variable (lt : α → α → Prop) variable [DecidableRel lt] def findCore : Rbnode α β → ∀ (k : α), Option (Sigma (fun k => β k)) | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => findCore a x | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => findCore b x) def find {β : Type v} : Rbnode α (fun _ => β) → α → Option β | leaf, x => none | Node _ a ky vy b, x => (match cmpUsing lt x ky with | Ordering.lt => find a x | Ordering.Eq => some vy | Ordering.gt => find b x) def lowerBound : Rbnode α β → α → Option (Sigma β) → Option (Sigma β) | leaf, x, lb => lb | Node _ a ky vy b, x, lb => (match cmpUsing lt x ky with | Ordering.lt => lowerBound a x lb | Ordering.Eq => some ⟨ky, vy⟩ | Ordering.gt => lowerBound b x (some ⟨ky, vy⟩)) end membership inductive WellFormed (lt : α → α → Prop) : Rbnode α β → Prop | leafWff : WellFormed leaf | insertWff {n n' : Rbnode α β} {k : α} {v : β k} [DecidableRel lt] : WellFormed n → n' = insert lt n k v → WellFormed n' end Rbnode open Rbnode /- TODO(Leo): define dRbmap -/ def Rbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Type (max u v) := {t : Rbnode α (fun _ => β) // t.WellFormed lt } @[inline] def mkRbmap (α : Type u) (β : Type v) (lt : α → α → Prop) : Rbmap α β lt := ⟨leaf, WellFormed.leafWff lt⟩ namespace Rbmap variable {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Prop} def depth (f : Nat → Nat → Nat) (t : Rbmap α β lt) : Nat := t.val.depth f @[inline] def fold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.fold f b @[inline] def revFold (f : α → β → σ → σ) : Rbmap α β lt → σ → σ | ⟨t, _⟩, b => t.revFold f b @[inline] def empty : Rbmap α β lt → Bool | ⟨leaf, _⟩ => true | _ => false @[specialize] def toList : Rbmap α β lt → List (α × β) | ⟨t, _⟩ => t.revFold (fun k v ps => (k, v)::ps) [] @[inline] protected def min : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.min with | some ⟨k, v⟩ => some (k, v) | none => none @[inline] protected def max : Rbmap α β lt → Option (α × β) | ⟨t, _⟩ => match t.max with | some ⟨k, v⟩ => some (k, v) | none => none instance [Repr α] [Repr β] : Repr (Rbmap α β lt) := ⟨fun t => "rbmapOf " ++ repr t.toList⟩ variable [DecidableRel lt] def insert : Rbmap α β lt → α → β → Rbmap α β lt | ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩ @[specialize] def ofList : List (α × β) → Rbmap α β lt | [] => mkRbmap _ _ _ | ⟨k,v⟩::xs => (ofList xs).insert k v def findCore : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.findCore lt x def find : Rbmap α β lt → α → Option β | ⟨t, _⟩, x => t.find lt x /-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`, if it exists. -/ def lowerBound : Rbmap α β lt → α → Option (Sigma (fun (k : α) => β)) | ⟨t, _⟩, x => t.lowerBound lt x none @[inline] def contains (t : Rbmap α β lt) (a : α) : Bool := (t.find a).isSome def fromList (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := l.foldl (fun r p => r.insert p.1 p.2) (mkRbmap α β lt) @[inline] def all : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.all p @[inline] def any : Rbmap α β lt → (α → β → Bool) → Bool | ⟨t, _⟩, p => t.any p end Rbmap def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Prop) [DecidableRel lt] : Rbmap α β lt := Rbmap.fromList l lt /- Test -/ @[reducible] def map : Type := Rbmap Nat Bool Less.Less def mkMapAux : Nat → map → map | 0, m => m | n+1, m => mkMapAux n (m.insert n (n % 10 = 0)) def mkMap (n : Nat) := mkMapAux n (mkRbmap Nat Bool Less.Less) def main (xs : List String) : IO UInt32 := let m := mkMap xs.head.toNat; let v := Rbmap.fold (fun (k : Nat) (v : Bool) (r : Nat) => if v then r + 1 else r) m 0; IO.println (toString v) *> pure 0
b0b41899f13fbecab0b8b0e69943d798d829a2c4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/monoidal/types.lean
6412fbbeaa913c12987711df6ee7c652dca1ed7a
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,071
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.of_chosen_finite_products import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.types /-! # The category of types is a symmetric monoidal category -/ open category_theory open category_theory.limits open tactic universes v u namespace category_theory instance types_monoidal : monoidal_category.{u} (Type u) := monoidal_of_chosen_finite_products (types.terminal_limit_cone) (types.binary_product_limit_cone) instance types_symmetric : symmetric_category.{u} (Type u) := symmetric_of_chosen_finite_products (types.terminal_limit_cone) (types.binary_product_limit_cone) @[simp] lemma tensor_apply {W X Y Z : Type u} (f : W ⟶ X) (g : Y ⟶ Z) (p : W ⊗ Y) : (f ⊗ g) p = (f p.1, g p.2) := rfl @[simp] lemma left_unitor_hom_apply {X : Type u} {x : X} {p : punit} : ((λ_ X).hom : (𝟙_ (Type u)) ⊗ X → X) (p, x) = x := rfl @[simp] lemma left_unitor_inv_apply {X : Type u} {x : X} : ((λ_ X).inv : X ⟶ (𝟙_ (Type u)) ⊗ X) x = (punit.star, x) := rfl @[simp] lemma right_unitor_hom_apply {X : Type u} {x : X} {p : punit} : ((ρ_ X).hom : X ⊗ (𝟙_ (Type u)) → X) (x, p) = x := rfl @[simp] lemma right_unitor_inv_apply {X : Type u} {x : X} : ((ρ_ X).inv : X ⟶ X ⊗ (𝟙_ (Type u))) x = (x, punit.star) := rfl @[simp] lemma associator_hom_apply {X Y Z : Type u} {x : X} {y : Y} {z : Z} : ((α_ X Y Z).hom : (X ⊗ Y) ⊗ Z → X ⊗ (Y ⊗ Z)) ((x, y), z) = (x, (y, z)) := rfl @[simp] lemma associator_inv_apply {X Y Z : Type u} {x : X} {y : Y} {z : Z} : ((α_ X Y Z).inv : X ⊗ (Y ⊗ Z) → (X ⊗ Y) ⊗ Z) (x, (y, z)) = ((x, y), z) := rfl @[simp] lemma braiding_hom_apply {X Y : Type u} {x : X} {y : Y} : ((β_ X Y).hom : X ⊗ Y → Y ⊗ X) (x, y) = (y, x) := rfl @[simp] lemma braiding_inv_apply {X Y : Type u} {x : X} {y : Y} : ((β_ X Y).inv : Y ⊗ X → X ⊗ Y) (y, x) = (x, y) := rfl open opposite open monoidal_category /-- `(𝟙_ C ⟶ -)` is a lax monoidal functor to `Type`. -/ def coyoneda_tensor_unit (C : Type u) [category.{v} C] [monoidal_category C] : lax_monoidal_functor C (Type v) := { ε := λ p, 𝟙 _, μ := λ X Y p, (λ_ (𝟙_ C)).inv ≫ (p.1 ⊗ p.2), μ_natural' := by tidy, associativity' := λ X Y Z, begin ext ⟨⟨f, g⟩, h⟩, dsimp at f g h, dsimp, simp only [iso.cancel_iso_inv_left, category.assoc], conv_lhs { rw [←category.id_comp h, tensor_comp, category.assoc, associator_naturality, ←category.assoc, unitors_inv_equal, triangle_assoc_comp_right_inv], }, conv_rhs { rw [←category.id_comp f, tensor_comp], }, end, left_unitality' := by tidy, right_unitality' := λ X, begin ext ⟨f, ⟨⟩⟩, dsimp at f, dsimp, simp only [category.assoc], rw [right_unitor_naturality, unitors_inv_equal, iso.inv_hom_id_assoc], end, ..coyoneda.obj (op (𝟙_ C)) } end category_theory
0971ea14128f09f0430dc0719c26928c01ce5a9a
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/topology/algebra/ordered.lean
d598de8e960ec4e6a5cb7b6b6dddd7230294d88d
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
43,437
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 Theory of ordered topology. -/ import order.liminf_limsup import data.set.intervals import topology.algebra.group import topology.constructions open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- (Partially) ordered topology Also called: partially ordered spaces (pospaces). Usually ordered topology is used for a topology on linear ordered spaces, where the open intervals are open sets. This is a generalization as for each linear order where open interals are open sets, the order relation is closed. -/ class ordered_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed (λp:α×α, p.1 ≤ p.2)) instance {α : Type*} : Π [topological_space α], topological_space (order_dual α) := id section ordered_topology section preorder variables [topological_space α] [preorder α] [t : ordered_topology α] include t lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ t.is_closed_le' lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id instance : ordered_topology (order_dual α) := ⟨continuous_swap _ (@ordered_topology.is_closed_le' α _ _ _)⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter (is_closed_ge' a) (is_closed_le' b) lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} (hb : b ≠ ⊥) (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) (h : {b | f b ≤ g b} ∈ b) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (nhds (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from mem_of_closed_of_tendsto hb this t.is_closed_le' h lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | c ≤ b} ∈ x) : a ≤ b := le_of_tendsto_of_tendsto nt lim tendsto_const_nhds h lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} (nt : x ≠ ⊥) (lim : tendsto f x (nhds a)) (h : f ⁻¹' {c | b ≤ c} ∈ x) : b ≤ a := le_of_tendsto_of_tendsto nt tendsto_const_nhds lim h @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := closure_eq_iff_is_closed.mpr $ is_closed_le hf hg end preorder section partial_order variables [topological_space α] [partial_order α] [t : ordered_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) instance ordered_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [t : ordered_topology α] include t lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf lemma is_open_Ioo {a b : α} : is_open (Ioo a b) := is_open_and (is_open_lt continuous_const continuous_id) (is_open_lt continuous_id continuous_const) lemma is_open_Iio {a : α} : is_open (Iio a) := is_open_lt continuous_id continuous_const end linear_order section decidable_linear_order variables [topological_space α] [decidable_linear_order α] [t : ordered_topology α] [topological_space β] {f g : β → α} include t section variables (hf : continuous f) (hg : continuous g) include hf hg lemma frontier_le_subset_eq : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := assume b ⟨hb₁, hb₂⟩, le_antisymm (by simpa [closure_le_eq hf hg] using hb₁) (not_lt.1 $ assume hb : f b < g b, have {b | f b < g b} ⊆ interior {b | f b ≤ g b}, from (subset_interior_iff_subset_of_open $ is_open_lt hf hg).mpr $ assume x, le_of_lt, have b ∈ interior {b | f b ≤ g b}, from this hb, by exact hb₂ this) lemma frontier_lt_subset_eq : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_max : continuous (λb, max (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, g b = f b, from assume b hb, (frontier_le_subset_eq hf hg hb).symm, continuous_if this hg hf lemma continuous_min : continuous (λb, min (f b) (g b)) := have ∀b∈frontier {b | f b ≤ g b}, f b = g b, from assume b hb, frontier_le_subset_eq hf hg hb, continuous_if this hf hg end lemma tendsto_max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, max (f b) (g b)) b (nhds (max a₁ a₂)) := show tendsto ((λp:α×α, max p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (max a₁ a₂)), from (hf.prod_mk hg).comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_max continuous_fst continuous_snd) _ end lemma tendsto_min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (nhds a₁)) (hg : tendsto g b (nhds a₂)) : tendsto (λb, min (f b) (g b)) b (nhds (min a₁ a₂)) := show tendsto ((λp:α×α, min p.1 p.2) ∘ (λb, (f b, g b))) b (nhds (min a₁ a₂)), from (hf.prod_mk hg).comp begin rw [←nhds_prod_eq], from continuous_iff_continuous_at.mp (continuous_min continuous_fst continuous_snd) _ end end decidable_linear_order end ordered_topology /-- Topologies generated by the open intervals. This is restricted to linear orders. Only then it is guaranteed that they are also a ordered topology. -/ class orderable_topology (α : Type*) [t : topological_space α] [partial_order α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}}) section orderable_topology instance {α : Type*} [topological_space α] [partial_order α] [orderable_topology α] : orderable_topology (order_dual α) := ⟨by convert @orderable_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : orderable_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = {b : α | a < b} ∨ s = {b : α | b < a}} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : {b | a < b} ∈ nhds b := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : {b | a ≤ b} ∈ nhds b := (nhds b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : {a | a < b} ∈ nhds a := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : {a | a ≤ b} ∈ nhds a := (nhds a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_orderable {a : α} : nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_infi $ assume b, le_infi $ assume hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_orderable {f : β → α} {a : α} {x : filter β} : tendsto f x (nhds a) ↔ (∀a'<a, {b | a' < f b} ∈ x) ∧ (∀a'>a, {b | a' > f b} ∈ x) := by simp [@nhds_eq_orderable α _ _, tendsto_inf, tendsto_infi, tendsto_principal] /-- Also known as squeeze or sandwich theorem. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (nhds a)) (hh : tendsto h b (nhds a)) (hgf : {b | g b ≤ f b} ∈ b) (hfh : {b | f b ≤ h b} ∈ b) : tendsto f b (nhds a) := tendsto_orderable.2 ⟨assume a' h', have {b : β | a' < g b} ∈ b, from (tendsto_orderable.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have {b : β | h b < a'} ∈ b, from (tendsto_orderable.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ lemma nhds_orderable_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : nhds a = (⨅l (h₂ : l < a) u (h₂ : a < u), principal {x | l < x ∧ x < u }) := let ⟨u, hu⟩ := hu, ⟨l, hl⟩ := hl in calc nhds a = (⨅b<a, principal {c | b < c}) ⊓ (⨅b>a, principal {c | c < b}) : nhds_eq_orderable ... = (⨅b<a, principal {c | b < c} ⊓ (⨅b>a, principal {c | c < b})) : binfi_inf hl ... = (⨅l<a, (⨅u>a, principal {c | c < u} ⊓ principal {c | l < c})) : begin congr, funext x, congr, funext hx, rw [inf_comm], apply binfi_inf hu end ... = _ : by simp [inter_comm]; refl lemma tendsto_orderable_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → {b | l < f b ∧ f b < u } ∈ x) : tendsto f x (nhds a) := by rw [nhds_orderable_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order theorem induced_orderable_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @orderable_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced_eq_comap, nhds_generate_from, @nhds_eq_orderable β _ _], apply le_antisymm, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } end theorem induced_orderable_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [orderable_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @orderable_topology _ (induced f ta) _ := induced_orderable_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) lemma nhds_top_orderable [topological_space α] [order_top α] [orderable_topology α] : nhds (⊤:α) = (⨅l (h₂ : l < ⊤), principal {x | l < x}) := by rw [@nhds_eq_orderable α _ _]; simp [(>)] lemma nhds_bot_orderable [topological_space α] [order_bot α] [orderable_topology α] : nhds (⊥:α) = (⨅l (h₂ : ⊥ < l), principal {x | x < l}) := by rw [@nhds_eq_orderable α _ _]; simp section linear_order variables [topological_space α] [linear_order α] [t : orderable_topology α] include t lemma mem_nhds_orderable_dest {a : α} {s : set α} (hs : s ∈ nhds a) : ((∃u, u>a) → ∃u, a < u ∧ ∀b, a ≤ b → b < u → b ∈ s) ∧ ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ≤ a → b ∈ s) := let ⟨t₁, ht₁, t₂, ht₂, hts⟩ := mem_inf_sets.mp $ by rw [@nhds_eq_orderable α _ _ _] at hs; exact hs in have ht₁ : ((∃l, l<a) → ∃l, l < a ∧ ∀b, l < b → b ∈ t₁) ∧ (∀b, a ≤ b → b ∈ t₁), from infi_sets_induct ht₁ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' < a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨max u a', max_lt hu₁ h, assume b hb, ⟨hs₁ $ lt_of_le_of_lt (le_max_right _ _) hb, hu₂ _ $ lt_of_le_of_lt (le_max_left _ _) hb⟩⟩, assume b hb, ⟨hs₁ $ lt_of_lt_of_le h hb, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), have ht₂ : ((∃u, u>a) → ∃u, a < u ∧ ∀b, b < u → b ∈ t₂) ∧ (∀b, b ≤ a → b ∈ t₂), from infi_sets_induct ht₂ (by simp {contextual := tt}) (assume a' s₁ s₂ hs₁ ⟨hs₂, hs₃⟩, begin by_cases a' > a, { simp [h] at hs₁, letI := classical.DLO α, exact ⟨assume hx, let ⟨u, hu₁, hu₂⟩ := hs₂ hx in ⟨min u a', lt_min hu₁ h, assume b hb, ⟨hs₁ $ lt_of_lt_of_le hb (min_le_right _ _), hu₂ _ $ lt_of_lt_of_le hb (min_le_left _ _)⟩⟩, assume b hb, ⟨hs₁ $ lt_of_le_of_lt hb h, hs₃ _ hb⟩⟩ }, { simp [h] at hs₁, simp [hs₁], exact ⟨by simpa using hs₂, hs₃⟩ } end) (assume s₁ s₂ h ih, and.intro (assume hx, let ⟨u, hu₁, hu₂⟩ := ih.left hx in ⟨u, hu₁, assume b hb, h $ hu₂ _ hb⟩) (assume b hb, h $ ih.right _ hb)), and.intro (assume hx, let ⟨u, hu, h⟩ := ht₂.left hx in ⟨u, hu, assume b hb hbu, hts ⟨ht₁.right b hb, h _ hbu⟩⟩) (assume hx, let ⟨l, hl, h⟩ := ht₁.left hx in ⟨l, hl, assume b hbl hb, hts ⟨h _ hbl, ht₂.right b hb⟩⟩) lemma mem_nhds_unbounded {a : α} {s : set α} (hu : ∃u, a < u) (hl : ∃l, l < a) : s ∈ nhds a ↔ (∃l u, l < a ∧ a < u ∧ ∀b, l < b → b < u → b ∈ s) := let ⟨l, hl'⟩ := hl, ⟨u, hu'⟩ := hu in have nhds a = (⨅p : {l // l < a} × {u // a < u}, principal {x | p.1.val < x ∧ x < p.2.val }), by simp [nhds_orderable_unbounded hu hl, infi_subtype, infi_prod], iff.intro (assume hs, by rw [this] at hs; from infi_sets_induct hs ⟨l, u, hl', hu', by simp⟩ begin intro p, rcases p with ⟨⟨l, hl⟩, ⟨u, hu⟩⟩, simp [set.subset_def], intros s₁ s₂ hs₁ l' hl' u' hu' hs₂, letI := classical.DLO α, refine ⟨max l l', _, min u u', _⟩; simp [*, lt_min_iff, max_lt_iff] {contextual := tt} end (assume s₁ s₂ h ⟨l, u, h₁, h₂, h₃⟩, ⟨l, u, h₁, h₂, assume b hu hl, h $ h₃ _ hu hl⟩)) (assume ⟨l, u, hl, hu, h⟩, by rw [this]; exact mem_infi_sets ⟨⟨l, hl⟩, ⟨u, hu⟩⟩ (assume b ⟨h₁, h₂⟩, h b h₁ h₂)) lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete h with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end instance orderable_topology.to_ordered_topology : ordered_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } instance orderable_topology.t2_space : t2_space α := by apply_instance instance orderable_topology.regular_space : regular_space α := { regular := assume s a hs ha, have -s ∈ nhds a, from mem_nhds_sets hs ha, let ⟨h₁, h₂⟩ := mem_nhds_orderable_dest this in have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := h₂ h in match dense_or_discrete hl with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h c (lt_of_lt_of_le hb₁ hbc) (le_of_lt hca) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ nhds a ⊓ principal t = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := h₁ h in match dense_or_discrete hu with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h c (le_of_lt hca) (lt_of_le_of_lt hbc hb₂) hcs, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot $ (nhds a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, by rw [principal_empty, inf_bot_eq]⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [←sup_principal, inf_sup_left, ht₁a, ht₂a, bot_sup_eq]⟩, ..orderable_topology.t2_space } end linear_order lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section topological_add_group variables [topological_space α] [ordered_comm_group α] [orderable_topology α] [topological_add_group α] lemma neg_preimage_closure {s : set α} : (λr:α, -r) ⁻¹' closure s = closure ((λr:α, -r) '' s) := have (λr:α, -r) ∘ (λr:α, -r) = id, from funext neg_neg, by rw [preimage_neg]; exact (subset.antisymm (image_closure_subset_closure_image continuous_neg') $ calc closure ((λ (r : α), -r) '' s) = (λr, -r) '' ((λr, -r) '' closure ((λ (r : α), -r) '' s)) : by rw [←image_comp, this, image_id] ... ⊆ (λr, -r) '' closure ((λr, -r) '' ((λ (r : α), -r) '' s)) : mono_image $ image_closure_subset_closure_image continuous_neg' ... = _ : by rw [←image_comp, this, image_id]) end topological_add_group section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [orderable_topology α] [orderable_topology β] lemma nhds_principal_ne_bot_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : nhds a ⊓ principal s ≠ ⊥ := let ⟨a', ha'⟩ := exists_mem_of_ne_empty hs in forall_sets_neq_empty_iff_neq_bot.mp $ assume t ht, let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := mem_inf_sets.mp ht in let ⟨hu, hl⟩ := mem_nhds_orderable_dest ht₁ in by_cases (assume h : a = a', have a ∈ t₁, from mem_of_nhds ht₁, have a ∈ t₂, from ht₂ $ by rwa [h], ne_empty_iff_exists_mem.mpr ⟨a, ht ⟨‹a ∈ t₁›, ‹a ∈ t₂›⟩⟩) (assume : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ‹a' ∈ s›) this.symm, let ⟨l, hl, hlt₁⟩ := hl ⟨a', this⟩ in have ∃a'∈s, l < a', from classical.by_contradiction $ assume : ¬ ∃a'∈s, l < a', have ∀a'∈s, a' ≤ l, from assume a ha, not_lt.1 $ assume ha', this ⟨a, ha, ha'⟩, have ¬ l < a, from not_lt.2 $ ha.right _ this, this ‹l < a›, let ⟨a', ha', ha'l⟩ := this in have a' ∈ t₁, from hlt₁ _ ‹l < a'› $ ha.left _ ha', ne_empty_iff_exists_mem.mpr ⟨a', ht ⟨‹a' ∈ t₁›, ht₂ ‹a' ∈ s›⟩⟩) lemma nhds_principal_ne_bot_of_is_glb : ∀ {a : α} {s : set α}, is_glb s a → s ≠ ∅ → nhds a ⊓ principal s ≠ ⊥ := @nhds_principal_ne_bot_of_is_lub (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) (hfa : f ⊓ nhds a ≠ ⊥) : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ nhds a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := inhabited_of_mem_sets hfa this in have b < b, from lt_of_lt_of_le hxb $ hb _ hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → f ⊓ nhds a ≠ ⊥ → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub_of_is_lub_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s ≠ ∅) (hb : tendsto f (nhds a ⊓ principal s) (nhds b)) : is_lub (f '' s) b := have hnbot : (nhds a ⊓ principal s) ≠ ⊥, from nhds_principal_ne_bot_of_is_lub ha hs, have ∀a'∈s, ¬ b < f a', from assume a' ha' h, have {x | x < f a'} ∈ nhds b, from mem_nhds_sets (is_open_gt' _) h, let ⟨t₁, ht₁, t₂, ht₂, hs⟩ := mem_inf_sets.mp (hb this) in by_cases (assume h : a = a', have a ∈ t₁ ∩ t₂, from ⟨mem_of_nhds ht₁, ht₂ $ by rwa [h]⟩, have f a < f a', from hs this, lt_irrefl (f a') $ by rwa [h] at this) (assume h : a ≠ a', have a' < a, from lt_of_le_of_ne (ha.left _ ha') h.symm, have {x | a' < x} ∈ nhds a, from mem_nhds_sets (is_open_lt' _) this, have {x | a' < x} ∩ t₁ ∈ nhds a, from inter_mem_sets this ht₁, have ({x | a' < x} ∩ t₁) ∩ s ∈ nhds a ⊓ principal s, from inter_mem_inf_sets this (subset.refl s), let ⟨x, ⟨hx₁, hx₂⟩, hx₃⟩ := inhabited_of_mem_sets hnbot this in have hxa' : f x < f a', from hs ⟨hx₂, ht₂ hx₃⟩, have ha'x : f a' ≤ f x, from hf _ ha' _ hx₃ $ le_of_lt hx₁, lt_irrefl _ (lt_of_le_of_lt ha'x hxa')), and.intro (assume b' ⟨a', ha', h_eq⟩, h_eq ▸ not_lt.1 $ this _ ha') (assume b' hb', le_of_tendsto hnbot hb $ mem_inf_sets_of_right $ assume x hx, hb' _ $ mem_image_of_mem _ hx) lemma is_glb_of_is_glb_of_tendsto {f : α → β} {s : set α} {a : α} {b : β} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto (order_dual α) (order_dual β) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_glb_of_is_lub_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_glb (f '' s) b := @is_lub_of_is_lub_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma is_lub_of_is_glb_of_tendsto : ∀ {f : α → β} {s : set α} {a : α} {b : β}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s ≠ ∅ → tendsto f (nhds a ⊓ principal s) (nhds b) → is_lub (f '' s) b := @is_glb_of_is_glb_of_tendsto α (order_dual β) _ _ _ _ _ _ lemma mem_closure_of_is_lub {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_lub ha hs lemma mem_of_is_lub_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_lub ha hs lemma mem_closure_of_is_glb {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) : a ∈ closure s := by rw closure_eq_nhds; exact nhds_principal_ne_bot_of_is_glb ha hs lemma mem_of_is_glb_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s ≠ ∅) (sc : is_closed s): a ∈ s := by rw ←closure_eq_of_is_closed sc; exact mem_closure_of_is_glb ha hs /-- A compact set is bounded below -/ lemma bdd_below_of_compact {α : Type u} [topological_space α] [linear_order α] [ordered_topology α] [nonempty α] {s : set α} (hs : compact s) : bdd_below s := begin by_contra H, letI := classical.DLO α, rcases @compact_elim_finite_subcover_image α _ _ _ s (λ x, {b | x < b}) hs (λ x _, is_open_lt continuous_const continuous_id) _ with ⟨t, st, ft, ht⟩, { refine H ((bdd_below_finite ft).imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC _ hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma bdd_above_of_compact {α : Type u} [topological_space α] [linear_order α] [orderable_topology α] : Π [nonempty α] {s : set α}, compact s → bdd_above s := @bdd_below_of_compact (order_dual α) _ _ _ end order_topology section complete_linear_order variables [complete_linear_order α] [topological_space α] [orderable_topology α] [complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Sup s ∈ closure s := mem_closure_of_is_lub is_lub_Sup hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) : Inf s ∈ closure s := mem_closure_of_is_glb is_glb_Inf hs lemma Sup_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Sup s ∈ s := mem_of_is_lub_of_is_closed is_lub_Sup hs hc lemma Inf_mem_of_is_closed {α : Type u} [topological_space α] [complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) : Inf s ∈ s := mem_of_is_glb_of_is_closed is_glb_Inf hs hc /-- A continuous monotone function sends supremum to supremum for nonempty sets. -/ lemma Sup_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub_of_is_lub_of_tendsto (is_lub_iff_Sup_eq.1 (is_lub_of_is_lub_of_tendsto (λ x hx y hy xy, Cf xy) is_lub_Sup hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending bot to bot sends supremum to supremum. -/ lemma Sup_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (fbot : f ⊥ = ⊥) {s : set α} : f (Sup s) = Sup (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Sup_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed supremum to indexed supremum. -/ lemma supr_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (supr g) = supr (f ∘ g) := by rw [supr, Sup_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum for nonempty sets. -/ lemma Inf_of_continuous' {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (hs : s ≠ ∅) : f (Inf s) = Inf (f '' s) := (is_glb_iff_Inf_eq.1 (is_glb_of_is_glb_of_tendsto (λ x hx y hy xy, Cf xy) is_glb_Inf hs $ tendsto_le_left inf_le_left (continuous.tendsto Mf _))).symm /-- A continuous monotone function sending top to top sends infimum to infimum. -/ lemma Inf_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) (ftop : f ⊤ = ⊤) {s : set α} : f (Inf s) = Inf (f '' s) := begin by_cases (s = ∅), { simpa [h] }, { exact Inf_of_continuous' Mf Cf h } end /-- A continuous monotone function sends indexed infimum to indexed infimum. -/ lemma infi_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) : f (infi g) = infi (f ∘ g) := by rw [infi, Inf_of_continuous' Mf Cf (λ h, range_eq_empty.1 h ‹_›), ← range_comp]; refl end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] [conditionally_complete_linear_order β] [topological_space β] [orderable_topology β] [nonempty γ] lemma cSup_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_above s) : Sup s ∈ closure s := mem_closure_of_is_lub (is_lub_cSup hs B) hs lemma cInf_mem_closure {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (B : bdd_below s) : Inf s ∈ closure s := mem_closure_of_is_glb (is_glb_cInf hs B) hs lemma cSup_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_above s) : Sup s ∈ s := mem_of_is_lub_of_is_closed (is_lub_cSup hs B) hs hc lemma cInf_mem_of_is_closed {α : Type u} [topological_space α] [conditionally_complete_linear_order α] [orderable_topology α] {s : set α} (hs : s ≠ ∅) (hc : is_closed s) (B : bdd_below s) : Inf s ∈ s := mem_of_is_glb_of_is_closed (is_glb_cInf hs B) hs hc /-- A continuous monotone function sends supremum to supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma cSup_of_cSup_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine (is_lub_iff_eq_of_is_lub _).1 (is_lub_cSup (mt image_eq_empty.1 ne) (bdd_above_of_bdd_above_of_monotone Cf H)), refine is_lub_of_is_lub_of_tendsto (λx hx y hy xy, Cf xy) (is_lub_cSup ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed supremum to indexed supremum in conditionally complete lattices, under a boundedness assumption. -/ lemma csupr_of_csupr_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_above (range g)) : f (supr g) = supr (f ∘ g) := by rw [supr, cSup_of_cSup_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- A continuous monotone function sends infimum to infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cInf_of_cInf_of_monotone_of_continuous {f : α → β} (Mf : continuous f) (Cf : monotone f) {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := begin refine (is_glb_iff_eq_of_is_glb _).1 (is_glb_cInf (mt image_eq_empty.1 ne) (bdd_below_of_bdd_below_of_monotone Cf H)), refine is_glb_of_is_glb_of_tendsto (λx hx y hy xy, Cf xy) (is_glb_cInf ne H) ne _, exact tendsto_le_left inf_le_left (continuous.tendsto Mf _) end /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete lattices, under a boundedness assumption. -/ lemma cinfi_of_cinfi_of_monotone_of_continuous {f : α → β} {g : γ → α} (Mf : continuous f) (Cf : monotone f) (H : bdd_below (range g)): f (infi g) = infi (f ∘ g) := by rw [infi, cInf_of_cInf_of_monotone_of_continuous Mf Cf (λ h, range_eq_empty.1 h ‹_›) H, ← range_comp]; refl /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma exists_forall_le_of_compact_of_continuous {α : Type u} [topological_space α] (f : α → β) (hf : continuous f) (s : set α) (hs : compact s) (ne_s : s ≠ ∅) : ∃x∈s, ∀y∈s, f x ≤ f y := begin have C : compact (f '' s) := compact_image hs hf, haveI := has_Inf_to_nonempty β, have B : bdd_below (f '' s) := bdd_below_of_compact C, have : Inf (f '' s) ∈ f '' s := cInf_mem_of_is_closed (mt image_eq_empty.1 ne_s) (closed_of_compact _ C) B, rcases (mem_image _ _ _).1 this with ⟨x, xs, hx⟩, exact ⟨x, xs, λ y hy, hx.symm ▸ cInf_le B ⟨_, hy, rfl⟩⟩ end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma exists_forall_ge_of_compact_of_continuous {α : Type u} [topological_space α] : ∀ f : α → β, continuous f → ∀ s : set α, compact s → s ≠ ∅ → ∃x∈s, ∀y∈s, f y ≤ f x := @exists_forall_le_of_compact_of_continuous (order_dual β) _ _ _ _ _ end conditionally_complete_linear_order section liminf_limsup section ordered_topology variables [semilattice_sup α] [topological_space α] [orderable_topology α] lemma is_bounded_le_nhds (a : α) : (nhds a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, show {x : α | x ≤ a} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma is_bounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≤) u := is_bounded_of_le h (is_bounded_le_nhds a) lemma is_cobounded_ge_nhds (a : α) : (nhds a).is_cobounded (≥) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_le_nhds a) lemma is_cobounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≥) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_le_of_tendsto h) end ordered_topology section ordered_topology variables [semilattice_inf α] [topological_space α] [orderable_topology α] lemma is_bounded_ge_nhds (a : α) : (nhds a).is_bounded (≥) := match forall_le_or_exists_lt_inf a with | or.inl h := ⟨a, show {x : α | a ≤ x} ∈ nhds a, from univ_mem_sets' h⟩ | or.inr ⟨b, hb⟩ := ⟨b, le_mem_nhds hb⟩ end lemma is_bounded_under_ge_of_tendsto {f : filter β} {u : β → α} {a : α} (h : tendsto u f (nhds a)) : f.is_bounded_under (≥) u := is_bounded_of_le h (is_bounded_ge_nhds a) lemma is_cobounded_le_nhds (a : α) : (nhds a).is_cobounded (≤) := is_cobounded_of_is_bounded nhds_neq_bot (is_bounded_ge_nhds a) lemma is_cobounded_under_le_of_tendsto {f : filter β} {u : β → α} {a : α} (hf : f ≠ ⊥) (h : tendsto u f (nhds a)) : f.is_cobounded_under (≤) u := is_cobounded_of_is_bounded (map_ne_bot hf) (is_bounded_under_ge_of_tendsto h) end ordered_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [orderable_topology α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : {a | a < b} ∈ f := let ⟨c, (h : {a : α | a ≤ c} ∈ f), hcb⟩ := exists_lt_of_cInf_lt (ne_empty_iff_exists_mem.2 h) l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → f.Liminf > b → {a | a > b} ∈ f := @lt_mem_sets_of_Limsup_lt (order_dual α) _ _ _ /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ nhds a := tendsto_orderable.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (nhds a) = a := cInf_intro (ne_empty_iff_exists_mem.2 $ is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ nhds a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ nhds a), c < b, from match dense_or_discrete hba with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (nhds a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (nhds a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} (hf : f ≠ ⊥) (h : f ≤ nhds a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from is_bounded_of_le h (is_bounded_ge_nhds a), have hb_le : is_bounded (≤) f, from is_bounded_of_le h (is_bounded_le_nhds a), le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hf hb_le hb_ge ... ≤ (nhds a).Limsup : Limsup_le_Limsup_of_le h (is_cobounded_of_is_bounded hf hb_ge) (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (nhds a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) (is_cobounded_of_is_bounded hf hb_le)) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α}, f ≠ ⊥ → f ≤ nhds a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ end conditionally_complete_linear_order end liminf_limsup end orderable_topology lemma orderable_topology_of_nhds_abs {α : Type*} [decidable_linear_ordered_comm_group α] [topological_space α] (h_nhds : ∀a:α, nhds a = (⨅r>0, principal {b | abs (a - b) < r})) : orderable_topology α := orderable_topology.mk $ eq_of_nhds_eq_nhds $ assume a:α, le_antisymm_iff.mpr begin simp [infi_and, topological_space.nhds_generate_from, h_nhds, le_infi_iff, -le_principal_iff, and_comm], refine ⟨λ s ha b hs, _, λ r hr, _⟩, { rcases hs with rfl | rfl, { refine infi_le_of_le (a - b) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < a - b), _), have : a - c < a - b := lt_of_le_of_lt (le_abs_self _) hc, exact lt_of_neg_lt_neg (lt_of_add_lt_add_left this) }, { refine infi_le_of_le (b - a) (infi_le_of_le (lt_sub_left_of_add_lt $ by simpa using ha) $ principal_mono.mpr $ assume c (hc : abs (a - c) < b - a), _), have : abs (c - a) < b - a, {rw abs_sub; simpa using hc}, have : c - a < b - a := lt_of_le_of_lt (le_abs_self _) this, exact lt_of_add_lt_add_right this } }, { have h : {b | abs (a + -b) < r} = {b | a - r < b} ∩ {b | b < a + r}, from set.ext (assume b, by simp [abs_lt, -sub_eq_add_neg, (sub_eq_add_neg _ _).symm, sub_lt, lt_sub_iff_add_lt, and_comm, sub_lt_iff_lt_add']), rw [h, ← inf_principal], apply le_inf _ _, { exact infi_le_of_le {b : α | a - r < b} (infi_le_of_le (sub_lt_self a hr) $ infi_le_of_le (a - r) $ infi_le _ (or.inl rfl)) }, { exact infi_le_of_le {b : α | b < a + r} (infi_le_of_le (lt_add_of_pos_right _ hr) $ infi_le_of_le (a + r) $ infi_le _ (or.inr rfl)) } } end lemma tendsto_at_top_supr_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : monotone f) : tendsto f at_top (nhds (⨆i, f i)) := tendsto_orderable.2 $ and.intro (assume a ha, let ⟨n, hn⟩ := lt_supr_iff.1 ha in mem_at_top_sets.2 ⟨n, assume i hi, lt_of_lt_of_le hn (hf hi)⟩) (assume a ha, univ_mem_sets' (assume n, lt_of_le_of_lt (le_supr _ n) ha)) lemma tendsto_at_top_infi_nat [topological_space α] [complete_linear_order α] [orderable_topology α] (f : ℕ → α) (hf : ∀{n m}, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds (⨅i, f i)) := @tendsto_at_top_supr_nat (order_dual α) _ _ _ _ @hf lemma supr_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : monotone f) : tendsto f at_top (nhds a) → supr f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_supr_nat f hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [orderable_topology α] {f : ℕ → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (nhds a) → infi f = a := tendsto_nhds_unique at_top_ne_bot (tendsto_at_top_infi_nat f hf)
66256f57c7441ec2c27aadf96e16a420f1ee9056
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/PrettyPrinter/Formatter.lean
80da39d6ff72461307ad14c73a70907264a30d79
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
21,865
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.CoreM import Lean.Parser.Extension import Lean.Parser.StrInterpolation import Lean.KeyedDeclsAttribute import Lean.ParserCompiler.Attribute import Lean.PrettyPrinter.Basic /-! The formatter turns a `Syntax` tree into a `Format` object, inserting both mandatory whitespace (to separate adjacent tokens) as well as "pretty" optional whitespace. The basic approach works much like the parenthesizer: A right-to-left traversal over the syntax tree, driven by parser-specific handlers registered via attributes. The traversal is right-to-left so that when emitting a token, we already know the text following it and can decide whether or not whitespace between the two is necessary. -/ namespace Lean namespace PrettyPrinter namespace Formatter structure Context where options : Options table : Parser.TokenTable structure State where stxTrav : Syntax.Traverser -- Textual content of `stack` up to the first whitespace (not enclosed in an escaped ident). We assume that the textual -- content of `stack` is modified only by `pushText` and `pushLine`, so `leadWord` is adjusted there accordingly. leadWord : String := "" -- Whether the generated format begins with the result of an ungrouped category formatter. isUngrouped : Bool := false -- Whether the resulting format must be grouped when used in a category formatter. -- If the flag is set to false, then categoryParser omits the fill+nest operation. mustBeGrouped : Bool := true -- Stack of generated Format objects, analogous to the Syntax stack in the parser. -- Note, however, that the stack is reversed because of the right-to-left traversal. stack : Array Format := #[] end Formatter abbrev FormatterM := ReaderT Formatter.Context $ StateRefT Formatter.State CoreM @[inline] def FormatterM.orElse {α} (p₁ : FormatterM α) (p₂ : Unit → FormatterM α) : FormatterM α := do let s ← get catchInternalId backtrackExceptionId p₁ (fun _ => do set s; p₂ ()) instance {α} : OrElse (FormatterM α) := ⟨FormatterM.orElse⟩ abbrev Formatter := FormatterM Unit unsafe def mkFormatterAttribute : IO (KeyedDeclsAttribute Formatter) := KeyedDeclsAttribute.init { builtinName := `builtin_formatter, name := `formatter, descr := "Register a formatter for a parser. [formatter k] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `SyntaxNodeKind` `k`.", valueTypeName := `Lean.PrettyPrinter.Formatter, evalKey := fun builtin stx => do let env ← getEnv let stx ← Attribute.Builtin.getIdent stx let id := stx.getId -- `isValidSyntaxNodeKind` is updated only in the next stage for new `[builtin*Parser]`s, but we try to -- synthesize a formatter for it immediately, so we just check for a declaration in this case unless (builtin && (env.find? id).isSome) || Parser.isValidSyntaxNodeKind env id do throwError "invalid [formatter] argument, unknown syntax kind '{id}'" if (← getEnv).contains id && (← Elab.getInfoState).enabled then Elab.addConstInfo stx id none pure id } `Lean.PrettyPrinter.formatterAttribute @[builtin_init mkFormatterAttribute] opaque formatterAttribute : KeyedDeclsAttribute Formatter unsafe def mkCombinatorFormatterAttribute : IO ParserCompiler.CombinatorAttribute := ParserCompiler.registerCombinatorAttribute `combinator_formatter "Register a formatter for a parser combinator. [combinator_formatter c] registers a declaration of type `Lean.PrettyPrinter.Formatter` for the `Parser` declaration `c`. Note that, unlike with [formatter], this is not a node kind since combinators usually do not introduce their own node kinds. The tagged declaration may optionally accept parameters corresponding to (a prefix of) those of `c`, where `Parser` is replaced with `Formatter` in the parameter types." @[builtin_init mkCombinatorFormatterAttribute] opaque combinatorFormatterAttribute : ParserCompiler.CombinatorAttribute namespace Formatter open Lean.Core open Lean.Parser def throwBacktrack {α} : FormatterM α := throw $ Exception.internal backtrackExceptionId instance : Syntax.MonadTraverser FormatterM := ⟨{ get := State.stxTrav <$> get, set := fun t => modify (fun st => { st with stxTrav := t }), modifyGet := fun f => modifyGet (fun st => let (a, t) := f st.stxTrav; (a, { st with stxTrav := t })) }⟩ open Syntax.MonadTraverser def getStack : FormatterM (Array Format) := do let st ← get pure st.stack def getStackSize : FormatterM Nat := do let stack ← getStack; pure stack.size def setStack (stack : Array Format) : FormatterM Unit := modify fun st => { st with stack := stack } private def push (f : Format) : FormatterM Unit := modify fun st => { st with stack := st.stack.push f, isUngrouped := false } def pushWhitespace (f : Format) : FormatterM Unit := do push f modify fun st => { st with leadWord := "", isUngrouped := false } def pushLine : FormatterM Unit := pushWhitespace Format.line def pushAlign (force : Bool) : FormatterM Unit := pushWhitespace (.align force) /-- Execute `x` at the right-most child of the current node, if any, then advance to the left. -/ def visitArgs (x : FormatterM Unit) : FormatterM Unit := do let stx ← getCur if stx.getArgs.size > 0 then goDown (stx.getArgs.size - 1) *> x <* goUp goLeft /-- Execute `x`, pass array of generated Format objects to `fn`, and push result. -/ def fold (fn : Array Format → Format) (x : FormatterM Unit) : FormatterM Unit := do let sp ← getStackSize x let stack ← getStack let f := fn $ stack.extract sp stack.size setStack $ (stack.shrink sp).push f /-- Execute `x` and concatenate generated Format objects. -/ def concat (x : FormatterM Unit) : FormatterM Unit := do fold (Array.foldl (fun acc f => if acc.isNil then f else f ++ acc) Format.nil) x def indent (x : Formatter) (indent : Option Int := none) : Formatter := do concat x let ctx ← read let indent := indent.getD $ Std.Format.getIndent ctx.options modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) (Format.nest indent) } def fill (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) Format.fill isUngrouped := false } def group (x : Formatter) : Formatter := do concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) Format.group isUngrouped := false } /-- If `pos?` has a position, run `x` and tag its results with that position, if they are not already tagged. Otherwise just run `x`. -/ def withMaybeTag (pos? : Option String.Pos) (x : FormatterM Unit) : Formatter := do if let some p := pos? then concat x modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) fun fmt => if fmt matches Format.tag .. then fmt else Format.tag p.byteIdx fmt } else x @[combinator_formatter orelse] partial def orelse.formatter (p1 p2 : Formatter) : Formatter := do let stx ← getCur -- `orelse` may produce `choice` nodes for antiquotations if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available orelse.formatter p1 p2 else -- HACK: We have no (immediate) information on which side of the orelse could have produced the current node, so try -- them in turn. Uses the syntax traverser non-linearly! p1 <|> p2 -- `mkAntiquot` is quite complex, so we'd rather have its formatter synthesized below the actual parser definition. -- Note that there is a mutual recursion -- `categoryParser -> mkAntiquot -> termParser -> categoryParser`, so we need to introduce an indirection somewhere -- anyway. @[extern "lean_mk_antiquot_formatter"] opaque mkAntiquot.formatter' (name : String) (kind : SyntaxNodeKind) (anonymous := true) (isPseudoKind := false) : Formatter -- break up big mutual recursion @[extern "lean_pretty_printer_formatter_interpret_parser_descr"] opaque interpretParserDescr' : ParserDescr → CoreM Formatter private def SourceInfo.getExprPos? : SourceInfo → Option String.Pos | SourceInfo.synthetic (pos := pos) .. => pos | _ => none private def getExprPos? : Syntax → Option String.Pos | Syntax.node info _ _ => SourceInfo.getExprPos? info | Syntax.atom info _ => SourceInfo.getExprPos? info | Syntax.ident info _ _ _ => SourceInfo.getExprPos? info | Syntax.missing => none unsafe def formatterForKindUnsafe (k : SyntaxNodeKind) : Formatter := do if k == `missing then push "<missing>" goLeft else let stx ← getCur let f ← runForNodeKind formatterAttribute k interpretParserDescr' withMaybeTag (getExprPos? stx) f @[implemented_by formatterForKindUnsafe] opaque formatterForKind (k : SyntaxNodeKind) : Formatter @[combinator_formatter withAntiquot] def withAntiquot.formatter (antiP p : Formatter) : Formatter := -- TODO: could be optimized using `isAntiquot` (which would have to be moved), but I'd rather -- fix the backtracking hack outright. orelse.formatter antiP p @[combinator_formatter withAntiquotSuffixSplice] def withAntiquotSuffixSplice.formatter (_ : SyntaxNodeKind) (p suffix : Formatter) : Formatter := do if (← getCur).isAntiquotSuffixSplice then visitArgs <| suffix *> p else p @[combinator_formatter tokenWithAntiquot] def tokenWithAntiquot.formatter (p : Formatter) : Formatter := do if (← getCur).isTokenAntiquot then visitArgs p else p def categoryFormatterCore (cat : Name) : Formatter := do modify fun st => { st with mustBeGrouped := true, isUngrouped := false } let stx ← getCur trace[PrettyPrinter.format] "formatting {indentD (format stx)}" if stx.getKind == `choice then visitArgs do -- format only last choice -- TODO: We could use elaborator data here to format the chosen child when available formatterForKind (← getCur).getKind else if cat == `rawStx then withAntiquot.formatter (mkAntiquot.formatter' cat.toString cat (isPseudoKind := true)) (push stx.formatStx *> goLeft) else withAntiquot.formatter (mkAntiquot.formatter' cat.toString cat (isPseudoKind := true)) (formatterForKind stx.getKind) modify fun st => { st with mustBeGrouped := true, isUngrouped := !st.mustBeGrouped } @[combinator_formatter categoryParser] def categoryParser.formatter (cat : Name) : Formatter := do concat <| categoryFormatterCore cat unless (← get).isUngrouped do let indent := Std.Format.getIndent (← read).options modify fun st => { st with stack := st.stack.modify (st.stack.size - 1) fun fmt => fmt.nest indent |>.fill } def categoryFormatter (cat : Name) : Formatter := fill <| indent <| categoryFormatterCore cat @[combinator_formatter parserOfStack] def parserOfStack.formatter (offset : Nat) (_prec : Nat := 0) : Formatter := do let st ← get let stx := st.stxTrav.parents.back.getArg (st.stxTrav.idxs.back - offset) formatterForKind stx.getKind @[combinator_formatter error] def error.formatter (_msg : String) : Formatter := pure () @[combinator_formatter errorAtSavedPos] def errorAtSavedPos.formatter (_msg : String) (_delta : Bool) : Formatter := pure () @[combinator_formatter lookahead] def lookahead.formatter (_ : Formatter) : Formatter := pure () @[combinator_formatter notFollowedBy] def notFollowedBy.formatter (_ : Formatter) : Formatter := pure () @[combinator_formatter andthen] def andthen.formatter (p1 p2 : Formatter) : Formatter := p2 *> p1 def checkKind (k : SyntaxNodeKind) : FormatterM Unit := do let stx ← getCur if k != stx.getKind then trace[PrettyPrinter.format.backtrack] "unexpected node kind '{stx.getKind}', expected '{k}'" throwBacktrack @[combinator_formatter node] def node.formatter (k : SyntaxNodeKind) (p : Formatter) : Formatter := do checkKind k; visitArgs p @[combinator_formatter withFn] def withFn.formatter (_ : ParserFn → ParserFn) (p : Formatter) : Formatter := p @[combinator_formatter trailingNode] def trailingNode.formatter (k : SyntaxNodeKind) (_ _ : Nat) (p : Formatter) : Formatter := do checkKind k visitArgs do p; -- leading term, not actually produced by `p` categoryParser.formatter `foo def parseToken (s : String) : FormatterM ParserState := -- include comment tokens, e.g. when formatting `- -0` return (Parser.andthenFn Parser.whitespace (Parser.tokenFn [])).run { input := s, fileName := "", fileMap := FileMap.ofString "" } { env := ← getEnv, options := ← getOptions } ((← read).table) (Parser.mkParserState s) def pushToken (info : SourceInfo) (tk : String) : FormatterM Unit := do match info with | SourceInfo.original _ _ ss _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then push s!"\n{ss'}" else push s!" {ss'}" modify fun st => { st with leadWord := "" } | _ => pure () let st ← get -- If there is no space between `tk` and the next word, see if we would parse more than `tk` as a single token if st.leadWord != "" && tk.trimRight == tk then let tk' := tk.trimLeft let t ← parseToken $ tk' ++ st.leadWord if t.pos <= tk'.endPos then -- stopped within `tk` => use it as is, extend `leadWord` if not prefixed by whitespace push tk modify fun st => { st with leadWord := if tk.trimLeft == tk then tk ++ st.leadWord else "" } else -- stopped after `tk` => add space push $ tk ++ " " modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } else -- already separated => use `tk` as is if st.leadWord == "" then push tk.trimRight else if tk.endsWith " " then pushLine push tk.trimRight else push tk -- preserve special whitespace for tokens like ":=\n" modify fun st => { st with leadWord := if tk.trimLeft == tk then tk else "" } match info with | SourceInfo.original ss _ _ _ => -- preserve non-whitespace content (i.e. comments) let ss' := ss.trim if !ss'.isEmpty then let ws := { ss with startPos := ss'.stopPos } if ws.contains '\n' then do -- Indentation is automatically increased when entering a category, but comments should be aligned -- with the actual token, so dedent indent (push s!"{ss'}\n") (some ((0:Int) - Std.Format.getIndent (← getOptions))) else pushLine push ss'.toString modify fun st => { st with leadWord := "" } | _ => pure () @[combinator_formatter symbolNoAntiquot] def symbolNoAntiquot.formatter (sym : String) : Formatter := do let stx ← getCur if stx.isToken sym then do let (Syntax.atom info _) ← pure stx | unreachable! withMaybeTag (getExprPos? stx) (pushToken info sym) goLeft else do trace[PrettyPrinter.format.backtrack] "unexpected syntax '{format stx}', expected symbol '{sym}'" throwBacktrack @[combinator_formatter nonReservedSymbolNoAntiquot] def nonReservedSymbolNoAntiquot.formatter := symbolNoAntiquot.formatter @[combinator_formatter rawCh] def rawCh.formatter (ch : Char) := symbolNoAntiquot.formatter ch.toString @[combinator_formatter unicodeSymbolNoAntiquot] def unicodeSymbolNoAntiquot.formatter (sym asciiSym : String) : Formatter := do let Syntax.atom info val ← getCur | throwError m!"not an atom: {← getCur}" if val == sym.trim then pushToken info sym else pushToken info asciiSym; goLeft @[combinator_formatter identNoAntiquot] def identNoAntiquot.formatter : Formatter := do checkKind identKind let stx@(Syntax.ident info _ id _) ← getCur | throwError m!"not an ident: {← getCur}" let id := id.simpMacroScopes withMaybeTag (getExprPos? stx) (pushToken info id.toString) goLeft @[combinator_formatter rawIdentNoAntiquot] def rawIdentNoAntiquot.formatter : Formatter := do checkKind identKind let Syntax.ident info _ id _ ← getCur | throwError m!"not an ident: {← getCur}" pushToken info id.toString goLeft @[combinator_formatter identEq] def identEq.formatter (_id : Name) := rawIdentNoAntiquot.formatter def visitAtom (k : SyntaxNodeKind) : Formatter := do let stx ← getCur if k != Name.anonymous then checkKind k let Syntax.atom info val ← pure $ stx.ifNode (fun n => n.getArg 0) (fun _ => stx) | throwError m!"not an atom: {stx}" pushToken info val goLeft @[combinator_formatter charLitNoAntiquot] def charLitNoAntiquot.formatter := visitAtom charLitKind @[combinator_formatter strLitNoAntiquot] def strLitNoAntiquot.formatter := visitAtom strLitKind @[combinator_formatter nameLitNoAntiquot] def nameLitNoAntiquot.formatter := visitAtom nameLitKind @[combinator_formatter numLitNoAntiquot] def numLitNoAntiquot.formatter := visitAtom numLitKind @[combinator_formatter scientificLitNoAntiquot] def scientificLitNoAntiquot.formatter := visitAtom scientificLitKind @[combinator_formatter fieldIdx] def fieldIdx.formatter := visitAtom fieldIdxKind @[combinator_formatter manyNoAntiquot] def manyNoAntiquot.formatter (p : Formatter) : Formatter := do let stx ← getCur visitArgs $ stx.getArgs.size.forM fun _ => p @[combinator_formatter many1NoAntiquot] def many1NoAntiquot.formatter (p : Formatter) : Formatter := manyNoAntiquot.formatter p @[combinator_formatter optionalNoAntiquot] def optionalNoAntiquot.formatter (p : Formatter) : Formatter := visitArgs p @[combinator_formatter many1Unbox] def many1Unbox.formatter (p : Formatter) : Formatter := do let stx ← getCur if stx.getKind == nullKind then do manyNoAntiquot.formatter p else p @[combinator_formatter sepByNoAntiquot] def sepByNoAntiquot.formatter (p pSep : Formatter) : Formatter := do let stx ← getCur visitArgs <| (List.range stx.getArgs.size).reverse.forM fun i => if i % 2 == 0 then p else pSep @[combinator_formatter sepBy1NoAntiquot] def sepBy1NoAntiquot.formatter := sepByNoAntiquot.formatter @[combinator_formatter withoutInfo] def withoutInfo.formatter (p : Formatter) : Formatter := p @[combinator_formatter checkWsBefore] def checkWsBefore.formatter : Formatter := do let st ← get if st.leadWord != "" then pushLine @[combinator_formatter checkPrec] def checkPrec.formatter : Formatter := pure () @[combinator_formatter checkLhsPrec] def checkLhsPrec.formatter : Formatter := pure () @[combinator_formatter setLhsPrec] def setLhsPrec.formatter : Formatter := pure () @[combinator_formatter checkStackTop] def checkStackTop.formatter : Formatter := pure () @[combinator_formatter checkNoWsBefore] def checkNoWsBefore.formatter : Formatter := -- prevent automatic whitespace insertion modify fun st => { st with leadWord := "" } @[combinator_formatter checkLinebreakBefore] def checkLinebreakBefore.formatter : Formatter := pure () @[combinator_formatter checkTailWs] def checkTailWs.formatter : Formatter := pure () @[combinator_formatter checkColEq] def checkColEq.formatter : Formatter := pure () @[combinator_formatter checkColGe] def checkColGe.formatter : Formatter := pure () @[combinator_formatter checkColGt] def checkColGt.formatter : Formatter := pure () @[combinator_formatter checkLineEq] def checkLineEq.formatter : Formatter := pure () @[combinator_formatter eoi] def eoi.formatter : Formatter := pure () @[combinator_formatter checkNoImmediateColon] def checkNoImmediateColon.formatter : Formatter := pure () @[combinator_formatter skip] def skip.formatter : Formatter := pure () @[combinator_formatter pushNone] def pushNone.formatter : Formatter := goLeft @[combinator_formatter interpolatedStr] def interpolatedStr.formatter (p : Formatter) : Formatter := do visitArgs $ (← getCur).getArgs.reverse.forM fun chunk => match chunk.isLit? interpolatedStrLitKind with | some str => push str *> goLeft | none => p @[combinator_formatter _root_.ite, macro_inline] def ite {_ : Type} (c : Prop) [Decidable c] (t e : Formatter) : Formatter := if c then t else e abbrev FormatterAliasValue := AliasValue Formatter builtin_initialize formatterAliasesRef : IO.Ref (NameMap FormatterAliasValue) ← IO.mkRef {} def registerAlias (aliasName : Name) (v : FormatterAliasValue) : IO Unit := do Parser.registerAliasCore formatterAliasesRef aliasName v instance : Coe Formatter FormatterAliasValue := { coe := AliasValue.const } instance : Coe (Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.unary } instance : Coe (Formatter → Formatter → Formatter) FormatterAliasValue := { coe := AliasValue.binary } end Formatter open Formatter def format (formatter : Formatter) (stx : Syntax) : CoreM Format := do trace[PrettyPrinter.format.input] "{Std.format stx}" let options ← getOptions let table ← Parser.builtinTokenTable.get catchInternalId backtrackExceptionId (do let (_, st) ← (concat formatter { table := table, options := options }).run { stxTrav := Syntax.Traverser.fromSyntax stx }; pure $ Format.fill $ st.stack.get! 0) (fun _ => throwError "format: uncaught backtrack exception") def formatCategory (cat : Name) := format <| categoryFormatter cat def formatTerm := formatCategory `term def formatTactic := formatCategory `tactic def formatCommand := formatCategory `command builtin_initialize registerTraceClass `PrettyPrinter.format registerTraceClass `PrettyPrinter.format.backtrack (inherited := true) registerTraceClass `PrettyPrinter.format.input (inherited := true) end PrettyPrinter end Lean
9c33404cb0672d7c0ffacf7b9176d3712c696911
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/linear_algebra/bilinear_form.lean
1cfd5c3857eb0426cbd4eea22c4c552ad3e07ff9
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
9,062
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Andreas Swerdlow -/ import linear_algebra.tensor_product /-! # Bilinear form This file defines a bilinear form over a module. Basic ideas such as orthogonality are also introduced, as well as reflexivive, symmetric and alternating bilinear forms. A bilinear form on an R-module V, is a function from V x V to R, that is linear in both arguments ## Notations Given any term B of type bilin_form, 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. ## References * <https://en.wikipedia.org/wiki/Bilinear_form> ## Tags Bilinear form, -/ universes u v /-- A bilinear form over a module -/ structure bilin_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] := (bilin : M → M → R) (bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z) (bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y)) (bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z) (bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y)) def linear_map.to_bilin {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M →ₗ[R] R) : bilin_form R M := { bilin := λ x y, f x y, bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z, bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul}, bilin_add_right := λ x y z, linear_map.map_add (f x) y z, bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y } namespace bilin_form variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} instance : has_coe_to_fun (bilin_form R M) := ⟨_, λ B, B.bilin⟩ lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y lemma zero_left (x : M) : B 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]} lemma zero_right (x : M) : B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, ring.zero_mul] lemma neg_left (x y : M) : B (-x) y = -(B x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul] lemma neg_right (x y : M) : B x (-y) = -(B x y) := by rw [←@neg_one_smul R _ _, smul_right, neg_one_mul] lemma sub_left (x y z : M) : B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl lemma sub_right (x y z : M) : B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl variable {D : bilin_form R M} @[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _} instance : add_comm_group (bilin_form R M) := { add := λ B D, { bilin := λ x y, B x y + D x y, bilin_add_left := λ x y z, by {rw add_left, rw add_left, ac_refl}, bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]}, bilin_add_right := λ x y z, by {rw add_right, rw add_right, ac_refl}, bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} }, add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc}, zero := { bilin := λ x y, 0, bilin_add_left := λ x y z, (add_zero 0).symm, bilin_smul_left := λ a x y, (mul_zero a).symm, bilin_add_right := λ x y z, (zero_add 0).symm, bilin_smul_right := λ a x y, (mul_zero a).symm }, zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add}, add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero}, neg := λ B, { bilin := λ x y, - (B.1 x y), bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add], bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm], bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add], bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] }, add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self}, add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} } instance : inhabited (bilin_form R M) := ⟨0⟩ section variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] (F : bilin_form R₂ M) (f : M → M) instance to_module : module R₂ (bilin_form R₂ M) := { smul := λ c B, { bilin := λ x y, c * B x y, bilin_add_left := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]}, bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]}, bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_right, left_distrib]}, bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} }, smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib}, add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib}, mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc}, one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul}, zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul}, smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} } def to_linear_map : M →ₗ[R₂] M →ₗ[R₂] R₂ := linear_map.mk₂ R₂ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F) def bilin_linear_map_equiv : (bilin_form R₂ M) ≃ₗ[R₂] (M →ₗ[R₂] M →ₗ[R₂] R₂) := { to_fun := to_linear_map, add := λ B D, rfl, smul := λ a B, rfl, inv_fun := linear_map.to_bilin, left_inv := λ B, by {ext, refl}, right_inv := λ B, by {ext, refl} } end /-- The proposition that two elements of a bilinear form space are orthogonal -/ def is_ortho (B : bilin_form R M) (x y : M) : Prop := B x y = 0 lemma ortho_zero (x : M) : is_ortho B (0 : M) x := zero_left x section variables {R₃ : Type*} [domain R₃] [module R₃ M] {G : bilin_form R₃ M} theorem ortho_smul_left {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G (a • x) y) := begin dunfold is_ortho, split; intro H, { rw [smul_left, H, ring.mul_zero] }, { rw [smul_left, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end theorem ortho_smul_right {x y : M} {a : R₃} (ha : a ≠ 0) : (is_ortho G x y) ↔ (is_ortho G x (a • y)) := begin dunfold is_ortho, split; intro H, { rw [smul_right, H, ring.mul_zero] }, { rw [smul_right, mul_eq_zero] at H, cases H, { trivial }, { exact H }} end end end bilin_form namespace refl_bilin_form open refl_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is reflexive -/ def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0 variable (H : is_refl B) lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩ end refl_bilin_form namespace sym_bilin_form open sym_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is symmetric -/ def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x variable (H : is_sym B) lemma sym (x y : M) : B x y = B y x := H x y lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1 lemma ortho_sym {x y : M} : is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H) end sym_bilin_form namespace alt_bilin_form open alt_bilin_form bilin_form variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M} /-- The proposition that a bilinear form is alternating -/ def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0 variable (H : is_alt B) include H lemma self_eq_zero (x : M) : B x x = 0 := H x lemma neg (x y : M) : - B x y = B y x := begin have H1 : B (x + y) (x + y) = 0, { exact self_eq_zero H (x + y) }, rw [add_left, add_right, add_right, self_eq_zero H, self_eq_zero H, ring.zero_add, ring.add_zero, add_eq_zero_iff_neg_eq] at H1, exact H1, end end alt_bilin_form
b6fcc886851a332089784c84e7ff9c66818f025c
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/ubscalar.lean
1e65664a01eedd20f8253a72451461f9e2a7dff3
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
330
lean
new_frontend structure Foo := (flag : Bool := false) (x : UInt16 := 0) (z : UInt32 := 0) (w : UInt64 := 0) (h : USize := 0) (xs : List Nat := []) set_option trace.compiler.ir.init true def f (s : Foo) : Foo := { s with x := s.x + 1 } def g (flag : Bool) : Foo := let s : Foo := { x := 10, flag := flag }; f s
d8c1b5287955d2523576b7280245b6d2bd598ce0
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/soundness.lean
55608e3a0215287f2af80cbeb9c23e17da7edd43
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
6,692
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Define propositional calculus, valuation, provability, validity, prove soundness. This file is based on Floris van Doorn Coq files. Similar to soundness.lean, but defines Nc in Type. The idea is to be able to prove soundness using recursive equations. -/ open nat bool list decidable attribute [reducible] definition PropVar := nat inductive PropF | Var : PropVar → PropF | Bot : PropF | Conj : PropF → PropF → PropF | Disj : PropF → PropF → PropF | Impl : PropF → PropF → PropF namespace PropF notation `#`:max P:max := Var P local notation A ∨ B := Disj A B local notation A ∧ B := Conj A B local infixr `⇒`:27 := Impl notation `⊥` := Bot def Neg A := A ⇒ ⊥ notation ~ A := Neg A def Top := ~⊥ notation `⊤` := Top def BiImpl A B := A ⇒ B ∧ B ⇒ A infixr `⇔`:27 := BiImpl def valuation := PropVar → bool def TrueQ (v : valuation) : PropF → bool | (# P) := v P | ⊥ := ff | (A ∨ B) := TrueQ A || TrueQ B | (A ∧ B) := TrueQ A && TrueQ B | (A ⇒ B) := bnot (TrueQ A) || TrueQ B attribute [reducible] def is_true (b : bool) := b = tt -- the valuation v satisfies a list of PropF, if forall (A : PropF) in Γ, -- (TrueQ v A) is tt (the Boolean true) def Satisfies v (Γ : list PropF) := ∀ A, A ∈ Γ → is_true (TrueQ v A) def Models Γ A := ∀ v, Satisfies v Γ → is_true (TrueQ v A) infix `⊨`:80 := Models def Valid p := [] ⊨ p reserve infix ` ⊢ `:26 /- Provability -/ inductive Nc : list PropF → PropF → Type infix ⊢ := Nc | Nax : ∀ Γ A, A ∈ Γ → Γ ⊢ A | ImpI : ∀ Γ A B, A::Γ ⊢ B → Γ ⊢ A ⇒ B | ImpE : ∀ Γ A B, Γ ⊢ A ⇒ B → Γ ⊢ A → Γ ⊢ B | BotC : ∀ Γ A, (~A)::Γ ⊢ ⊥ → Γ ⊢ A | AndI : ∀ Γ A B, Γ ⊢ A → Γ ⊢ B → Γ ⊢ A ∧ B | AndE₁ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ A | AndE₂ : ∀ Γ A B, Γ ⊢ A ∧ B → Γ ⊢ B | OrI₁ : ∀ Γ A B, Γ ⊢ A → Γ ⊢ A ∨ B | OrI₂ : ∀ Γ A B, Γ ⊢ B → Γ ⊢ A ∨ B | OrE : ∀ Γ A B C, Γ ⊢ A ∨ B → A::Γ ⊢ C → B::Γ ⊢ C → Γ ⊢ C infix ⊢ := Nc def Provable A := [] ⊢ A def Prop_Soundness := ∀ A, Provable A → Valid A def Prop_Completeness := ∀ A, Valid A → Provable A open Nc lemma weakening2 : ∀ {Γ A Δ}, Γ ⊢ A → Γ ⊆ Δ → Δ ⊢ A | ._ ._ Δ (Nax Γ A Hin) Hs := Nax _ _ (Hs Hin) | ._ .(A ⇒ B) Δ (ImpI Γ A B H) Hs := ImpI _ _ _ (weakening2 H (cons_subset_cons A Hs)) | ._ ._ Δ (ImpE Γ A B H₁ H₂) Hs := ImpE _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (BotC Γ A H) Hs := BotC _ _ (weakening2 H (cons_subset_cons (~A) Hs)) | ._ .(A ∧ B) Δ (AndI Γ A B H₁ H₂) Hs := AndI _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ Hs) | ._ ._ Δ (AndE₁ Γ A B H) Hs := AndE₁ _ _ _ (weakening2 H Hs) | ._ ._ Δ (AndE₂ Γ A B H) Hs := AndE₂ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₁ Γ A B H) Hs := OrI₁ _ _ _ (weakening2 H Hs) | ._ .(A ∨ B) Δ (OrI₂ Γ A B H) Hs := OrI₂ _ _ _ (weakening2 H Hs) | ._ ._ Δ (OrE Γ A B C H₁ H₂ H₃) Hs := OrE _ _ _ _ (weakening2 H₁ Hs) (weakening2 H₂ (cons_subset_cons A Hs)) (weakening2 H₃ (cons_subset_cons B Hs)) lemma weakening : ∀ Γ Δ A, Γ ⊢ A → Γ++Δ ⊢ A := λ Γ Δ A H, weakening2 H (subset_append_left Γ Δ) lemma deduction : ∀ Γ A B, Γ ⊢ A ⇒ B → A::Γ ⊢ B := λ Γ A B H, ImpE _ _ _ (weakening2 H (subset_cons A Γ)) (Nax _ _ (mem_cons_self A Γ)) lemma prov_impl : ∀ A B, Provable (A ⇒ B) → ∀ Γ, Γ ⊢ A → Γ ⊢ B := λ A B Hp Γ Ha, have wHp : Γ ⊢ (A ⇒ B), from weakening _ _ _ Hp, ImpE _ _ _ wHp Ha lemma Satisfies_cons : ∀ {A Γ v}, Satisfies v Γ → is_true (TrueQ v A) → Satisfies v (A::Γ) := λ A Γ v s t B BinAG, or.elim BinAG (λ e : B = A, by rewrite e; exact t) (λ i : B ∈ Γ, s _ i) attribute [simp] is_true TrueQ theorem Soundness_general {v : valuation} : ∀ {A Γ}, Γ ⊢ A → Satisfies v Γ → is_true (TrueQ v A) | ._ ._ (Nax Γ A Hin) s := s _ Hin | .(A ⇒ B) ._ (ImpI Γ A B H) s := by_cases (λ t : is_true (TrueQ v A), have Satisfies v (A::Γ), from Satisfies_cons s t, have TrueQ v B = tt, from Soundness_general H this, by simph) (λ f : ¬ is_true (TrueQ v A), have TrueQ v A = ff, by simp at f; simph, have bnot (TrueQ v A) = tt, by simph, by simph) | ._ ._ (ImpE Γ A B H₁ H₂) s := have aux : TrueQ v A = tt, from Soundness_general H₂ s, have bnot (TrueQ v A) || TrueQ v B = tt, from Soundness_general H₁ s, by simp [aux] at this; simph | ._ ._ (BotC Γ A H) s := by_contradiction (λ n : TrueQ v A ≠ tt, have TrueQ v A = ff, by {simp at n; simph}, have TrueQ v (~A) = tt, begin change (bnot (TrueQ v A) || ff = tt), simph end, have Satisfies v ((~A)::Γ), from Satisfies_cons s this, have TrueQ v ⊥ = tt, from Soundness_general H this, absurd this ff_ne_tt) | .(A ∧ B) ._ (AndI Γ A B H₁ H₂) s := have TrueQ v A = tt, from Soundness_general H₁ s, have TrueQ v B = tt, from Soundness_general H₂ s, by simph | ._ ._ (AndE₁ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp [TrueQ] at this; simph [is_true] | ._ ._ (AndE₂ Γ A B H) s := have TrueQ v (A ∧ B) = tt, from Soundness_general H s, by simp at this; simph | .(A ∨ B) ._ (OrI₁ Γ A B H) s := have TrueQ v A = tt, from Soundness_general H s, by simph | .(A ∨ B) ._ (OrI₂ Γ A B H) s := have TrueQ v B = tt, from Soundness_general H s, by simph | ._ ._ (OrE Γ A B C H₁ H₂ H₃) s := have TrueQ v A || TrueQ v B = tt, from Soundness_general H₁ s, have or (TrueQ v A = tt) (TrueQ v B = tt), by simp at this; simph, or.elim this (λ At, have Satisfies v (A::Γ), from Satisfies_cons s At, Soundness_general H₂ this) (λ Bt, have Satisfies v (B::Γ), from Satisfies_cons s Bt, Soundness_general H₃ this) theorem Soundness : Prop_Soundness := λ A H v s, Soundness_general H s end PropF
26df73cbd1d78e385b5cc1ca615e8b66b0f6e0f5
c46a17c860913da8a635099f06be3a2416f6cdab
/common_knowledge.lean
1ca253e8c1f4fafdc8f51df179c6a79ad0af8a79
[]
no_license
vladfi1/vfds
4ed0b7fd810218c74eef933364b9aa6be4cc2551
664b0d1c8126c93b379115ffe5da7b943f3375d5
refs/heads/master
1,585,024,431,435
1,535,567,828,000
1,535,567,828,000
142,457,395
0
1
null
1,532,805,351,000
1,532,617,692,000
Lean
UTF-8
Lean
false
false
1,890
lean
constants p1 p2 : bool def bool_to_nat : bool -> nat | ff := 0 | tt := 1 def count (p1 p2 : bool) : nat := bool_to_nat p1 + bool_to_nat p2 inductive person : Type | a | b def people : list person := [person.a, person.b] constant color : person -> bool constant beliefs (p : person) : nat -> set Prop def is_rational (s : set Prop) : Prop := ∀ (p q : Prop), (p -> q) -> (p ∈ s) -> (q ∈ s) axiom everyone_rational : ∀ p n, is_rational (beliefs p n) --axiom initial_beliefs : ∀ p, def all_believe (beliefs : set (set Prop)) (p : Prop) : Prop := forall b, b ∈ beliefs -> p ∈ b def common_knowledge_core (beliefs : set (set Prop)) (p : Prop) : nat -> Prop | 0 := all_believe beliefs p | (nat.succ n) := all_believe beliefs (common_knowledge_core n) def common_knowledge (beliefs : set (set Prop)) (p : Prop) : Prop := forall n, common_knowledge_core beliefs p n def list_as_set {α : Type} (xs : list α) : set α := λ x, x ∈ xs def get_beliefs (n : nat) : set (set Prop) := list_as_set (list.map (λ p, beliefs p n) people) axiom initial_beliefs : common_knowledge (get_beliefs 0) (∃ p, color p) def bool_ite {α : Type} (t f : α) : bool -> α | ff := f | tt := t def see (p : person) : Prop := bool_ite (color p = tt) (color p = ff) (color p) example : forall p, see p := begin intro, unfold see, cases (color p), unfold bool_ite, unfold bool_ite, end def typeof {α : Sort _} (a : α) := α axiom initial_beliefs' : forall (p q : person), p ≠ q -> see q ∈ beliefs p 0 axiom initial_beliefs'' : common_knowledge (get_beliefs 0) (typeof initial_beliefs') namespace test constants a a' : bool constant beliefs : set Prop axiom beliefs_rational : is_rational beliefs axiom true_beliefs : true ∈ beliefs example : (a = tt) -> ((a = tt) ∈ beliefs) := begin intro, apply beliefs_rational, intro, assumption, apply true_beliefs, end end test
161e0729f2face53d967f380a7036c04e5204d8e
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/testing/slim_check/sampleable.lean
ede25f9a14035568f7901b736988ad7de8fbf738
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
31,386
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import data.lazy_list.basic import data.tree import data.int.basic import control.bifunctor import tactic.linarith import testing.slim_check.gen /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ universes u v w namespace slim_check variables (α : Type u) local infix ` ≺ `:50 := has_well_founded.r /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α} [has_sizeof α] (x y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ @[reducible] def shrink_fn (α : Type*) [has_sizeof α] := Π x : α, lazy_list { y : α // sizeof_lt y x } /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable := [wf : has_sizeof α] (sample [] : gen α) (shrink : Π x : α, lazy_list { y : α // @sizeof _ wf y < @sizeof _ wf x } := λ _, lazy_list.nil) attribute [instance, priority 100] has_well_founded_of_has_sizeof default_has_sizeof attribute [instance, priority 200] sampleable.wf /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [functor F] := [wf : Π α [has_sizeof α], has_sizeof (F α)] (sample [] : ∀ {α}, gen α → gen (F α)) (shrink : ∀ α [has_sizeof α], shrink_fn α → shrink_fn (F α)) (p_repr : ∀ α, has_repr α → has_repr (F α)) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] := [wf : Π α β [has_sizeof α] [has_sizeof β], has_sizeof (F α β)] (sample [] : ∀ {α β}, gen α → gen β → gen (F α β)) (shrink : ∀ α β [has_sizeof α] [has_sizeof β], shrink_fn α → shrink_fn β → shrink_fn (F α β)) (p_repr : ∀ α β, has_repr α → has_repr β → has_repr (F α β)) export sampleable (sample shrink) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ meta def sampleable.mk_trivial_interp : tactic unit := tactic.refine ``(id) /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) := (proxy_repr : Type v) [wf : has_sizeof proxy_repr] (interp [] : proxy_repr → α . sampleable.mk_trivial_interp) [p_repr : has_repr proxy_repr] (sample [] : gen proxy_repr) (shrink : shrink_fn proxy_repr) attribute [instance, priority 100] sampleable_ext.p_repr sampleable_ext.wf open nat lazy_list section prio open sampleable_ext set_option default_priority 50 instance sampleable_ext.of_sampleable {α} [sampleable α] [has_repr α] : sampleable_ext α := { proxy_repr := α, sample := sampleable.sample α, shrink := shrink } instance sampleable.functor {α} {F} [functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := { wf := _, sample := sampleable_functor.sample F (sampleable.sample α), shrink := sampleable_functor.shrink α sampleable.shrink } instance sampleable.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := { wf := _, sample := sampleable_bifunctor.sample F (sampleable.sample α) (sampleable.sample β), shrink := sampleable_bifunctor.shrink α β sampleable.shrink sampleable.shrink } set_option default_priority 100 instance sampleable_ext.functor {α} {F} [functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := { wf := _, proxy_repr := F (proxy_repr α), interp := functor.map (interp _), sample := sampleable_functor.sample F (sampleable_ext.sample α), shrink := sampleable_functor.shrink _ sampleable_ext.shrink, p_repr := sampleable_functor.p_repr _ sampleable_ext.p_repr } instance sampleable_ext.bifunctor {α β} {F} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := { wf := _, proxy_repr := F (proxy_repr α) (proxy_repr β), interp := bifunctor.bimap (interp _) (interp _), sample := sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β), shrink := sampleable_bifunctor.shrink _ _ sampleable_ext.shrink sampleable_ext.shrink, p_repr := sampleable_bifunctor.p_repr _ _ sampleable_ext.p_repr sampleable_ext.p_repr } end prio /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) : Π n : ℕ, n ≤ k → list { m : ℕ // has_well_founded.r m k } → list { m : ℕ // has_well_founded.r m k } | n hn ls := if h : n ≤ 1 then ls.reverse else have h₂ : 0 < n, by linarith, have 1 * n / 2 < n, from nat.div_lt_of_lt_mul (nat.mul_lt_mul_of_pos_right (by norm_num) h₂), have n / 2 < n, by simpa, let m := n / 2 in have h₀ : m ≤ k, from le_trans (le_of_lt this) hn, have h₃ : 0 < m, by simp only [m, lt_iff_add_one_le, zero_add]; rw [le_div_iff_mul_le]; linarith, have h₁ : k - m < k, from nat.sub_lt (lt_of_lt_of_le h₂ hn) h₃, nat.shrink' m h₀ (⟨k - m, h₁⟩ :: ls) /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : list { m : ℕ // has_well_founded.r m n } := if h : n > 0 then have ∀ k, 1 < k → n / k < n, from λ k hk, nat.div_lt_of_lt_mul (suffices 1 * n < k * n, by simpa, nat.mul_lt_mul_of_pos_right hk h), ⟨n/11, this _ (by norm_num)⟩ :: ⟨n/3, this _ (by norm_num)⟩ :: nat.shrink' n n (le_refl _) [] else [] open gen /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := { wf := ⟨ sizeof ∘ g ⟩, sample := f <$> sample α, shrink := λ x, have ∀ a, sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x), by introv h'; solve_by_elim [lt_of_le_of_lt], subtype.map f this <$> shrink (g x) } instance nat.sampleable : sampleable ℕ := { sample := sized $ λ sz, freq [(1, coe <$> choose_any (fin $ succ (sz^3))), (3, coe <$> choose_any (fin $ succ sz))] dec_trivial, shrink := λ x, lazy_list.of_list $ nat.shrink x } /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → option α := well_founded.fix has_well_founded.wf $ λ x f_rec, do trace sformat!"{x} : {(shrink x).to_list}" $ pure (), y ← (shrink x).find (λ a, p a), f_rec y y.property <|> some y.val . instance fin.sampleable {n} [fact $ 0 < n] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val $ λ i, (mod_le _ _ : i % n ≤ i) @[priority 100] instance fin.sampleable' {n} : sampleable (fin (succ n)) := sampleable.lift ℕ fin.of_nat subtype.val $ λ i, (mod_le _ _ : i % succ n ≤ i) instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred $ λ a, by unfold_wf; simp only [pnat.nat_pred, succ_pnat, pnat.mk_coe, nat.sub_zero, succ_sub_succ_eq_sub] /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : has_sizeof ℤ := ⟨ int.nat_abs ⟩ local attribute [instance, priority 2000] int.has_sizeof instance int.sampleable : sampleable ℤ := { wf := _, sample := sized $ λ sz, freq [(1, subtype.val <$> choose (-(sz^3 + 1) : ℤ) (sz^3 + 1) (neg_le_self dec_trivial)), (3, subtype.val <$> choose (-(sz + 1)) (sz + 1) (neg_le_self dec_trivial))] dec_trivial, shrink := λ x, lazy_list.of_list $ (nat.shrink $ int.nat_abs x).bind $ λ ⟨y,h⟩, [⟨y, h⟩, ⟨-y, by dsimp [sizeof,has_sizeof.sizeof]; rw int.nat_abs_neg; exact h ⟩] } instance bool.sampleable : sampleable bool := { wf := ⟨ λ b, if b then 1 else 0 ⟩, sample := do { x ← choose_any bool, return x }, shrink := λ b, if h : b then lazy_list.singleton ⟨ff, by cases h; unfold_wf⟩ else lazy_list.nil } /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α β} [has_sizeof α] [has_sizeof β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) | ⟨x₀,x₁⟩ := let xs₀ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_a x₀).map $ subtype.map (λ a, (a, x₁)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h), xs₁ : lazy_list { y : α × β // sizeof_lt y (x₀,x₁) } := (shr_b x₁).map $ subtype.map (λ a, (x₀, a)) (λ x h, by dsimp [sizeof_lt]; unfold_wf; apply h) in xs₀.append xs₁ instance prod.sampleable : sampleable_bifunctor.{u v} prod := { wf := _, sample := λ α β sama samb, do { ⟨x⟩ ← (uliftable.up $ sama : gen (ulift.{max u v} α)), ⟨y⟩ ← (uliftable.up $ samb : gen (ulift.{max u v} β)), pure (x,y) }, shrink := @prod.shrink, p_repr := @prod.has_repr } instance sigma.sampleable {α β} [sampleable α] [sampleable β] : sampleable (Σ _ : α, β) := sampleable.lift (α × β) (λ ⟨x,y⟩, ⟨x,y⟩) (λ ⟨x,y⟩, ⟨x,y⟩) $ λ ⟨x,y⟩, le_refl _ /-- shrinking function for sum types -/ def sum.shrink {α β} [has_sizeof α] [has_sizeof β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) | (sum.inr x) := (shrink_β x).map $ subtype.map sum.inr $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim | (sum.inl x) := (shrink_α x).map $ subtype.map sum.inl $ λ a, by dsimp [sizeof_lt]; unfold_wf; solve_by_elim instance sum.sampleable : sampleable_bifunctor.{u v} sum := { wf := _, sample := λ (α : Type u) (β : Type v) sam_α sam_β, (@uliftable.up_map gen.{u} gen.{max u v} _ _ _ _ (@sum.inl α β) sam_α <|> @uliftable.up_map gen.{v} gen.{max v u} _ _ _ _ (@sum.inr α β) sam_β), shrink := λ α β Iα Iβ shr_α shr_β, @sum.shrink _ _ Iα Iβ shr_α shr_β, p_repr := @sum.has_repr } instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (λ x, prod.cases_on x rat.mk_pnat) (λ r, (r.num, ⟨r.denom, r.pos⟩)) $ begin intro i, rcases i with ⟨x,⟨y,hy⟩⟩; unfold_wf; dsimp [rat.mk_pnat], mono*, { rw [← int.coe_nat_le, ← int.abs_eq_nat_abs, ← int.abs_eq_nat_abs], apply int.abs_div_le_abs }, { change _ - 1 ≤ y-1, apply nat.sub_le_sub_right, apply nat.div_le_of_le_mul, suffices : 1 * y ≤ x.nat_abs.gcd y * y, { simpa }, apply nat.mul_le_mul_right, apply gcd_pos_of_pos_right _ hy } end /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : nat) (characters : string) : sampleable char := { sample := do { x ← choose_nat 0 length dec_trivial, if x.val = 0 then do n ← sample ℕ, pure $ char.of_nat n else do i ← choose_nat 0 (characters.length - 1) dec_trivial, pure (characters.mk_iterator.nextn i).curr }, shrink := λ _, lazy_list.nil } instance char.sampleable : sampleable char := sampleable_char 3 " 0123abcABC:,;`\\/" variables {α} section list_shrink variables [has_sizeof α] (shr : Π x : α, lazy_list { y : α // sizeof_lt y x }) lemma list.sizeof_drop_lt_sizeof_of_lt_length {xs : list α} {k} (hk : 0 < k) (hk' : k < xs.length) : sizeof (list.drop k xs) < sizeof xs := begin induction xs with x xs generalizing k, { cases hk' }, cases k, { cases hk }, have : sizeof xs < sizeof (x :: xs), { unfold_wf, linarith }, cases k, { simp only [this, list.drop] }, { simp only [list.drop], transitivity, { solve_by_elim [xs_ih, lt_of_succ_lt_succ hk', zero_lt_succ] }, { assumption } } end lemma list.sizeof_cons_lt_right (a b : α) {xs : list α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := by unfold_wf; assumption lemma list.sizeof_cons_lt_left (x : α) {xs xs' : list α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := by unfold_wf; assumption lemma list.sizeof_append_lt_left {xs ys ys' : list α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := begin induction xs, { apply h }, { unfold_wf, simp only [list.sizeof, add_lt_add_iff_left], exact xs_ih } end lemma list.one_le_sizeof (xs : list α) : 1 ≤ sizeof xs := by cases xs; unfold_wf; [refl, linarith] /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes (k : ℕ) (hk : 0 < k) : Π (xs : list α) n, n = xs.length → lazy_list { ys : list α // sizeof_lt ys xs } | xs n hn := if hkn : k > n then lazy_list.nil else if hkn' : k = n then have 1 < xs.sizeof, by { subst_vars, cases xs, { contradiction }, unfold_wf, apply lt_of_lt_of_le, show 1 < 1 + has_sizeof.sizeof xs_hd + 1, { linarith }, { mono, apply list.one_le_sizeof, } }, lazy_list.singleton ⟨[], this ⟩ else have h₂ : k < xs.length, from hn ▸ lt_of_le_of_ne (le_of_not_gt hkn) hkn', match list.split_at k xs, rfl : Π ys, ys = list.split_at k xs → _ with | ⟨xs₁,xs₂⟩, h := have h₄ : xs₁ = xs.take k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have h₃ : xs₂ = xs.drop k, by simp only [list.split_at_eq_take_drop, prod.mk.inj_iff] at h; tauto, have sizeof xs₂ < sizeof xs, by rw h₃; solve_by_elim [list.sizeof_drop_lt_sizeof_of_lt_length], have h₁ : n - k = xs₂.length, by simp only [h₃, ←hn, list.length_drop], have h₅ : ∀ (a : list α), sizeof_lt a xs₂ → sizeof_lt (xs₁ ++ a) xs, by intros a h; rw [← list.take_append_drop k xs, ← h₃, ← h₄]; solve_by_elim [list.sizeof_append_lt_left], lazy_list.cons ⟨xs₂, this⟩ $ subtype.map ((++) xs₁) h₅ <$> list.shrink_removes xs₂ (n - k) h₁ end /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one : shrink_fn (list α) | [] := lazy_list.nil | (x :: xs) := lazy_list.append (subtype.map (λ x', x' :: xs) (λ a, list.sizeof_cons_lt_right _ _) <$> shr x) (subtype.map ((::) x) (λ _, list.sizeof_cons_lt_left _) <$> list.shrink_one xs) /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with (xs : list α) : lazy_list { ys : list α // sizeof_lt ys xs } := let n := xs.length in lazy_list.append ((lazy_list.cons n $ (shrink n).reverse.map subtype.val).bind (λ k, if hk : 0 < k then list.shrink_removes k hk xs n rfl else lazy_list.nil )) (list.shrink_one shr _) end list_shrink instance list.sampleable : sampleable_functor list.{u} := { wf := _, sample := λ α sam_α, list_of sam_α, shrink := λ α Iα shr_α, @list.shrink_with _ Iα shr_α, p_repr := @list.has_repr } instance prop.sampleable_ext : sampleable_ext Prop := { proxy_repr := bool, interp := coe, sample := choose_any bool, shrink := λ _, lazy_list.nil } /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type*) := α instance no_shrink.inhabited {α} [inhabited α] : inhabited (no_shrink α) := ⟨ (default α : α) ⟩ /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α} (x : no_shrink α) : α := x instance no_shrink.sampleable {α} [sampleable α] : sampleable (no_shrink α) := { sample := no_shrink.mk <$> sample α } instance string.sampleable : sampleable string := { sample := do { x ← list_of (sample char), pure x.as_string }, .. sampleable.lift (list char) list.as_string string.to_list $ λ _, le_refl _ } /-- implementation of `sampleable (tree α)` -/ def tree.sample (sample : gen α) : ℕ → gen (tree α) | n := if h : n > 0 then have n / 2 < n, from div_lt_self h (by norm_num), tree.node <$> sample <*> tree.sample (n / 2) <*> tree.sample (n / 2) else pure tree.nil /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type*} [has_sizeof α] (t : α) (sh : Π x : α, sizeof_lt x t → lazy_list { y : α // sizeof_lt y x }) : shrink_fn { t' : α // sizeof_lt t' t } | ⟨t',ht'⟩ := (λ t'' : { y : α // sizeof_lt y t' }, ⟨⟨t''.val, lt_trans t''.property ht'⟩, t''.property⟩ ) <$> sh t' ht' lemma tree.one_le_sizeof {α} [has_sizeof α] (t : tree α) : 1 ≤ sizeof t := by cases t; unfold_wf; linarith instance : functor tree := { map := @tree.map } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) : shrink_fn α := well_founded.fix (sizeof_measure_wf _) $ λ t f_rec, lazy_list.join (lazy_list.of_list $ shrink_a t $ λ ⟨t', h⟩, rec_shrink _ f_rec _) lemma rec_shrink_with_eq [has_sizeof α] (shrink_a : Π x : α, shrink_fn { y : α // sizeof_lt y x } → list (lazy_list { y : α // sizeof_lt y x })) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list $ shrink_a x $ λ t', rec_shrink _ (λ x h', rec_shrink_with shrink_a x) _) := begin conv_lhs { rw [rec_shrink_with, well_founded.fix_eq], }, congr, ext ⟨y, h⟩, refl end /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with [has_sizeof α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with $ λ t, match t with | tree.nil := λ f_rec, [] | (tree.node x t₀ t₁) := λ f_rec, have h₂ : sizeof_lt tree.nil (tree.node x t₀ t₁), by clear _match; have := tree.one_le_sizeof t₀; dsimp [sizeof_lt, sizeof, has_sizeof.sizeof] at *; unfold_wf; linarith, have h₀ : sizeof_lt t₀ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, have h₁ : sizeof_lt t₁ (tree.node x t₀ t₁), by dsimp [sizeof_lt]; unfold_wf; linarith, [lazy_list.of_list [⟨tree.nil, h₂⟩, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩], (prod.shrink shrink_a (prod.shrink f_rec f_rec) (x, ⟨t₀, h₀⟩, ⟨t₁, h₁⟩)).map $ λ ⟨⟨y,⟨t'₀, _⟩,⟨t'₁, _⟩⟩,hy⟩, ⟨tree.node y t'₀ t'₁, by revert hy; dsimp [sizeof_lt]; unfold_wf; intro; linarith⟩] end instance sampleable_tree : sampleable_functor tree := { wf := _, sample := λ α sam_α, sized $ tree.sample sam_α, shrink := λ α Iα shr_α, @tree.shrink_with _ Iα shr_α, p_repr := @tree.has_repr } /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type*) := α /-- Add the `small` type tag -/ def small.mk {α} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type*) := α /-- Add the `large` type tag -/ def large.mk {α} (x : α) : large α := x instance small.functor : functor small := id.monad.to_functor instance large.functor : functor large := id.monad.to_functor instance small.inhabited [inhabited α] : inhabited (small α) := ⟨ (default α : α) ⟩ instance large.inhabited [inhabited α] : inhabited (large α) := ⟨ (default α : α) ⟩ instance small.sampleable_functor : sampleable_functor small := { wf := _, sample := λ α samp, gen.resize (λ n, n / 5 + 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance large.sampleable_functor : sampleable_functor large := { wf := _, sample := λ α samp, gen.resize (λ n, n * 5) samp, shrink := λ α _, id, p_repr := λ α, id } instance ulift.sampleable_functor : sampleable_functor ulift.{u v} := { wf := λ α h, ⟨ λ ⟨x⟩, @sizeof α h x ⟩, sample := λ α samp, uliftable.up_map ulift.up $ samp, shrink := λ α _ shr ⟨x⟩, (shr x).map (subtype.map ulift.up (λ a h, h)), p_repr := λ α h, ⟨ @repr α h ∘ ulift.down ⟩ } /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ instance nat_le.sampleable {y} : slim_check.sampleable { x : ℕ // x ≤ y } := { sample := do { ⟨x,h⟩ ← slim_check.gen.choose_nat 0 y dec_trivial, pure ⟨x, h.2⟩}, shrink := λ ⟨x, h⟩, (λ a : subtype _, subtype.rec_on a $ λ x' h', ⟨⟨x', le_trans (le_of_lt h') h⟩, h'⟩) <$> shrink x } instance nat_ge.sampleable {x} : slim_check.sampleable { y : ℕ // x ≤ y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y, by norm_num⟩ }, shrink := λ ⟨y, h⟩, (λ a : { y' // sizeof y' < sizeof (y - x) }, subtype.rec_on a $ λ δ h', ⟨⟨x + δ, nat.le_add_right _ _⟩, nat.add_lt_of_lt_sub_left h'⟩) <$> shrink (y - x) } /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ instance nat_gt.sampleable {x} : slim_check.sampleable { y : ℕ // x < y } := { sample := do { (y : ℕ) ← slim_check.sampleable.sample ℕ, pure ⟨x+y+1, by linarith⟩ }, shrink := λ x, shrink _ } /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ instance le.sampleable {y : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { x : α // x ≤ y } := { sample := do { x ← sample α, pure ⟨y - abs x, sub_le_self _ (abs_nonneg _) ⟩ }, shrink := λ _, lazy_list.nil } instance ge.sampleable {x : α} [sampleable α] [linear_ordered_add_comm_group α] : slim_check.sampleable { y : α // x ≤ y } := { sample := do { y ← sample α, pure ⟨x + abs y, by norm_num [abs_nonneg]⟩ }, shrink := λ _, lazy_list.nil } /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ instance int_le.sampleable {y : ℤ} : slim_check.sampleable { x : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨y - n, int.sub_left_le_of_le_add $ by simp⟩) (λ ⟨i, h⟩, (y - i).nat_abs) (λ n, by unfold_wf; simp [int_le.sampleable._match_1]; ring) instance int_ge.sampleable {x : ℤ} : slim_check.sampleable { y : ℤ // x ≤ y } := sampleable.lift ℕ (λ n, ⟨x + n, by simp⟩) (λ ⟨i, h⟩, (i - x).nat_abs) (λ n, by unfold_wf; simp [int_ge.sampleable._match_1]; ring) instance int_lt.sampleable {y} : slim_check.sampleable { x : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨y - (n+1), int.sub_left_lt_of_lt_add $ by linarith [int.coe_nat_nonneg n]⟩) (λ ⟨i, h⟩, (y - i - 1).nat_abs) (λ n, by unfold_wf; simp [int_lt.sampleable._match_1]; ring) instance int_gt.sampleable {x} : slim_check.sampleable { y : ℤ // x < y } := sampleable.lift ℕ (λ n, ⟨x + (n+1), by linarith⟩) (λ ⟨i, h⟩, (i - x - 1).nat_abs) (λ n, by unfold_wf; simp [int_gt.sampleable._match_1]; ring) /-! ### Subtypes of any `list` -/ instance perm.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm xs ys } := { sample := permutation_of xs, shrink := λ _, lazy_list.nil } instance perm'.slim_check {xs : list α} : slim_check.sampleable { ys : list α // list.perm ys xs } := { sample := subtype.map id (@list.perm.symm α _) <$> permutation_of xs, shrink := λ _, lazy_list.nil } setup_tactic_parser open tactic /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io unit := do xs ← io.run_rand $ uliftable.down $ do { xs ← (list.range 10).mmap $ g.run ∘ ulift.up, pure ⟨xs.map repr⟩ }, xs.mmap' io.put_str_ln /-- Create a `gen α` expression from the argument of `#sample` -/ meta def mk_generator (e : expr) : tactic (expr × expr) := do t ← infer_type e, match t with | `(gen %%t) := do repr_inst ← mk_app ``has_repr [t] >>= mk_instance, pure (repr_inst, e) | _ := do samp_inst ← to_expr ``(sampleable_ext %%e) >>= mk_instance, repr_inst ← mk_mapp ``sampleable_ext.p_repr [e, samp_inst], gen ← mk_mapp ``sampleable_ext.sample [none, samp_inst], pure (repr_inst, gen) end /-- `#sample my_type`, where `my_type` has an instance of `sampleable`, prints ten random values of type `my_type` of using an increasing size parameter. ```lean #sample nat -- prints -- 0 -- 0 -- 2 -- 24 -- 64 -- 76 -- 5 -- 132 -- 8 -- 449 -- or some other sequence of numbers #sample list int -- prints -- [] -- [1, 1] -- [-7, 9, -6] -- [36] -- [-500, 105, 260] -- [-290] -- [17, 156] -- [-2364, -7599, 661, -2411, -3576, 5517, -3823, -968] -- [-643] -- [11892, 16329, -15095, -15461] -- or whatever ``` -/ @[user_command] meta def sample_cmd (_ : parse $ tk "#sample") : lean.parser unit := do e ← texpr, of_tactic $ do e ← i_to_expr e, (repr_inst, gen) ← mk_generator e, print_samples ← mk_mapp ``print_samples [none, repr_inst, gen], sample ← eval_expr (io unit) print_samples, unsafe_run_io sample end slim_check
4ecbfbbd4ee52a5dc71f8a20b9bdc3c9d5b37d25
c777c32c8e484e195053731103c5e52af26a25d1
/src/combinatorics/simple_graph/ends/properties.lean
1daaae2a569e205910cca81d65614720710b4e3a
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
740
lean
/- Copyright (c) 2022 Anand Rao, Rémi Bottinelli. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anand Rao, Rémi Bottinelli -/ import combinatorics.simple_graph.ends.defs /-! # Properties of the ends of graphs This file is meant to contain results about the ends of (locally finite connected) graphs. -/ variables {V : Type} (G : simple_graph V) namespace simple_graph instance [finite V] : is_empty G.end := ⟨ begin rintro ⟨s, _⟩, casesI nonempty_fintype V, obtain ⟨v, h⟩ := (s $ opposite.op finset.univ).nonempty, exact set.disjoint_iff.mp (s _).disjoint_right ⟨by simp only [opposite.unop_op, finset.coe_univ], h⟩, end ⟩ end simple_graph
31b3eebebecc6c383a9d4190d85ce4f212e64742
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/adjunction/whiskering.lean
9d005d33b0cd57b464bc3f50e2cc2d00a4d2bdee
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
2,493
lean
/- Copyright (c) 2021 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import category_theory.adjunction import category_theory.whiskering /-! Given categories `C D E`, functors `F : D ⥤ E` and `G : E ⥤ D` with an adjunction `F ⊣ G`, we provide the induced adjunction between the functor categories `C ⥤ D` and `C ⥤ E`, and the functor categories `E ⥤ C` and `D ⥤ C`. -/ namespace category_theory.adjunction open category_theory variables (C : Type*) {D E : Type*} [category C] [category D] [category E] {F : D ⥤ E} {G : E ⥤ D} -- `tidy` works for all the proofs in this definition, but it's fairly slow. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_right C _ _).obj F ⊣ (whiskering_right C _ _).obj G`. -/ @[simps unit_app_app counit_app_app] protected def whisker_right (adj : F ⊣ G) : (whiskering_right C D E).obj F ⊣ (whiskering_right C E D).obj G := mk_of_unit_counit { unit := { app := λ X, (functor.right_unitor _).inv ≫ whisker_left X adj.unit ≫ (functor.associator _ _ _).inv, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).hom ≫ whisker_left X adj.counit ≫ (functor.right_unitor _).hom, naturality' := by { intros, ext, dsimp, simp } }, left_triangle' := by { ext, dsimp, simp }, right_triangle' := by { ext, dsimp, simp } } -- `tidy` gets stuck for `left_triangle'` and `right_triangle'`. /-- Given an adjunction `F ⊣ G`, this provides the natural adjunction `(whiskering_left _ _ C).obj G ⊣ (whiskering_left _ _ C).obj F`. -/ @[simps unit_app_app counit_app_app] protected def whisker_left (adj : F ⊣ G) : (whiskering_left E D C).obj G ⊣ (whiskering_left D E C).obj F := mk_of_unit_counit { unit := { app := λ X, (functor.left_unitor _).inv ≫ whisker_right adj.unit X ≫ (functor.associator _ _ _).hom, naturality' := by { intros, ext, dsimp, simp } }, counit := { app := λ X, (functor.associator _ _ _).inv ≫ whisker_right adj.counit X ≫ (functor.left_unitor _).hom, naturality' := by by { intros, ext, dsimp, simp } }, left_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp }, right_triangle' := by { ext x, dsimp, simp only [category.id_comp, category.comp_id, ← x.map_comp], simp } } end category_theory.adjunction
edc1196e4eb9bd5c05c76551b8b0589b5849c3e1
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebraic_geometry/locally_ringed_space.lean
3e7c3c1bcbcb1c555a201e8e79d681383c6923ef
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,165
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 algebraic_geometry.ringed_space import algebraic_geometry.stalks import logic.equiv.transfer_instance /-! # The category of locally ringed spaces We define (bundled) locally ringed spaces (as `SheafedSpace CommRing` along with the fact that the stalks are local rings), and morphisms between these (morphisms in `SheafedSpace` with `is_local_ring_hom` on the stalk maps). -/ universes v u open category_theory open Top open topological_space open opposite open category_theory.category category_theory.functor namespace algebraic_geometry /-- A `LocallyRingedSpace` is a topological space equipped with a sheaf of commutative rings such that all the stalks are local rings. A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphisms induced on stalks are local ring homomorphisms. -/ @[nolint has_nonempty_instance] structure LocallyRingedSpace extends SheafedSpace CommRing := (local_ring : ∀ x, local_ring (presheaf.stalk x)) attribute [instance] LocallyRingedSpace.local_ring namespace LocallyRingedSpace variables (X : LocallyRingedSpace) /-- An alias for `to_SheafedSpace`, where the result type is a `RingedSpace`. This allows us to use dot-notation for the `RingedSpace` namespace. -/ def to_RingedSpace : RingedSpace := X.to_SheafedSpace /-- The underlying topological space of a locally ringed space. -/ def to_Top : Top := X.1.carrier instance : has_coe_to_sort LocallyRingedSpace (Type u) := ⟨λ X : LocallyRingedSpace, (X.to_Top : Type u)⟩ instance (x : X) : _root_.local_ring (X.to_PresheafedSpace.stalk x) := X.local_ring x -- PROJECT: how about a typeclass "has_structure_sheaf" to mediate the 𝒪 notation, rather -- than defining it over and over for PresheafedSpace, LRS, Scheme, etc. /-- The structure sheaf of a locally ringed space. -/ def 𝒪 : sheaf CommRing X.to_Top := X.to_SheafedSpace.sheaf /-- A morphism of locally ringed spaces is a morphism of ringed spaces such that the morphims induced on stalks are local ring homomorphisms. -/ @[ext] structure hom (X Y : LocallyRingedSpace.{u}) : Type u := (val : X.to_SheafedSpace ⟶ Y.to_SheafedSpace) (prop : ∀ x, is_local_ring_hom (PresheafedSpace.stalk_map val x)) instance : quiver LocallyRingedSpace := ⟨hom⟩ /-- The stalk of a locally ringed space, just as a `CommRing`. -/ -- TODO perhaps we should make a bundled `LocalRing` and return one here? -- TODO define `sheaf.stalk` so we can write `X.𝒪.stalk` here? noncomputable def stalk (X : LocallyRingedSpace) (x : X) : CommRing := X.presheaf.stalk x /-- A morphism of locally ringed spaces `f : X ⟶ Y` induces a local ring homomorphism from `Y.stalk (f x)` to `X.stalk x` for any `x : X`. -/ noncomputable def stalk_map {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : Y.stalk (f.1.1 x) ⟶ X.stalk x := PresheafedSpace.stalk_map f.1 x instance {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : is_local_ring_hom (stalk_map f x) := f.2 x instance {X Y : LocallyRingedSpace} (f : X ⟶ Y) (x : X) : is_local_ring_hom (PresheafedSpace.stalk_map f.1 x) := f.2 x /-- The identity morphism on a locally ringed space. -/ @[simps] def id (X : LocallyRingedSpace) : hom X X := ⟨𝟙 _, λ x, by { erw PresheafedSpace.stalk_map.id, apply is_local_ring_hom_id, }⟩ instance (X : LocallyRingedSpace) : inhabited (hom X X) := ⟨id X⟩ /-- Composition of morphisms of locally ringed spaces. -/ def comp {X Y Z : LocallyRingedSpace} (f : hom X Y) (g : hom Y Z) : hom X Z := ⟨f.val ≫ g.val, λ x, begin erw PresheafedSpace.stalk_map.comp, exact @is_local_ring_hom_comp _ _ _ _ _ _ _ _ (f.2 _) (g.2 _), end⟩ /-- The category of locally ringed spaces. -/ instance : category LocallyRingedSpace := { hom := hom, id := id, comp := λ X Y Z f g, comp f g, comp_id' := by { intros, ext1, simp [comp], }, id_comp' := by { intros, ext1, simp [comp], }, assoc' := by { intros, ext1, simp [comp], }, }. /-- The forgetful functor from `LocallyRingedSpace` to `SheafedSpace CommRing`. -/ @[simps] def forget_to_SheafedSpace : LocallyRingedSpace ⥤ SheafedSpace CommRing := { obj := λ X, X.to_SheafedSpace, map := λ X Y f, f.1, } instance : faithful forget_to_SheafedSpace := {} /-- The forgetful functor from `LocallyRingedSpace` to `Top`. -/ @[simps] def forget_to_Top : LocallyRingedSpace ⥤ Top := forget_to_SheafedSpace ⋙ SheafedSpace.forget _ @[simp] lemma comp_val {X Y Z : LocallyRingedSpace} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val = f.val ≫ g.val := rfl @[simp] lemma comp_val_c {X Y Z : LocallyRingedSpace.{u}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).val.c = g.val.c ≫ (presheaf.pushforward _ g.val.base).map f.val.c := rfl lemma comp_val_c_app {X Y Z : LocallyRingedSpace} (f : X ⟶ Y) (g : Y ⟶ Z) (U : (opens Z)ᵒᵖ) : (f ≫ g).val.c.app U = g.val.c.app U ≫ f.val.c.app (op $ (opens.map g.val.base).obj U.unop) := rfl /-- Given two locally ringed spaces `X` and `Y`, an isomorphism between `X` and `Y` as _sheafed_ spaces can be lifted to a morphism `X ⟶ Y` as locally ringed spaces. See also `iso_of_SheafedSpace_iso`. -/ @[simps] def hom_of_SheafedSpace_hom_of_is_iso {X Y : LocallyRingedSpace} (f : X.to_SheafedSpace ⟶ Y.to_SheafedSpace) [is_iso f] : X ⟶ Y := hom.mk f $ λ x, -- Here we need to see that the stalk maps are really local ring homomorphisms. -- This can be solved by type class inference, because stalk maps of isomorphisms are isomorphisms -- and isomorphisms are local ring homomorphisms. show is_local_ring_hom (PresheafedSpace.stalk_map (SheafedSpace.forget_to_PresheafedSpace.map f) x), by apply_instance /-- Given two locally ringed spaces `X` and `Y`, an isomorphism between `X` and `Y` as _sheafed_ spaces can be lifted to an isomorphism `X ⟶ Y` as locally ringed spaces. This is related to the property that the functor `forget_to_SheafedSpace` reflects isomorphisms. In fact, it is slightly stronger as we do not require `f` to come from a morphism between _locally_ ringed spaces. -/ def iso_of_SheafedSpace_iso {X Y : LocallyRingedSpace} (f : X.to_SheafedSpace ≅ Y.to_SheafedSpace) : X ≅ Y := { hom := hom_of_SheafedSpace_hom_of_is_iso f.hom, inv := hom_of_SheafedSpace_hom_of_is_iso f.inv, hom_inv_id' := hom.ext _ _ f.hom_inv_id, inv_hom_id' := hom.ext _ _ f.inv_hom_id } instance : reflects_isomorphisms forget_to_SheafedSpace := { reflects := λ X Y f i, { out := by exactI ⟨hom_of_SheafedSpace_hom_of_is_iso (category_theory.inv (forget_to_SheafedSpace.map f)), hom.ext _ _ (is_iso.hom_inv_id _), hom.ext _ _ (is_iso.inv_hom_id _)⟩ } } instance is_SheafedSpace_iso {X Y : LocallyRingedSpace} (f : X ⟶ Y) [is_iso f] : is_iso f.1 := LocallyRingedSpace.forget_to_SheafedSpace.map_is_iso f /-- The restriction of a locally ringed space along an open embedding. -/ @[simps] def restrict {U : Top} (X : LocallyRingedSpace) {f : U ⟶ X.to_Top} (h : open_embedding f) : LocallyRingedSpace := { local_ring := begin intro x, dsimp at *, -- We show that the stalk of the restriction is isomorphic to the original stalk, apply @ring_equiv.local_ring _ _ _ (X.local_ring (f x)), exact (X.to_PresheafedSpace.restrict_stalk_iso h x).symm.CommRing_iso_to_ring_equiv, end, to_SheafedSpace := X.to_SheafedSpace.restrict h } /-- The canonical map from the restriction to the supspace. -/ def of_restrict {U : Top} (X : LocallyRingedSpace) {f : U ⟶ X.to_Top} (h : open_embedding f) : X.restrict h ⟶ X := ⟨X.to_PresheafedSpace.of_restrict h, λ x, infer_instance⟩ /-- The restriction of a locally ringed space `X` to the top subspace is isomorphic to `X` itself. -/ def restrict_top_iso (X : LocallyRingedSpace) : X.restrict (opens.open_embedding ⊤) ≅ X := @iso_of_SheafedSpace_iso (X.restrict (opens.open_embedding ⊤)) X X.to_SheafedSpace.restrict_top_iso /-- The global sections, notated Gamma. -/ def Γ : LocallyRingedSpaceᵒᵖ ⥤ CommRing := forget_to_SheafedSpace.op ⋙ SheafedSpace.Γ lemma Γ_def : Γ = forget_to_SheafedSpace.op ⋙ SheafedSpace.Γ := rfl @[simp] lemma Γ_obj (X : LocallyRingedSpaceᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl lemma Γ_obj_op (X : LocallyRingedSpace) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl @[simp] lemma Γ_map {X Y : LocallyRingedSpaceᵒᵖ} (f : X ⟶ Y) : Γ.map f = f.unop.1.c.app (op ⊤) := rfl lemma Γ_map_op {X Y : LocallyRingedSpace} (f : X ⟶ Y) : Γ.map f.op = f.1.c.app (op ⊤) := rfl lemma preimage_basic_open {X Y : LocallyRingedSpace} (f : X ⟶ Y) {U : opens Y} (s : Y.presheaf.obj (op U)) : (opens.map f.1.base).obj (Y.to_RingedSpace.basic_open s) = @RingedSpace.basic_open X.to_RingedSpace ((opens.map f.1.base).obj U) (f.1.c.app _ s) := begin ext, split, { rintros ⟨⟨y, hyU⟩, (hy : is_unit _), (rfl : y = _)⟩, erw RingedSpace.mem_basic_open _ _ ⟨x, show x ∈ (opens.map f.1.base).obj U, from hyU⟩, rw ← PresheafedSpace.stalk_map_germ_apply, exact (PresheafedSpace.stalk_map f.1 _).is_unit_map hy }, { rintros ⟨y, (hy : is_unit _), rfl⟩, erw RingedSpace.mem_basic_open _ _ ⟨f.1.base y.1, y.2⟩, rw ← PresheafedSpace.stalk_map_germ_apply at hy, exact (is_unit_map_iff (PresheafedSpace.stalk_map f.1 _) _).mp hy } end -- This actually holds for all ringed spaces with nontrivial stalks. @[simp] lemma basic_open_zero (X : LocallyRingedSpace) (U : opens X.carrier) : X.to_RingedSpace.basic_open (0 : X.presheaf.obj $ op U) = ⊥ := begin ext, simp only [set.mem_empty_iff_false, topological_space.opens.mem_coe, opens.coe_bot, iff_false, RingedSpace.basic_open, is_unit_zero_iff, set.mem_set_of_eq, map_zero], rintro ⟨⟨y, _⟩, h, e⟩, exact zero_ne_one' (X.presheaf.stalk y) h, end instance component_nontrivial (X : LocallyRingedSpace) (U : opens X.carrier) [hU : nonempty U] : nontrivial (X.presheaf.obj $ op U) := (X.to_PresheafedSpace.presheaf.germ hU.some).domain_nontrivial end LocallyRingedSpace end algebraic_geometry
a8a2cc2314df947f934a523a95e06899a5654389
75c54c8946bb4203e0aaf196f918424a17b0de99
/src/henkin.lean
8b5651f71ac3f3e04d0cfeb60cee5fce4a22f77e
[ "Apache-2.0" ]
permissive
urkud/flypitch
261e2a45f1038130178575406df8aea78255ba77
2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c
refs/heads/master
1,653,266,469,246
1,577,819,679,000
1,577,819,679,000
259,862,235
1
0
Apache-2.0
1,588,147,244,000
1,588,147,244,000
null
UTF-8
Lean
false
false
52,033
lean
/- Copyright (c) 2019 The Flypitch Project. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jesse Han, Floris van Doorn -/ import .completion .language_extension .colimit -- local attribute [instance, priority 0] classical.prop_decidable open fol universes u v local infix ` →ᴸ `:10 := Lhom -- \^L /- Temporarily putting this here because I can't get Lean to recognize Lhom in colimit.lean -/ namespace colimit export directed_type /- Below we define colimits of languages. These are just fieldwise (and then indexwise) colimits of types, so the proofs are very similar. -/ local infix ` ∘ `:60 := Lhom.comp structure directed_diagram_language (D : (directed_type.{u})) : Type (max (u+1) (v+1)) := (obj : D.carrier → (Language.{v})) (mor : ∀{x}, ∀{y}, D.rel x y → (obj x →ᴸ obj y)) (h_mor : ∀{x} {y} {z} {f1 : D.rel x y} {f2 : D.rel y z} {f3 : D.rel x z}, (mor f3) = (mor f2) ∘ (mor f1)) -- functoriality export directed_diagram_language /- Given a directed diagram of languages, we obtain two ℕ-indexed families of directed diagrams of types: one by restricting to functions and one by restricting to relations. -/ @[reducible]def diagram_functions {D : (directed_type)} {F : (directed_diagram_language D)} (n : ℕ) : ((directed_diagram D)) := begin refine ⟨by {intro x, exact (obj F x).functions n},_,_⟩, {intros x y edge, have := (F.mor edge).on_function, exact this }, {intros, simp only [], have := F.h_mor, have := @this x y z f1 f2 f3, rw[this]}, end @[reducible]def diagram_relations {D : (directed_type)} {F : (directed_diagram_language D)} (n : ℕ) : ((directed_diagram D)) := begin refine ⟨by {intro x, exact (obj F x).relations n},_,_⟩, {intros x y edge, have := (F.mor edge).on_relation, exact @this n}, {intros, simp only [], have := F.h_mor, have := @this x y z f1 f2 f3, rw[this]}, end def coproduct_of_directed_diagram_language {D : (directed_type : Type (u+1)) } (F : (directed_diagram_language D : Type (max (u+1) (v+1)))) : Language := ⟨λn, coproduct_of_directed_diagram (@diagram_functions D F n), λn, coproduct_of_directed_diagram (@diagram_relations D F n)⟩ def colimit_language {D : (directed_type : Type (u+1)) } (F : (directed_diagram_language D)) : Language := ⟨λn, @quotient (coproduct_of_directed_diagram (@diagram_functions D F n)) ⟨germ_relation (diagram_functions n), germ_equivalence (diagram_functions n)⟩, λn, @quotient (coproduct_of_directed_diagram (@diagram_relations D F n)) ⟨germ_relation (diagram_relations n), germ_equivalence (diagram_relations n)⟩⟩ /- The canonical map of languages is the pointwise canonical map of colimits of types -/ def canonical_map_language {D} {F : directed_diagram_language D} (i : D.carrier) : (F.obj i) →ᴸ colimit_language F := ⟨λ n, function.comp (by apply quotient.mk) (@canonical_inclusion_coproduct D (diagram_functions n) i), λ n, function.comp (by apply quotient.mk) (@canonical_inclusion_coproduct D (diagram_relations n) i)⟩ -- structure cocone_language' {D} (F : directed_diagram_language D) := -- (vertex : Language) -- (cocone_functions : ∀{n}, @colimit.cocone D (@diagram_functions D F n) -- would need extra hypotheses that for every n, the vertex of the cocone_functions (resp. relations) -- is equal to vertex.functions (resp. relations) -- maybe that would have been easier to work with structure cocone_language {D} (F : directed_diagram_language D) := (vertex : Language) (map : Π i : D.carrier, F.obj i →ᴸ vertex) (h_compat : ∀{i}, ∀{j}, Π h : D.rel i j, (map i ) = (map j) ∘ (F.mor h)) export cocone_language def cocone_of_colimit_language {D} (F : directed_diagram_language D) : cocone_language F := begin refine ⟨colimit_language F, canonical_map_language, _⟩, intros i j H, fapply Lhom.Lhom_funext, all_goals{fapply funext, intro n, simp only [quotient.eq,(≈),canonical_map_language,function.comp], have h_refl : D.rel j j, by apply D.h_reflexive, -- refine ⟨j,F.mor H x, H, h_refl, rfl, _⟩, fapply funext, intro x, simp only [quotient.eq,(≈),canonical_map_language,function.comp], }, {refine ⟨j,(F.mor H).on_function x, H, h_refl, rfl, _⟩, change (function.comp ((diagram_functions n).mor h_refl) begin fapply Lhom.on_function, exact @mor D F i j H, end) x = (F.mor H).on_function x, have := Lhom.comp_on_function' (F.mor h_refl) (F.mor H) n, rw[<-this,<-F.h_mor]}, { refine ⟨j,(F.mor H).on_relation x, H, h_refl, rfl, _⟩, change (function.comp ((diagram_relations n).mor h_refl) begin fapply Lhom.on_relation, exact @mor D F i j H, end) x = (F.mor H).on_relation x, have := Lhom.comp_on_relation' (F.mor h_refl) (F.mor H) n, rw[<-this,<-F.h_mor]} end /- Given a cocone V over a diagram D, return the canonical map colim D → V-/ def universal_map_language {D} {F : directed_diagram_language D} {V : cocone_language F} : colimit_language F →ᴸ (V.vertex) := begin split, all_goals{intro n, fapply quotient.lift}, {exact λp, begin fapply @Lhom.on_function, exact F.obj p.fst, exact @map D F V p.fst, exact p.snd end}, {intros p q H, rcases p with ⟨i,x⟩, rcases q with ⟨j,y⟩, simp only *, simp[(≈), germ_relation] at H, rcases H with ⟨k,z,⟨f1, H1⟩,f2,H2⟩, change (V.map i).on_function x = (V.map j).on_function y, have : (V.map i).on_function x = (V.map k).on_function ((F.mor f1).on_function x), simp only [V.h_compat f1, eq_self_iff_true, function.comp_app], have : (V.map j).on_function y = (V.map k).on_function ((F.mor f2).on_function y), simp only [V.h_compat f2, eq_self_iff_true, function.comp_app], simp only [*, eq_self_iff_true]}, {exact λp, begin fapply @Lhom.on_relation, exact F.obj p.fst, exact @map D F V p.fst, exact p.snd end}, {intros p q H, rcases p with ⟨i,x⟩, rcases q with ⟨j,y⟩, simp only *, simp[(≈), germ_relation] at H, rcases H with ⟨k,z,⟨f1, H1⟩,f2,H2⟩, change (V.map i).on_relation x = (V.map j).on_relation y, have : (V.map i).on_relation x = (V.map k).on_relation ((F.mor f1).on_relation x), simp only [V.h_compat f1, eq_self_iff_true, function.comp_app], have : (V.map j).on_relation y = (V.map k).on_relation ((F.mor f2).on_relation y), simp only [V.h_compat f2, eq_self_iff_true, function.comp_app], simp only [*, eq_self_iff_true]}, end namespace omega_colimit_language /- Facts about directed colimits indexed by ℕ'. -/ def diagram.mk.map {F : ℕ → Language} {h_succ : ∀{i : ℕ}, F i →ᴸ F (i+1)} : Π (x y : ℕ), x ≤ y → (F x →ᴸ F y) | x 0 h := by {rw[nat.eq_zero_of_le_zero h], exact ⟨λn, id, λn, id⟩} | x (y+1) h := by {by_cases x = y + 1, rw[h], exact ⟨λn, id, λn, id⟩, refine h_succ ∘ _, apply diagram.mk.map, apply nat.le_of_le_and_ne_succ, repeat{assumption}} --TODO(jesse) finish converting this to language versions and refactor henkin_language_chain -- @[simp]lemma diagram.mk.map_self_id {F : ℕ → Type*} {h_succ : ∀(i : ℕ), F i → F (i+1)} (x : ℕ) : -- @diagram.mk.map F @h_succ x x (by constructor) = id := -- by {induction x, tidy, simp[diagram.mk.map,*], refl} -- /- If the successive maps of h_succ are injective, then all their compositions are injective -/ -- lemma diagram.mk.map_inj {F : ℕ → Type*} {h_succ : ∀(i : ℕ), F i → F (i+1)} {h_inj : ∀ {i : ℕ}, function.injective (@h_succ i )} (x y : ℕ) (h : x ≤ y) : function.injective (@diagram.mk.map F h_succ x y h) := -- begin -- induction y, -- {have : x = 0, by exact nat.eq_zero_of_le_zero h, dsimp[*,diagram.mk.map], finish}, -- by_cases x = y_n + 1, -- {dsimp[*, diagram.mk.map], finish}, -- have : x ≤ y_n, by {apply nat.le_of_le_and_ne_succ, repeat{assumption}}, -- simp[*, diagram.mk.map], apply function.injective_comp, apply h_inj, apply y_ih -- end -- -- /- Given a ℕ-indexed family of types and a way of assigning maps between successive objects -- -- in this family, return the induced directed_diagram over ℕ'. -/ -- def diagram.mk(F : ℕ → Type*) (h_succ :∀{i : ℕ}, F i → F (i+1)) : directed_diagram ℕ' := -- begin -- refine ⟨F, by {apply diagram.mk.map, assumption}, _⟩, -- intros x y z H1 H2 H3, -- induction z, induction y, induction x, -- dsimp[diagram.mk.map], refl, -- by {exfalso, fapply nat.succ_ne_zero, exact x_n, apply (nat.le_zero_iff).mp, assumption}, -- by {exfalso, fapply nat.succ_ne_zero, exact y_n, apply (nat.le_zero_iff).mp, assumption}, -- by_cases y = z_n+1, subst h; -- by_cases x = z_n+1; -- {repeat{dsimp[diagram.mk.map], simp*, refl}}, -- by_cases x = z_n+1, -- {exfalso, have : y < z_n+1, by {fapply nat.lt_of_le_and_ne, -- repeat{assumption}}, dsimp at *, linarith}, -- {have h_x : x ≤ z_n; have h_y : y ≤ z_n, -- all_goals{try{apply nat.le_of_le_and_ne_succ, repeat{assumption}}}, -- have := @z_ih h_y h_x, -- dsimp[diagram.mk.map], dedup, -- simp only [h, h_1, dif_neg, not_false_iff, colimit.nat.le_of_le_and_ne_succ], -- rw[this]} -- end end omega_colimit_language end colimit open colimit open omega_colimit /- The Henkin construction consists of the following: 1. Constructing a ℕ-indexed chain of languages and theories, and 2. Taking the union of that chain. -/ /- To define henkin_language_step, there is an inductive type of new function function symbols, comprising an inclusion constructor for the symbols from L, and a witness constructor which introduces witnesses for every bounded_formula 1-/ inductive henkin_language_functions (L : Language.{u}) : ℕ → Type u | inc : ∀ {n}, L.functions n → henkin_language_functions n | wit : bounded_formula L 1 → henkin_language_functions 0 open henkin_language_functions /- The basic step of the Henkin construction on languages. Given a language L, return a language L' with constants witnessing all bounded_formula 1-/ @[reducible]def henkin_language_step (L : Language.{u}) : Language.{u} := ⟨henkin_language_functions L, L.relations⟩ def wit' {L : Language} : bounded_formula L 1 → (henkin_language_step L).constants := wit def henkin_language_inclusion {L : Language} : L →ᴸ henkin_language_step L := ⟨λ n f, inc f, λn, id⟩ lemma henkin_language_inclusion_inj {L : Language} : Lhom.is_injective (@henkin_language_inclusion L) := begin split, all_goals{intro n, intros x y H, try{exact H}}, fapply @henkin_language_functions.inc.inj_arrow, exact L, exact n, exact x, exact y, exact H, simp only [imp_self] end /- The basic step of the Henkin construction on theories. Given an L-theory T, return an L'-theory T' which is T expanded by sentences saying that the new witnesses are witnesses. -/ @[reducible]def wit_property {L : Language} (f : bounded_formula L 1) (c : L.constants) : sentence L := (∃'f) ⟹ f[bd_const c/0] open fol.Lhom def henkin_theory_step {L} (T : Theory L) : Theory $ henkin_language_step L := Theory_induced henkin_language_inclusion T ∪ (λ f : bounded_formula L 1, wit_property (henkin_language_inclusion.on_bounded_formula f) (wit' f)) '' (set.univ : set $ bounded_formula L 1) def is_consistent_henkin_theory_step {L} {T : Theory L} (hT : is_consistent T) : is_consistent (henkin_theory_step T) := begin refine eq.mp _ (is_consistent_extend hT henkin_language_inclusion_inj (λf, (∃' f).cast1 ⟹ f) _ wit _ _), { congr1, congr1, apply set.image_congr', intro f, ext, simp [wit_property, wit', -fst_ex], rw [←on_bounded_formula_fst, subst_sentence_irrel], refl }, { intro f, apply falsumE, apply impE (∃' f.fst), { apply impI, apply impE _ axm2, apply exE axm1, apply exI &0, rw [lift_subst_formula_cancel], apply impI axm2 }, { apply falsumE, apply impE _ axm2, apply exI &0, apply impI, apply exfalso, apply impE _ axm2, rw [bounded_preformula.cast1_fst, subst_sentence_irrel], exact axm1 }}, { intros f f' h, cases h, refl }, { intro f, intro h, rcases h with ⟨f', hf'⟩, cases hf' } end @[reducible]def henkin_language_chain_objects {L : Language} : ℕ → Language | 0 := L | (n+1) := henkin_language_step (henkin_language_chain_objects n) @[simp]lemma obvious {L : Language} {i : ℕ} : henkin_language_functions (@henkin_language_chain_objects L i) 0 = (@henkin_language_chain_objects L (i+1)).constants := by refl local infix ` ∘ `:60 := Lhom.comp def henkin_language_chain_maps (L : Language): Π x y, x ≤ y → (@henkin_language_chain_objects L x →ᴸ @henkin_language_chain_objects L y) | x 0 H := by {have : x = 0, by exact nat.eq_zero_of_le_zero H, rw[this], apply Lhom.id} | x (y+1) H := by {by_cases x = y + 1, rw[h], fapply Lhom.id, refine @henkin_language_inclusion (@henkin_language_chain_objects L y) ∘ _, fapply henkin_language_chain_maps, fapply nat.le_of_le_and_ne_succ, exacts [H, h]} lemma henkin_language_chain_maps_inj (L : Language) : Π x y : ℕ, Π (h : x ≤ y), Lhom.is_injective (henkin_language_chain_maps L x y h) := begin intros i j h, split, swap, {induction j, {have : i = 0, by exact nat.eq_zero_of_le_zero h, subst this, intros n x y H, exact H}, {by_cases i = (j_n + 1), dedup, {subst h_1, rw[henkin_language_chain_maps], simp*, intros n x y H, exact H}, {have : i ≤ j_n, by {apply nat.le_of_le_and_ne_succ, repeat{assumption}}, have ih := j_ih this, show ℕ, exact i, rw[henkin_language_chain_maps], simp only [*, dif_neg, not_false_iff], intro n, fapply function.injective_comp, fapply henkin_language_inclusion_inj.on_relation, change function.injective (Lhom.on_relation (henkin_language_chain_maps L i j_n this)), simp only *,}} }, {induction j, {have : i = 0, by exact nat.eq_zero_of_le_zero h, subst this, intros n x y H, exact H}, {by_cases i = (j_n + 1), dedup, {subst h_1, rw[henkin_language_chain_maps], simp*, intros n x y H, exact H}, {have : i ≤ j_n, by {apply nat.le_of_le_and_ne_succ, repeat{assumption}}, have ih := j_ih this, show ℕ, exact i, rw[henkin_language_chain_maps], simp only [*, dif_neg, not_false_iff], intro n, fapply function.injective_comp, fapply henkin_language_inclusion_inj.on_function, change function.injective (Lhom.on_function (henkin_language_chain_maps L i j_n this)), simp only *,}}}, end /- Given a language, iterate henkin_language_step, returning this data in the form of a directed diagram of types indexed by ℕ' -/ def henkin_language_chain {L : Language} : (directed_diagram_language directed_type_of_nat) := begin refine ⟨_, _, _⟩, {exact @henkin_language_chain_objects L}, {change Π {x y : ℕ}, x ≤ y → (henkin_language_chain_objects x →ᴸ henkin_language_chain_objects y), intros x y H, fapply henkin_language_chain_maps, exact H}, {change ∀ {x y z : ℕ} {f1 : x ≤ y} {f2 : y ≤ z} {f3 : x ≤ z}, henkin_language_chain_maps L x z _ = henkin_language_chain_maps L y z _ ∘ henkin_language_chain_maps L x y _, intros x y z f1 f2 f3, induction z, {have this1 : x = 0, by exact nat.eq_zero_of_le_zero f3, have this2 : y = 0, by exact nat.eq_zero_of_le_zero f2, subst this1, subst this2, refl}, { unfold henkin_language_chain_maps, by_cases y = z_n + 1, simp*, subst h, by_cases x = z_n+1, simp*, subst h, unfold henkin_language_chain_maps, simp, refl, {simp*, have : eq.mpr _ (Lhom.id (henkin_language_chain_objects (z_n + 1))) ∘ henkin_language_chain_maps L x (z_n + 1) f1 = (Lhom.id (henkin_language_chain_objects (z_n + 1))) ∘ henkin_language_chain_maps L x (z_n + 1) f1, by refl, rw[this], have : Lhom.id (henkin_language_chain_objects (z_n + 1)) ∘ henkin_language_chain_maps L x (z_n + 1) f1 = henkin_language_chain_maps L x (z_n + 1) f1, by simp only [eq_self_iff_true, fol.Lhom.id_is_left_identity], rw[this], unfold henkin_language_chain_maps, simp*, }, {by_cases x = z_n+1, {simp*, have : y < z_n+1, by {fapply nat.lt_of_le_and_ne, repeat{assumption}}, exfalso, linarith}, {simp*} } } } end @[simp]lemma id_of_self_map (L : Language) : ∀ k, (henkin_language_chain_maps L k k (le_refl k)) = Lhom.id ((@henkin_language_chain L).obj k) | 0 := by refl | (n+1) := by {dsimp[henkin_language_chain_maps], simp*, refl} @[simp]lemma henkin_language_inclusion_chain_map {i} {L : Language} : henkin_language_inclusion = henkin_language_chain_maps L i (i + 1) (by simp[nat.le_succ]) := begin unfold henkin_language_chain_maps, have : i ≠ i + 1, by {induction i, tidy}, simp[this], rw[@Lhom.id_is_right_identity ((@henkin_language_chain L).obj i)] end def L_infty (L) : Language := colimit_language $ @henkin_language_chain L /-- For every n : ℕ, return the canonical inclusion L_n → L_infty --/ def henkin_language_canonical_map {L : Language} (m : ℕ) : (@henkin_language_chain L).obj m →ᴸ (@L_infty L) := by apply canonical_map_language @[simp]lemma henkin_language_canonical_map_inj {L : Language} (m : ℕ) : Lhom.is_injective $ @henkin_language_canonical_map L m := begin split, {intro n, unfold henkin_language_canonical_map canonical_map_language Lhom.on_function, have := @canonical_map_inj_of_transition_maps_inj directed_type_of_nat (@diagram_functions directed_type_of_nat (@henkin_language_chain L) n), unfold canonical_map at this, apply this,intros i j H, dsimp[diagram_functions, henkin_language_chain], fapply ((henkin_language_chain_maps_inj) L i j H).on_function}, {intro n, unfold henkin_language_canonical_map canonical_map_language Lhom.on_relation, have := @canonical_map_inj_of_transition_maps_inj directed_type_of_nat (@diagram_relations directed_type_of_nat (@henkin_language_chain L) n), unfold canonical_map at this, apply this,intros i j H, dsimp[diagram_relations, henkin_language_chain], fapply ((henkin_language_chain_maps_inj) L i j H).on_relation} end /- To prove that T_infty is Henkin, we'll have to exhibit a witnessing function of the form wit : bounded_formula 1 → L_infty.constants. To do this, we have to recursively go through formulas and terms and show that for every formula, there exists some N such that all the symbols in that formula were contained in L_N, and therefore, the wit function for L_N introduces the constant we want. The natural way to proceed is to define the induced colimit on bounded_formulas, etc. Then, we can define the required wit function by taking a bounded formula, picking a representative from stage N, applying the wit function from stage N to get something in stage N+1, and then pushing it up to L_infty. -/ /- In what follows, "l" is always pre(whatever) level, "k" is always chain index, and "n" is always the bound in bounded_(whatever)-/ def henkin_term_chain {L : Language} (l : ℕ) : directed_diagram ℕ' := begin refine ⟨λ k, preterm (@henkin_language_chain_objects L k) l, _, _⟩, {intros x y H, apply Lhom.on_term, apply @henkin_language_chain_maps L, exact H}, {intros x y z f1 f2 f3, dsimp only [*], have : (henkin_language_chain_maps L x z f3) = (henkin_language_chain_maps L y z f2) ∘ (henkin_language_chain_maps L x y f1), fapply henkin_language_chain.h_mor, simp*} end def henkin_formula_chain {L : Language} (l : ℕ) : directed_diagram ℕ' := begin refine ⟨λ k, preformula (@henkin_language_chain_objects L k) l, _, _⟩, {intros x y H, apply Lhom.on_formula, apply @henkin_language_chain_maps L, exact H}, {intros x y z f1 f2 f3, dsimp only [*], have : (henkin_language_chain_maps L x z f3) = (henkin_language_chain_maps L y z f2) ∘ (henkin_language_chain_maps L x y f1), fapply henkin_language_chain.h_mor, simp*} end def henkin_bounded_term_chain {L : Language} (n l : ℕ) : directed_diagram ℕ' := begin refine ⟨λ k, bounded_preterm (@henkin_language_chain_objects L k) n l, _, _⟩, {intros x y H, apply Lhom.on_bounded_term, apply @henkin_language_chain_maps L, exact H}, {intros x y z f1 f2 f3, dsimp only [*], have : (henkin_language_chain_maps L x z f3) = (henkin_language_chain_maps L y z f2) ∘ (henkin_language_chain_maps L x y f1), fapply henkin_language_chain.h_mor, rw[this, Lhom.comp_on_bounded_term]} end @[reducible] def henkin_bounded_term_chain' {L : Language} : directed_diagram ℕ' := @henkin_bounded_term_chain L 1 0 def henkin_bounded_formula_chain {L : Language} (n l : ℕ) : directed_diagram ℕ' := begin refine ⟨λ k, bounded_preformula (@henkin_language_chain_objects L k) n l, _, _⟩, {intros x y H, apply Lhom.on_bounded_formula, apply @henkin_language_chain_maps L, exact H}, {intros x y z f1 f2 f3, dsimp only [*], have : (henkin_language_chain_maps L x z f3) = (henkin_language_chain_maps L y z f2) ∘ (henkin_language_chain_maps L x y f1), fapply henkin_language_chain.h_mor, rw[this, Lhom.comp_on_bounded_formula]} end @[reducible]def henkin_bounded_formula_chain' {L : Language} : directed_diagram ℕ' := @henkin_bounded_formula_chain L 1 0 /- L_infty := colim L_n is naturally a cocone over the diagram of languages -/ def cocone_of_L_infty {L : Language} : cocone_language (@henkin_language_chain L) := by apply cocone_of_colimit_language def cocone_of_term_L_infty {L : Language } (l : ℕ) : cocone (@henkin_term_chain L l) := begin refine ⟨preterm (L_infty L) l,_,_⟩, {intro i, fapply Lhom.on_term, fapply henkin_language_canonical_map}, {intros i j H, dsimp[henkin_term_chain], rw[<-Lhom.comp_on_term], have : henkin_language_canonical_map i = (henkin_language_canonical_map j ∘ henkin_language_chain_maps L i j H), swap, rw[this], {have := (@cocone_of_L_infty L).h_compat, tidy}} end def cocone_of_formula_L_infty {L : Language } (l : ℕ) : cocone (@henkin_formula_chain L l) := begin refine ⟨preformula (L_infty L) l,_,_⟩, {intro i, fapply Lhom.on_formula, fapply henkin_language_canonical_map}, {intros i j H, dsimp[henkin_formula_chain], rw[<-Lhom.comp_on_formula], have : henkin_language_canonical_map i = (henkin_language_canonical_map j ∘ henkin_language_chain_maps L i j H), swap, rw[this], {have := (@cocone_of_L_infty L).h_compat, tidy}} end def cocone_of_bounded_term_L_infty {L : Language } (n l : ℕ) : cocone (@henkin_bounded_term_chain L n l) := begin refine ⟨bounded_preterm (L_infty L) n l,_,_⟩, {intro i, fapply Lhom.on_bounded_term, fapply henkin_language_canonical_map}, {intros i j H, dsimp[henkin_bounded_term_chain], rw[<-Lhom.comp_on_bounded_term], have : henkin_language_canonical_map i = (henkin_language_canonical_map j ∘ henkin_language_chain_maps L i j H), swap, rw[this], {have := (@cocone_of_L_infty L).h_compat, tidy}} end def cocone_of_bounded_formula_L_infty {L : Language } (n l : ℕ) : cocone (@henkin_bounded_formula_chain L n l) := begin refine ⟨bounded_preformula (L_infty L) n l,_,_⟩, {intro i, fapply Lhom.on_bounded_formula, fapply henkin_language_canonical_map}, {intros i j H, dsimp[henkin_bounded_formula_chain], rw[<-Lhom.comp_on_bounded_formula], have : henkin_language_canonical_map i = (henkin_language_canonical_map j ∘ henkin_language_chain_maps L i j H), swap, rw[this], {have := (@cocone_of_L_infty L).h_compat, tidy}} end /- bounded_formula (L_infty L) 1 is naturally a cocone over the diagram of bounded_formulas -/ def cocone_of_bounded_formula'_L_infty {L : Language} : cocone (@henkin_bounded_formula_chain' L) := begin refine ⟨bounded_formula (L_infty L) 1,_,_⟩, {intro i, fapply Lhom.on_bounded_formula, fapply henkin_language_canonical_map}, {intros i j H, dsimp[henkin_bounded_formula_chain', henkin_bounded_formula_chain], rw[<-Lhom.comp_on_bounded_formula], have : henkin_language_canonical_map i = (henkin_language_canonical_map j ∘ henkin_language_chain_maps L i j H), swap, rw[this], {have := (@cocone_of_L_infty L).h_compat, tidy}} end def term_comparison {L : Language} (l) : colimit (@henkin_term_chain L l) → preterm (L_infty L) l := begin change colimit (@henkin_term_chain L l) → (@cocone_of_term_L_infty L l).vertex, apply colimit.universal_map end def formula_comparison {L : Language} (l) : colimit (@henkin_formula_chain L l) → preformula (L_infty L) l := begin change colimit (@henkin_formula_chain L l) → (@cocone_of_formula_L_infty L l).vertex, apply colimit.universal_map end def bounded_term_comparison {L : Language} (n l) : colimit (@henkin_bounded_term_chain L n l) → bounded_preterm (L_infty L) n l := begin change colimit (@henkin_bounded_term_chain L n l) → (@cocone_of_bounded_term_L_infty L n l).vertex, apply colimit.universal_map end @[reducible]def bounded_term'_comparison {L : Language} : colimit (@henkin_bounded_term_chain' L) → bounded_term (L_infty L) 1 := @bounded_term_comparison L 1 0 def bounded_formula_comparison {L : Language} (n l) : colimit (@henkin_bounded_formula_chain L n l) → bounded_preformula (L_infty L) n l := begin change colimit (@henkin_bounded_formula_chain L n l) → (@cocone_of_bounded_formula_L_infty L n l).vertex, apply colimit.universal_map end @[reducible]def bounded_formula'_comparison {L : Language} : colimit (@henkin_bounded_formula_chain' L) → bounded_formula (L_infty L) 1 := @bounded_formula_comparison L 1 0 -- to proceed, need to show that bounded_formula_comparison, as we've defined it, -- commutes with operations on bounded formulas -- so we need to generalize from -- bounded_formula 1 to bounded_formula n, and prove colimit statements for terms, etc -- to complete the structural recursion /- The universal map from colimit preterm L_n → preterm L_infty is a bijection -/ -- TODO(jesse) refactor with new colimit lemmas lemma term_comparison_bijective {L : Language} (l) : function.bijective (@term_comparison L l) := begin refine ⟨_,_⟩, {{unfold term_comparison id, fapply universal_map_inj_of_components_inj, change ∀ i : ℕ, function.injective ((cocone_of_term_L_infty l).map i), dsimp[cocone_of_term_L_infty], intro m, fapply Lhom.on_term_inj (@henkin_language_canonical_map_inj L m)},}, {intro f, induction f, {refine ⟨(by {fapply canonical_map, by {change ℕ, exact 0}, exact var f}), by split⟩}, {have W := germ_rep f_f, rcases W with ⟨⟨i,x⟩, Hx⟩, fapply exists.intro, fapply canonical_map i, fapply func, exact x, rw[<-Hx], refl}, {rcases f_ih_t with ⟨t, Ht⟩, rcases f_ih_s with ⟨s,Hs⟩, have Wt := germ_rep t, have Ws := germ_rep s, rcases Wt with ⟨⟨i,x_t⟩, Hxt⟩, rcases Ws with ⟨⟨j, x_s⟩, Hxs⟩, let x_t' : (henkin_term_chain (f_l + 1)).obj (i+j), fapply (henkin_term_chain (f_l + 1)).mor, exact i, simp only [ℕ', directed_type.rel, id.def, zero_le, le_add_iff_nonneg_right], exact x_t, let x_s' : (henkin_term_chain 0).obj (i+j), fapply (henkin_term_chain 0).mor, exact j, simp only [ℕ', directed_type.rel, zero_le, le_add_iff_nonneg_left], exact x_s, have Hxt' : ⟦(⟨i+j,x_t'⟩ : coproduct_of_directed_diagram $ henkin_term_chain (f_l + 1))⟧ = t, {rw[<-Hxt], simp[(≈), germ_relation], refine ⟨(i+j),x_t',⟨by simp,_⟩,_⟩, dsimp[henkin_term_chain, henkin_language_chain_maps], let k := i + j, simp only [id_of_self_map], apply Lhom.id_term, fapply exists.intro, simp only [zero_le, le_add_iff_nonneg_right]}, have Hxs' : ⟦(⟨i+j,x_s'⟩ : coproduct_of_directed_diagram $ henkin_term_chain 0)⟧ = s, {{rw[<-Hxs], simp[(≈), germ_relation], refine ⟨(i+j),x_s',⟨by simp,_⟩,_⟩, dsimp[henkin_term_chain, henkin_language_chain_maps], let k := i + j, simp only [id_of_self_map], apply Lhom.id_term, fapply exists.intro, simp only [zero_le, le_add_iff_nonneg_left]},}, fapply exists.intro, fapply canonical_map, change ℕ, exact (i + j), fapply app, exact x_t', exact x_s', rw[<-Ht, <-Hs, <-Hxt', <-Hxs'], refl},} end /- At some point, I should write out explicitly the fact that all the comparison maps structurally recurse -/ lemma formula_comparison_bijective {L : Language} (l) : function.bijective (@formula_comparison L l) := begin refine ⟨_,_⟩, {{unfold formula_comparison id, fapply universal_map_inj_of_components_inj, change ∀ i : ℕ, function.injective ((cocone_of_formula_L_infty l).map i), dsimp[cocone_of_formula_L_infty], intro m, fapply Lhom.on_formula_inj (@henkin_language_canonical_map_inj L m)},}, {intro f, induction f, {refine ⟨(by {fapply canonical_map, by {change ℕ, exact 0}, exact falsum}), by split⟩}, { rcases (term_comparison_bijective 0).right f_t₁ with ⟨t₁, H₁⟩, rcases (term_comparison_bijective 0).right f_t₂ with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact i+j, fapply equal, exact push_to_sum_r x j, exact push_to_sum_l y i, rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {have x := germ_rep f_R, rcases x with ⟨⟨i,x⟩,H⟩, fapply exists.intro, have R' := rel x, exact ⟦⟨i,R'⟩⟧, tidy}, {rcases f_ih with ⟨t₁, H₁⟩, rcases (term_comparison_bijective 0).right f_t with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact i+j, fapply apprel, exact push_to_sum_r x j, exact push_to_sum_l y i, rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {rcases f_ih_f₁ with ⟨t₁, H₁⟩, rcases f_ih_f₂ with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact (i+j), fapply imp, exact push_to_sum_r x j, exact push_to_sum_l y i, rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {rcases f_ih with ⟨t₁, H₁⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, fapply exists.intro, fapply canonical_map, exact i, fapply all, exact x, rw[<-H₁, <-Hx], simpa only}} end @[simp]lemma bounded_term_comparison_bijective {L : Language} (n l) : function.bijective (@bounded_term_comparison L n l) := begin refine ⟨_,_⟩, {{unfold bounded_term_comparison id, fapply universal_map_inj_of_components_inj, change ∀ i : ℕ, function.injective ((cocone_of_bounded_term_L_infty n l).map i), dsimp[cocone_of_bounded_term_L_infty], intro m, fapply Lhom.on_bounded_term_inj (@henkin_language_canonical_map_inj L m)},}, {intro f, induction f, {refine ⟨(by {fapply canonical_map, by {change ℕ, exact 0}, exact bd_var f}), by split⟩}, {have W := germ_rep f_f, rcases W with ⟨⟨i,x⟩, Hx⟩, fapply exists.intro, fapply canonical_map i, fapply bd_func, exact x, rw[<-Hx], refl,}, {rcases f_ih_t with ⟨t, Ht⟩, rcases f_ih_s with ⟨s,Hs⟩, have Wt := germ_rep t, have Ws := germ_rep s, rcases Wt with ⟨⟨i,x_t⟩, Hxt⟩, rcases Ws with ⟨⟨j, x_s⟩, Hxs⟩, let x_t' : (henkin_bounded_term_chain n (f_l + 1)).obj (i+j), fapply (henkin_bounded_term_chain n (f_l + 1)).mor, exact i, simp only [ℕ', directed_type.rel, id.def, zero_le, le_add_iff_nonneg_right], exact x_t, let x_s' : (henkin_bounded_term_chain n 0).obj (i+j), fapply (henkin_bounded_term_chain n 0).mor, exact j, simp only [ℕ', directed_type.rel, zero_le, le_add_iff_nonneg_left], exact x_s, have Hxt' : ⟦(⟨i+j,x_t'⟩ : coproduct_of_directed_diagram $ henkin_bounded_term_chain n (f_l + 1))⟧ = t, {rw[<-Hxt], simp[(≈), germ_relation], refine ⟨(i+j),x_t',⟨by simp,_⟩,_⟩, dsimp[henkin_bounded_term_chain, henkin_language_chain_maps], let k := i + j, simp only [id_of_self_map], apply Lhom.id_bounded_term, fapply exists.intro, simp only [zero_le, le_add_iff_nonneg_right]}, have Hxs' : ⟦(⟨i+j,x_s'⟩ : coproduct_of_directed_diagram $ henkin_bounded_term_chain n 0)⟧ = s, {{rw[<-Hxs], simp[(≈), germ_relation], refine ⟨(i+j),x_s',⟨by simp,_⟩,_⟩, dsimp[henkin_bounded_term_chain, henkin_language_chain_maps], let k := i + j, simp only [id_of_self_map], apply Lhom.id_bounded_term, fapply exists.intro, simp only [zero_le, le_add_iff_nonneg_left]},}, fapply exists.intro, fapply canonical_map, change ℕ, exact (i + j), fapply bd_app, exact x_t', exact x_s', rw[<-Ht, <-Hs, <-Hxt', <-Hxs'], refl},} end @[simp]lemma bounded_formula_comparison_bijective {L : Language} (n l) : function.bijective (@bounded_formula_comparison L n l) := begin refine ⟨_,_⟩, {{unfold bounded_formula_comparison id, fapply universal_map_inj_of_components_inj, change ∀ i : ℕ, function.injective ((cocone_of_bounded_formula_L_infty n l).map i), dsimp[cocone_of_bounded_formula_L_infty], intro m, fapply Lhom.on_bounded_formula_inj (@henkin_language_canonical_map_inj L m)},}, {intro f, induction f, {refine ⟨(by {fapply canonical_map, by {change ℕ, exact 0}, exact bd_falsum}), by split⟩}, { rcases (bounded_term_comparison_bijective f_n 0).right f_t₁ with ⟨t₁, H₁⟩, rcases (bounded_term_comparison_bijective f_n 0).right f_t₂ with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact i+j, fapply bd_equal, exact push_to_sum_r x j, exact push_to_sum_l y i, simp[H₁, H₂], rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {have x := germ_rep f_R, rcases x with ⟨⟨i,x⟩,H⟩, fapply exists.intro, have R' := bd_rel x, exact ⟦⟨i,R'⟩⟧, tidy}, {rcases f_ih with ⟨t₁, H₁⟩, rcases (bounded_term_comparison_bijective _ 0).right f_t with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact i+j, fapply bd_apprel, exact push_to_sum_r x j, exact push_to_sum_l y i, rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {rcases f_ih_f₁ with ⟨t₁, H₁⟩, rcases f_ih_f₂ with ⟨t₂, H₂⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, rcases germ_rep t₂ with ⟨⟨j,y⟩,Hy⟩, fapply exists.intro, fapply canonical_map, exact (i+j), fapply bd_imp, exact push_to_sum_r x j, exact push_to_sum_l y i, rw[<-H₁, <-H₂,<-Hx, <-Hy, <-canonical_map_quotient, same_fiber_as_push_to_r x j ,<-canonical_map_quotient, same_fiber_as_push_to_l y i], simpa only}, {rcases f_ih with ⟨t₁, H₁⟩, rcases germ_rep t₁ with ⟨⟨i,x⟩,Hx⟩, fapply exists.intro, fapply canonical_map, exact i, fapply bd_all, exact x, rw[<-H₁, <-Hx], simpa only}}, end @[simp]lemma bounded_formula'_comparison_bijective {L : Language} : function.bijective (@bounded_formula'_comparison L) := by apply bounded_formula_comparison_bijective noncomputable def equiv_bounded_formula_comparison {L : Language} : equiv (colimit (@henkin_bounded_formula_chain' L)) (bounded_formula (L_infty L) 1) := begin fapply equiv.of_bijective, exacts [bounded_formula'_comparison, bounded_formula'_comparison_bijective] end /- Not really a chain, since we haven't set up interpretations of theories yet -/ def henkin_theory_chain {L : Language} (T : Theory L) : Π(n : ℕ), (Theory (obj (@henkin_language_chain L) n)) | 0 := T | (n+1) := henkin_theory_step (henkin_theory_chain n) def is_consistent_henkin_theory_chain {L} {T : Theory L} (hT : is_consistent T) (n : ℕ) : is_consistent (henkin_theory_chain T n) := by induction n; [exact hT, exact is_consistent_henkin_theory_step n_ih] /- Now we have to push all these theories into Theory L_∞, so that they literally become a chain of sets. -/ /- Given T_n from henkin_theory_chain, ι T_n is the expansion of T_n to an L_infty theory -/ def ι {L : Language} {T : Theory L} (m : ℕ) : Theory (L_infty L) := (Lhom.on_sentence (@henkin_language_canonical_map L m)) '' (@henkin_theory_chain L T m) @[simp]lemma in_iota_of_in_step {L} (i) {T} (f : sentence (@henkin_language_chain_objects L (i+1))): f ∈ (@henkin_theory_chain L T (i+1)) → Lhom.on_bounded_formula (@henkin_language_canonical_map L (i + 1)) f ∈ @ι L T (i + 1) := by {intro H, split, swap, exact f, refine ⟨H,_⟩, refl} @[simp]lemma is_consistent_iota {L : Language} {T : Theory L} (hT : is_consistent T) (m : ℕ) : is_consistent (@ι _ T m) := begin unfold ι, intro, have := @is_consistent_henkin_theory_chain L T hT m, suffices : (henkin_theory_chain T m) ⊢' bd_falsum, by contradiction, apply nonempty.intro, apply reflect_prf, exact henkin_language_canonical_map_inj m, simp[on_formula, bounded_preformula.fst, Theory.fst, set.image_image, sprovable, on_sentence_fst] at *; exact classical.choice a end @[simp]lemma not_succ (i : ℕ) : ¬ i = i + 1 := by {have := nat.succ_ne_self i, tidy} lemma henkin_theory_chain_inclusion_step {L} {T : Theory L} {i : ℕ} {f ∈ henkin_theory_chain T i} : (henkin_bounded_formula_chain 0 0).mor (by simp) f ∈ henkin_theory_chain T (i + 1) := begin dsimp[henkin_bounded_formula_chain, henkin_theory_chain], apply or.inl, unfold Theory_induced, fapply exists.intro, tidy, end lemma henkin_theory_chain_inclusion {L} {T : Theory L} {i j : ℕ} (h_leq : i ≤ j + 1) {f ∈ henkin_theory_chain T i} : (henkin_bounded_formula_chain 0 0).mor (by exact h_leq) f ∈ henkin_theory_chain T (j + 1) := begin dsimp[henkin_bounded_formula_chain], by_cases i = j +1, subst h, simp[id_bounded_formula 0 0 f], exact H, induction j with j ih, {have : i = 0, {suffices : i ≤ 0, by exact nat.eq_zero_of_le_zero this, fapply nat.le_of_le_and_ne_succ, repeat{assumption}}, subst this, apply or.inl, fapply exists.intro, exact f, tidy}, have : i ≤ nat.succ j, by {fapply nat.le_of_le_and_ne_succ, repeat{assumption}}, have := ih this, by_cases i = j+1, subst h, apply henkin_theory_chain_inclusion_step, assumption, unfold on_sentence henkin_language_chain_maps, simp*, apply or.inl, unfold Theory_induced, fapply exists.intro, exact on_bounded_formula (henkin_language_chain_maps L i (j+1) (by assumption)) f, split, apply ih, assumption, dedup, dsimp[on_sentence], unfold henkin_language_chain_maps, simp*, change on_bounded_formula (henkin_language_chain_maps L (j+1) (j+2) _) (on_bounded_formula (henkin_language_chain_maps L j (j + 1) _) (on_bounded_formula (henkin_language_chain_maps L i j _) f)) = on_bounded_formula (henkin_language_chain_maps L (j + 1) (j + 2) _) (on_bounded_formula ((Lhom.id (henkin_language_chain_objects (j + 1)))) (on_bounded_formula (henkin_language_chain_maps L j (j + 1) _) (on_bounded_formula (Lhom.id (henkin_language_chain_objects j)) (on_bounded_formula (henkin_language_chain_maps L i j _) f)))), simp only [id_bounded_formula 0 0, not_false_iff, nat.le_of_le_and_ne_succ, fol.Lhom.on_bounded_formula] end @[simp]lemma iota_inclusion_of_le {L} {T : Theory L} : Π{i : ℕ} {j : ℕ} (h : i ≤ j), (@ι _ T i) ⊆ (@ι _ T j) | i 0 h := by rw[(nat.eq_zero_of_le_zero h)] | i (j+1) h := by {by_cases i = j+1, rw[h], have := (cocone_of_bounded_formula_L_infty 0 0).h_compat, have this' := @this i (j+1) (by simp*), dsimp[cocone_of_bounded_formula_L_infty] at this', dsimp[ι, on_sentence], show Language, exact L, intros ψ hψ, have hψ_w := classical.psigma_of_exists hψ, cases hψ_w with x Hx, refine ⟨(@henkin_bounded_formula_chain L 0 0).mor (by assumption) x,_⟩, split, {simp[henkin_theory_chain_inclusion, Hx]}, simp, change (function.comp (on_bounded_formula (henkin_language_canonical_map (j + 1))) ((henkin_bounded_formula_chain 0 0).mor _)) x = ψ, rw[<-this'], exact Hx.right } /- T_infty is the henkinization of T; we define it to be the union ⋃ (n : ℕ), ι(T n). -/ @[reducible]def T_infty {L : Language} (T : Theory L) : Theory (L_infty L) := set.Union (@ι L T) @[reducible]def henkin_language {L} {T : Theory L} {hT : is_consistent T} : Language := L_infty L local infix ` →ᴸ `:10 := Lhom -- \^L /- I dislike this proof, but I don't know how apply canonical_map_language otherwise... -/ def henkin_language_over {L} {T : Theory L} {hT : is_consistent T} : L →ᴸ (@henkin_language L T hT) := by {change (henkin_language_chain.obj (0 : ℕ)) →ᴸ colimit_language henkin_language_chain, apply canonical_map_language} lemma henkin_language_over_injective {L} {T : Theory L} {hT : is_consistent T} : Lhom.is_injective (@henkin_language_over L T hT) := begin split, all_goals{intro n, unfold henkin_language_over canonical_map_language, simp, rw[<-canonical_map], fapply canonical_map_inj_of_transition_maps_inj, intros i j H, dsimp[diagram_functions, diagram_relations, henkin_language_chain], simp only [henkin_language_chain_maps_inj, Lhom.is_injective.on_function, Lhom.is_injective.on_relation]} end def complete_henkin_Theory_over {L : Language} (T : Theory L) (hT : is_consistent T) : Type u := Σ' T' : Theory_over T hT, has_enough_constants T'.val ∧ is_complete T'.val @[reducible]def henkinization {L : Language} {T : Theory L} (hT : is_consistent T) : Theory (@henkin_language L T hT) := T_infty T /-- Given an f : bounded_formula L_infty, return a Henkin witness for f, along with all the data and conditions needed to obtain this witness --/ noncomputable def wit_infty {L} {T : Theory L} {hT : is_consistent T} (f : bounded_formula (@henkin_language L T hT) 1) : Σ c : (@henkin_language L T hT).constants, Σ (f' : Σ' (x : colimit (@henkin_bounded_formula_chain' L)), bounded_formula'_comparison x = f), Σ' (f'' : coproduct_of_directed_diagram (@henkin_bounded_formula_chain' L)), ⟦f''⟧ = f'.fst ∧ c = (henkin_language_canonical_map (f''.fst + 1)).on_function (wit' f''.snd) := begin have f_lift1 := classical.psigma_of_exists ((bounded_formula'_comparison_bijective).right f), have f_lift2 := germ_rep (f_lift1.fst), refine ⟨(henkin_language_canonical_map (f_lift2.fst.fst + 1)).on_function (wit' (f_lift2.fst.snd)), f_lift1,(f_lift2.fst), f_lift2.snd,rfl⟩, end @[simp]lemma henkinization_is_henkin {L : Language} {T : Theory L} (hT : is_consistent T) : has_enough_constants (henkinization hT) := begin apply has_enough_constants.intro, unfold henkinization T_infty, intro f, have big_sigma := wit_infty f, rcases big_sigma with ⟨c, Hc⟩, refine ⟨c,_⟩, rcases Hc with ⟨⟨f', Hf'⟩,⟨i, f''⟩, H⟩, fapply nonempty.intro, fapply axm, simp only [*, fol.subst_formula, fol.bounded_preterm.fst, set.mem_Union, set.mem_image, fol.subst0_bounded_formula_fst, fol.bounded_preformula.fst], refine ⟨_,⟨(i+1),_⟩,_⟩, {fapply Lhom.on_bounded_formula, exact (@henkin_language_chain L).obj (i+1), fapply henkin_language_canonical_map, fapply wit_property, fapply Lhom.on_bounded_formula, exact (@henkin_language_chain L).obj i, exact henkin_language_inclusion, exact f'', exact (wit' f'')}, {fapply in_iota_of_in_step, fapply or.inr, tidy}, {let c_infty := (bd_const ((henkin_language_canonical_map (i + 1)).on_function (wit' f''))), have this1 : bounded_preformula.fst (∃' f) ⟹ (bounded_preformula.fst f)[bounded_preterm.fst (bd_const ((henkin_language_canonical_map (i + 1)).on_function (wit' f''))) // 0] = bounded_preformula.fst ((∃' f) ⟹ f[c_infty/0]), by simp, rw[this1], suffices : (Lhom.on_bounded_formula (henkin_language_canonical_map (i + 1)) (wit_property (Lhom.on_bounded_formula henkin_language_inclusion f'') (wit' f''))) = (∃' f ⟹ f[c_infty /0]), by rw[this], unfold wit_property at *, dsimp[c_infty], rw[<-canonical_map_quotient] at H, dsimp at H, rw[<-Hf',<-H.left], unfold bounded_formula'_comparison bounded_formula_comparison id, rw[(@universal_map_property ℕ' (henkin_bounded_formula_chain') (cocone_of_bounded_formula'_L_infty) i f'')], dsimp[cocone_of_bounded_formula'_L_infty], have : henkin_language_canonical_map i = henkin_language_canonical_map (i+1) ∘ henkin_language_inclusion, {have := cocone_of_L_infty.h_compat, have a := @this i (i+1) (by simp), dsimp[cocone_of_L_infty, cocone_of_colimit_language, henkin_language_chain] at a, unfold henkin_language_canonical_map, simp only [*, henkin_language_inclusion_chain_map], exact a}, rw[this,Lhom.comp_on_bounded_formula], have : (function.comp (Lhom.on_bounded_formula (henkin_language_canonical_map (i + 1))) (Lhom.on_bounded_formula henkin_language_inclusion) f'') = Lhom.on_bounded_formula (henkin_language_canonical_map (i+1)) (Lhom.on_bounded_formula henkin_language_inclusion f''), by refl, rw[this], have : (Lhom.on_bounded_formula (henkin_language_canonical_map (i + 1)) (Lhom.on_bounded_formula henkin_language_inclusion f''))[bd_const ((henkin_language_canonical_map (i + 1)).on_function (wit' f'')) /0] = (Lhom.on_bounded_formula (henkin_language_canonical_map (i + 1)) ((Lhom.on_bounded_formula henkin_language_inclusion f'')[bd_const (wit' f'') /0])), by tidy, rw[this], have : ∃' Lhom.on_bounded_formula (henkin_language_canonical_map (i + 1)) (Lhom.on_bounded_formula henkin_language_inclusion f'') = Lhom.on_bounded_formula (henkin_language_canonical_map (i+1)) (∃' (Lhom.on_bounded_formula henkin_language_inclusion f'')), by tidy, rw[this]} end noncomputable def directed_union_finset_lift {α β : Type*} (ι : α → set β) (Γ' : finset (set.Union ι)) (x ∈ Γ') : Σ' a : α, (ι a) x := begin cases x with x H', have := classical.psigma_of_exists H', rcases this with ⟨S,a⟩, simp[*,-a] at a, cases a with a1 a2, have := classical.psigma_of_exists a1, cases this with a Ha, rw[← Ha] at a2, exact ⟨a, a2⟩ end /- For every n, T_n is a theory over T in Theory L_infty -/ def henkin_Theory_over {L} (T : Theory L) (hT : is_consistent T) (n : ℕ) : Theory_over (@ι _ T 0) (@is_consistent_iota L T hT 0) := by { refine ⟨@ι _ T n, _⟩, split, apply iota_inclusion_of_le, simp, apply is_consistent_iota hT} def henkin_theory_schain {L} (T : Theory L) (hT : is_consistent T): set (Theory_over (@ι _ T 0) (@is_consistent_iota L T hT 0)) := {T' | ∃ k : ℕ, (@ι _ T k) = T'.val} /- (T ∪ set.sUnion (subtype.val '' Ts)) actually is (henkinization hT) -/ lemma iota_union_rw {L} (T : Theory L) (hT : is_consistent T) : (@ι _ T 0) ∪ ⋃₀(subtype.val '' henkin_theory_schain T hT) = henkinization hT := begin ext, split; intros; auto_cases, {tidy}, {tidy}, {right, cases a_h with H₁ H₂, use a_w, refine ⟨_,‹_›⟩, { unfold henkin_theory_schain, rw[set.mem_range] at H₁, cases H₁ with n Hn, rw[set.mem_image], refine ⟨_,_⟩, use a_w, tidy, apply is_consistent_iota; from ‹_› }}, recover end /- henkin_theory_chain satisfies the chain condition -/ lemma chain_henkin_theory_chain {L} (T : Theory L) (hT : is_consistent T) : zorn.chain Theory_over_subset (henkin_theory_schain T hT) := begin tidy, rename H_1_w i, rename H_w j, by_cases i ≤ j, apply or.inr, apply iota_inclusion_of_le, exact h, apply or.inl, suffices : j ≤ i, by {apply iota_inclusion_of_le, exact this}, revert h, simp only [not_le], apply nat.le_of_lt end lemma is_consistent_henkinization {L : Language} {T : Theory L} (hT : is_consistent T) : is_consistent (henkinization hT) := begin have := @consis_limit _ _ _ (henkin_theory_schain T hT), rw[iota_union_rw] at this, exact this (chain_henkin_theory_chain T hT) end -- @[simp]lemma is_consistent_henkinization {L : Language} {T : Theory L} (hT : is_consistent T) : is_consistent (henkinization hT) := -- begin -- intro P, have := proof_compactness P, -- have : ∃ k : ℕ, @ι L T k ⊢' bd_falsum, -- {sorry}, -- again, this depends on picking a representative of a germ-eq class -- -- on the induced colimit of formulas -- -- remark(Floris): we need a lemma that if a directed union of theories proves f, then an element of it proves f. -- cases this with k P', unfold ι at P', -- apply is_consistent_henkin_theory_chain hT k, -- apply nonempty.map (Lhom.reflect_prf (henkin_language_canonical_map_inj k)), -- simp only [on_formula, bounded_preformula.fst, Theory.fst, set.image_image, sprovable, -- on_sentence_fst] at P' ⊢, exact P' -- end @[reducible]noncomputable def completion_of_henkinization_core {L} {T : Theory L} (hT : is_consistent T) : Σ' (T' : Theory_over (henkinization hT) _), is_complete (T'.val) := completion_of_consis _ (henkinization hT) (is_consistent_henkinization hT) /- the completed theory-/ @[reducible]def completion_of_henkinization {L} {T : Theory L} (hT : is_consistent T) := (completion_of_henkinization_core (by assumption)).fst.val /- the completed theory contains the original theory -/ @[simp]def completion_of_henkinization_contains {L} {T : Theory L} (hT : is_consistent T) := (completion_of_henkinization_core (by assumption)).fst.property.left /- the completed theory is consistent -/ @[simp]def completion_of_henkinization_consistent {L} {T : Theory L} (hT : is_consistent T) := (completion_of_henkinization_core (by assumption)).fst.property.right /- the completed theory is complete -/ @[reducible]def completion_of_henkinization_complete {L} {T : Theory L} (hT : is_consistent T) := (completion_of_henkinization_core (by assumption)).snd /- the completed theory is henkin -/ @[simp]lemma completion_of_henkinization_is_henkin {L} {T : Theory L} (hT : is_consistent T) : has_enough_constants (completion_of_henkinization hT) := begin fapply has_enough_constants.intro, cases (@henkinization_is_henkin L T hT) with C H, intro f, refine ⟨C f,_⟩, fapply weakening', exact (Theory.fst $ (henkinization hT)), fapply set.image_subset, simp, exact H f end /- The term model of the complete henkinization of T satisfies T -/ @[simp]lemma reduct_of_complete_henkinization_models_T {L} {T : Theory L} (hT : is_consistent T) : Lhom.reduct (@henkin_language_canonical_map L 0) (term_model (completion_of_henkinization hT)) ⊨ T := begin fapply Lhom.reduct_all_ssatisfied, {simp only [henkin_language_canonical_map_inj]}, intros f hf, apply (term_model_ssatisfied (completion_of_henkinization_complete hT) (completion_of_henkinization_is_henkin hT)), fapply completion_of_henkinization_contains hT, unfold henkinization T_infty, simp, refine ⟨0, _⟩, unfold ι, tidy end /- Given ψ ∈ T, the term model of the complete henkinization of T satisfies ψ -/ @[simp]lemma reduct_of_complete_henkinization_satisfies {L} {T : Theory L} (hT : is_consistent T) (ψ : sentence L) (hψ : ψ ∈ T) : Lhom.reduct (@henkin_language_canonical_map L 0) (term_model (completion_of_henkinization hT)) ⊨ ψ := reduct_of_complete_henkinization_models_T _ hψ
05b0b08c6ba5139f3cdf5333b9e5cd3c7ae919fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/manifold/instances/real.lean
f82c76fdf14788d987d5efe5c67d79c71f82a3c1
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,823
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 geometry.manifold.smooth_manifold_with_corners import analysis.inner_product_space.pi_L2 /-! # Constructing examples of manifolds over ℝ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We introduce the necessary bits to be able to define manifolds modelled over `ℝ^n`, boundaryless or with boundary or with corners. As a concrete example, we construct explicitly the manifold with boundary structure on the real interval `[x, y]`. More specifically, we introduce * `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)` for the model space used to define `n`-dimensional real manifolds with boundary * `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n)` for the model space used to define `n`-dimensional real manifolds with corners ## Notations In the locale `manifold`, we introduce the notations * `𝓡 n` for the identity model with corners on `euclidean_space ℝ (fin n)` * `𝓡∂ n` for `model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n)`. For instance, if a manifold `M` is boundaryless, smooth and modelled on `euclidean_space ℝ (fin m)`, and `N` is smooth with boundary modelled on `euclidean_half_space n`, and `f : M → N` is a smooth map, then the derivative of `f` can be written simply as `mfderiv (𝓡 m) (𝓡∂ n) f` (as to why the model with corners can not be implicit, see the discussion in `smooth_manifold_with_corners.lean`). ## Implementation notes The manifold structure on the interval `[x, y] = Icc x y` requires the assumption `x < y` as a typeclass. We provide it as `[fact (x < y)]`. -/ noncomputable theory open set function open_locale manifold /-- The half-space in `ℝ^n`, used to model manifolds with boundary. We only define it when `1 ≤ n`, as the definition only makes sense in this case. -/ def euclidean_half_space (n : ℕ) [has_zero (fin n)] : Type := {x : euclidean_space ℝ (fin n) // 0 ≤ x 0} /-- The quadrant in `ℝ^n`, used to model manifolds with corners, made of all vectors with nonnegative coordinates. -/ def euclidean_quadrant (n : ℕ) : Type := {x : euclidean_space ℝ (fin n) // ∀i:fin n, 0 ≤ x i} section /- Register class instances for euclidean half-space and quadrant, that can not be noticed without the following reducibility attribute (which is only set in this section). -/ local attribute [reducible] euclidean_half_space euclidean_quadrant variable {n : ℕ} instance [has_zero (fin n)] : topological_space (euclidean_half_space n) := by apply_instance instance : topological_space (euclidean_quadrant n) := by apply_instance instance [has_zero (fin n)] : inhabited (euclidean_half_space n) := ⟨⟨0, le_rfl⟩⟩ instance : inhabited (euclidean_quadrant n) := ⟨⟨0, λ i, le_rfl⟩⟩ lemma range_half_space (n : ℕ) [has_zero (fin n)] : range (λx : euclidean_half_space n, x.val) = {y | 0 ≤ y 0} := by simp lemma range_quadrant (n : ℕ) : range (λx : euclidean_quadrant n, x.val) = {y | ∀i:fin n, 0 ≤ y i} := by simp end /-- Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_half_space n)`, used as a model for manifolds with boundary. In the locale `manifold`, use the shortcut `𝓡∂ n`. -/ def model_with_corners_euclidean_half_space (n : ℕ) [has_zero (fin n)] : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n) := { to_fun := subtype.val, inv_fun := λx, ⟨update x 0 (max (x 0) 0), by simp [le_refl]⟩, source := univ, target := {x | 0 ≤ x 0}, map_source' := λx hx, x.property, map_target' := λx hx, mem_univ _, left_inv' := λ ⟨xval, xprop⟩ hx, begin rw [subtype.mk_eq_mk, update_eq_iff], exact ⟨max_eq_left xprop, λ i _, rfl⟩ end, right_inv' := λx hx, update_eq_iff.2 ⟨max_eq_left hx, λ i _, rfl⟩, source_eq := rfl, unique_diff' := have this : unique_diff_on ℝ _ := unique_diff_on.pi (fin n) (λ _, ℝ) _ _ (λ i ∈ ({0} : set (fin n)), unique_diff_on_Ici 0), by simpa only [singleton_pi] using this, continuous_to_fun := continuous_subtype_val, continuous_inv_fun := (continuous_id.update 0 $ (continuous_apply 0).max continuous_const).subtype_mk _ } /-- Definition of the model with corners `(euclidean_space ℝ (fin n), euclidean_quadrant n)`, used as a model for manifolds with corners -/ def model_with_corners_euclidean_quadrant (n : ℕ) : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_quadrant n) := { to_fun := subtype.val, inv_fun := λx, ⟨λi, max (x i) 0, λi, by simp only [le_refl, or_true, le_max_iff]⟩, source := univ, target := {x | ∀ i, 0 ≤ x i}, map_source' := λx hx, by simpa only [subtype.range_val] using x.property, map_target' := λx hx, mem_univ _, left_inv' := λ ⟨xval, xprop⟩ hx, by { ext i, simp only [subtype.coe_mk, xprop i, max_eq_left] }, right_inv' := λ x hx, by { ext1 i, simp only [hx i, max_eq_left] }, source_eq := rfl, unique_diff' := have this : unique_diff_on ℝ _ := unique_diff_on.univ_pi (fin n) (λ _, ℝ) _ (λ i, unique_diff_on_Ici 0), by simpa only [pi_univ_Ici] using this, continuous_to_fun := continuous_subtype_val, continuous_inv_fun := continuous.subtype_mk (continuous_pi $ λ i, (continuous_id.max continuous_const).comp (continuous_apply i)) _ } localized "notation (name := model_with_corners_self.euclidean) `𝓡 `n := (model_with_corners_self ℝ (euclidean_space ℝ (fin n)) : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_space ℝ (fin n)))" in manifold localized "notation (name := model_with_corners_euclidean_half_space.euclidean) `𝓡∂ `n := (model_with_corners_euclidean_half_space n : model_with_corners ℝ (euclidean_space ℝ (fin n)) (euclidean_half_space n))" in manifold /-- The left chart for the topological space `[x, y]`, defined on `[x,y)` and sending `x` to `0` in `euclidean_half_space 1`. -/ def Icc_left_chart (x y : ℝ) [fact (x < y)] : local_homeomorph (Icc x y) (euclidean_half_space 1) := { source := {z : Icc x y | z.val < y}, target := {z : euclidean_half_space 1 | z.val 0 < y - x}, to_fun := λ(z : Icc x y), ⟨λi, z.val - x, sub_nonneg.mpr z.property.1⟩, inv_fun := λz, ⟨min (z.val 0 + x) y, by simp [le_refl, z.prop, le_of_lt (fact.out (x < y))]⟩, map_source' := by simp only [imp_self, sub_lt_sub_iff_right, mem_set_of_eq, forall_true_iff], map_target' := by { simp only [min_lt_iff, mem_set_of_eq], assume z hz, left, dsimp [-subtype.val_eq_coe] at hz, linarith }, left_inv' := begin rintros ⟨z, hz⟩ h'z, simp only [mem_set_of_eq, mem_Icc] at hz h'z, simp only [hz, min_eq_left, sub_add_cancel] end, right_inv' := begin rintros ⟨z, hz⟩ h'z, rw subtype.mk_eq_mk, funext, dsimp at hz h'z, have A : x + z 0 ≤ y, by linarith, rw subsingleton.elim i 0, simp only [A, add_comm, add_sub_cancel', min_eq_left], end, open_source := begin have : is_open {z : ℝ | z < y} := is_open_Iio, exact this.preimage continuous_subtype_val end, open_target := begin have : is_open {z : ℝ | z < y - x} := is_open_Iio, have : is_open {z : euclidean_space ℝ (fin 1) | z 0 < y - x} := this.preimage (@continuous_apply (fin 1) (λ _, ℝ) _ 0), exact this.preimage continuous_subtype_val end, continuous_to_fun := begin apply continuous.continuous_on, apply continuous.subtype_mk, have : continuous (λ (z : ℝ) (i : fin 1), z - x) := continuous.sub (continuous_pi $ λi, continuous_id) continuous_const, exact this.comp continuous_subtype_val, end, continuous_inv_fun := begin apply continuous.continuous_on, apply continuous.subtype_mk, have A : continuous (λ z : ℝ, min (z + x) y) := (continuous_id.add continuous_const).min continuous_const, have B : continuous (λz : euclidean_space ℝ (fin 1), z 0) := continuous_apply 0, exact (A.comp B).comp continuous_subtype_val end } /-- The right chart for the topological space `[x, y]`, defined on `(x,y]` and sending `y` to `0` in `euclidean_half_space 1`. -/ def Icc_right_chart (x y : ℝ) [fact (x < y)] : local_homeomorph (Icc x y) (euclidean_half_space 1) := { source := {z : Icc x y | x < z.val}, target := {z : euclidean_half_space 1 | z.val 0 < y - x}, to_fun := λ(z : Icc x y), ⟨λi, y - z.val, sub_nonneg.mpr z.property.2⟩, inv_fun := λz, ⟨max (y - z.val 0) x, by simp [le_refl, z.prop, le_of_lt (fact.out (x < y)), sub_eq_add_neg]⟩, map_source' := by simp only [imp_self, mem_set_of_eq, sub_lt_sub_iff_left, forall_true_iff], map_target' := by { simp only [lt_max_iff, mem_set_of_eq], assume z hz, left, dsimp [-subtype.val_eq_coe] at hz, linarith }, left_inv' := begin rintros ⟨z, hz⟩ h'z, simp only [mem_set_of_eq, mem_Icc] at hz h'z, simp only [hz, sub_eq_add_neg, max_eq_left, add_add_neg_cancel'_right, neg_add_rev, neg_neg] end, right_inv' := begin rintros ⟨z, hz⟩ h'z, rw subtype.mk_eq_mk, funext, dsimp at hz h'z, have A : x ≤ y - z 0, by linarith, rw subsingleton.elim i 0, simp only [A, sub_sub_cancel, max_eq_left], end, open_source := begin have : is_open {z : ℝ | x < z} := is_open_Ioi, exact this.preimage continuous_subtype_val end, open_target := begin have : is_open {z : ℝ | z < y - x} := is_open_Iio, have : is_open {z : euclidean_space ℝ (fin 1) | z 0 < y - x} := this.preimage (@continuous_apply (fin 1) (λ _, ℝ) _ 0), exact this.preimage continuous_subtype_val end, continuous_to_fun := begin apply continuous.continuous_on, apply continuous.subtype_mk, have : continuous (λ (z : ℝ) (i : fin 1), y - z) := continuous_const.sub (continuous_pi (λi, continuous_id)), exact this.comp continuous_subtype_val, end, continuous_inv_fun := begin apply continuous.continuous_on, apply continuous.subtype_mk, have A : continuous (λ z : ℝ, max (y - z) x) := (continuous_const.sub continuous_id).max continuous_const, have B : continuous (λz : euclidean_space ℝ (fin 1), z 0) := continuous_apply 0, exact (A.comp B).comp continuous_subtype_val end } /-- Charted space structure on `[x, y]`, using only two charts taking values in `euclidean_half_space 1`. -/ instance Icc_manifold (x y : ℝ) [fact (x < y)] : charted_space (euclidean_half_space 1) (Icc x y) := { atlas := {Icc_left_chart x y, Icc_right_chart x y}, chart_at := λz, if z.val < y then Icc_left_chart x y else Icc_right_chart x y, mem_chart_source := λz, begin by_cases h' : z.val < y, { simp only [h', if_true], exact h' }, { simp only [h', if_false], apply lt_of_lt_of_le (fact.out (x < y)), simpa only [not_lt] using h'} end, chart_mem_atlas := λ z, by by_cases h' : (z : ℝ) < y; simp [h'] } /-- The manifold structure on `[x, y]` is smooth. -/ instance Icc_smooth_manifold (x y : ℝ) [fact (x < y)] : smooth_manifold_with_corners (𝓡∂ 1) (Icc x y) := begin have M : cont_diff_on ℝ ∞ (λz : euclidean_space ℝ (fin 1), - z + (λi, y - x)) univ, { rw cont_diff_on_univ, exact cont_diff_id.neg.add cont_diff_const }, apply smooth_manifold_with_corners_of_cont_diff_on, assume e e' he he', simp only [atlas, mem_singleton_iff, mem_insert_iff] at he he', /- We need to check that any composition of two charts gives a `C^∞` function. Each chart can be either the left chart or the right chart, leaving 4 possibilities that we handle successively. -/ rcases he with rfl | rfl; rcases he' with rfl | rfl, { -- `e = left chart`, `e' = left chart` exact (mem_groupoid_of_pregroupoid.mpr (symm_trans_mem_cont_diff_groupoid _ _ _)).1 }, { -- `e = left chart`, `e' = right chart` apply M.congr_mono _ (subset_univ _), rintro _ ⟨⟨hz₁, hz₂⟩, ⟨⟨z, hz₀⟩, rfl⟩⟩, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, update_same, max_eq_left, hz₀, lt_sub_iff_add_lt] with mfld_simps at hz₁ hz₂, rw [min_eq_left hz₁.le, lt_add_iff_pos_left] at hz₂, ext i, rw subsingleton.elim i 0, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, *, pi_Lp.add_apply, pi_Lp.neg_apply, max_eq_left, min_eq_left hz₁.le, update_same] with mfld_simps, abel }, { -- `e = right chart`, `e' = left chart` apply M.congr_mono _ (subset_univ _), rintro _ ⟨⟨hz₁, hz₂⟩, ⟨z, hz₀⟩, rfl⟩, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, max_lt_iff, update_same, max_eq_left hz₀] with mfld_simps at hz₁ hz₂, rw lt_sub_comm at hz₁, ext i, rw subsingleton.elim i 0, simp only [model_with_corners_euclidean_half_space, Icc_left_chart, Icc_right_chart, pi_Lp.add_apply, pi_Lp.neg_apply, update_same, max_eq_left, hz₀, hz₁.le] with mfld_simps, abel }, { -- `e = right chart`, `e' = right chart` exact (mem_groupoid_of_pregroupoid.mpr (symm_trans_mem_cont_diff_groupoid _ _ _)).1 } end /-! Register the manifold structure on `Icc 0 1`, and also its zero and one. -/ section local attribute [instance] real.fact_zero_lt_one instance : charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) := by apply_instance instance : smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) := by apply_instance end
e2212385b4ea19b23ef9fb3666c085f20787b5c5
e58fe8dce8abdb027029831196eef44ecb90a19a
/Imperial/pred_prop_example.lean
560560ad8bc938494ce323a343d1618e61d14dba
[]
no_license
hieule3004/Imperial
89fc066eded43cf6015e19f6f83677411013b47c
829d0d96603ff3e68ede818873db4931b8d854da
refs/heads/master
1,584,834,346,353
1,531,250,018,000
1,531,250,018,000
139,205,362
0
0
null
null
null
null
UTF-8
Lean
false
false
6,509
lean
section open classical variables (α : Type) (p q : α → Prop) variable a : α variable r : Prop example : (∃ x : α, r) → r := λh, exists.elim h (λ_, id) example : (∃ x : α, r) → r := by { intro h, cases h, assumption } example : r → (∃ x : α, r) := exists.intro a include a example : r → (∃ x : α, r) := by { intro, constructor, assumption' } omit a example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := ⟨λh, exists.elim h (λh1, λh2, ⟨⟨h1, h2.left⟩, h2.right⟩), λh, exists.elim (h.left) (λh1, λh2, ⟨h1, h2, h.right⟩)⟩ example : (∃ x, p x ∧ r) ↔ (∃ x, p x) ∧ r := by { constructor; { intro h, cases h with h1 h2, cases h1 <|> cases h2, repeat { constructor }, assumption' } } example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := ⟨λh, exists.elim h (λh1, λh2, h2.elim (λh3, or.inl ⟨h1, h3⟩) (λh3, or.inr ⟨h1, h3⟩)), λh, h.elim (λh1, exists.elim h1 (λh2, λh3, ⟨h2, or.inl h3⟩)) (λh1, exists.elim h1 (λh2, λh3, ⟨h2, or.inr h3⟩))⟩ example : (∃ x, p x ∨ q x) ↔ (∃ x, p x) ∨ (∃ x, q x) := by { constructor; intro h, { cases h with _ h1, cases h1, { left, constructor, assumption }, { right, constructor, assumption } }, { cases h with h1 h1; cases h1; constructor, { left, assumption }, { right, assumption } } } example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := ⟨λh, λh1, exists.elim h1 (λh2, λh3, h3 (h h2)), λh, λh1, by_contradiction (λh2, h (exists.intro h1 h2))⟩ example : (∀ x, p x) ↔ ¬ (∃ x, ¬ p x) := by { constructor; intros h h1, { cases h1 with _ h2, apply h2, apply h }, { apply by_contradiction, intro, apply h, constructor, assumption} } example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := ⟨λh, exists.elim h (λh1, λh2, λh3, (h3 h1) h2), λh, by_contradiction (λh1, h (λh2, λh3, h1 ⟨h2, h3⟩))⟩ example : (∃ x, p x) ↔ ¬ (∀ x, ¬ p x) := by { constructor; intro h, { cases h, intro h1, apply h1, assumption }, { apply by_contradiction, intro h1, apply h, repeat { intro }, apply h1, constructor, assumption' } } example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := ⟨λh, λh1, show ¬ p h1, from λh2, h (exists.intro h1 h2), λh, λh1, exists.elim h1 (λh2, λh3, (h h2) h3)⟩ example : (¬ ∃ x, p x) ↔ (∀ x, ¬ p x) := by { constructor, { intro h, repeat { intro }, apply h, constructor, assumption' }, { intros h h1, cases h1, apply h, assumption' } } example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := ⟨λh, by_contradiction (λh1, h (λh2, by_contradiction (λh3, h1 ⟨h2, h3⟩))), λh, exists.elim h (λh1, λh2, λh3, h2 (h3 h1))⟩ example : (¬ ∀ x, p x) ↔ (∃ x, ¬ p x) := by { constructor, { intro h, apply by_contradiction, intro h1, apply h, intro, apply by_contradiction, intro, apply h1, constructor, assumption }, { intros h h1, cases h with _ h2, apply h2, apply h1 } } example : (∀ x, p x → r) ↔ (∃ x, p x) → r := ⟨λh, λh1, exists.elim h1 h, λh, λ_, λh1, h ⟨_, h1⟩⟩ example : (∀ x, p x → r) ↔ (∃ x, p x) → r := by { constructor, { intros h h1, cases h1, apply h, assumption' }, { intros h _ _, apply h, constructor, assumption' } } example : (∃ x, p x → r) ↔ (∀ x, p x) → r := ⟨λh, λh1, exists.elim h (λ_, λh3, h3 (h1 _)), λh, by_cases (λh1, ⟨a, λ_, h h1⟩) (λh1, by_contradiction (λh2, h1 (λh3, by_contradiction (λh4, h2 ⟨h3, flip absurd h4⟩))))⟩ include a example : (∃ x, p x → r) ↔ (∀ x, p x) → r := by { constructor, { intros h h1, cases h with _ h2, apply h2, apply h1 }, { intro h, apply by_cases, { intro h1, existsi a, intro, apply h h1 }, { intro h1, apply by_contradiction, intro h2, apply h1, intro, apply by_contradiction, intro, apply h2, constructor, intro, contradiction } } } example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := ⟨λh, λh1, exists.elim h (λh2, λh3, ⟨h2, h3 h1⟩), λh, by_cases (λh1, exists.elim (h h1) (λh2, λh3, ⟨h2, λh1, h3⟩)) (λh1, ⟨a, (λh2, absurd h2 h1)⟩)⟩ example : (∃ x, r → p x) ↔ (r → ∃ x, p x) := by { constructor, { intros h _, cases h with _ h1, constructor, apply h1, assumption }, { intro h, apply by_cases, { intro h1, cases (h h1), constructor, intro, assumption }, { intro, existsi a, intro, contradiction } } } omit a end -- section variables (α : Type) (p q : α → Prop) example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := ⟨λh, ⟨λh1, (h h1).left, λh1, (h h1).right⟩, λh, λh1, ⟨(h.left) h1, (h.right) h1⟩⟩ example : (∀ x, p x ∧ q x) ↔ (∀ x, p x) ∧ (∀ x, q x) := by { constructor, { intro h, constructor; intro h1; { cases (h h1), assumption } }, { intros h _, cases h with h1 h2, constructor, apply h1, apply h2 } } example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := λh, λh1, λh2, (h h2) (h1 h2) example : (∀ x, p x → q x) → (∀ x, p x) → (∀ x, q x) := by { intros h h1 _, apply h, apply h1 } example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := λh, λh1, h.elim (λh2, or.inl (h2 h1)) (λh2, or.inr (h2 h1)) example : (∀ x, p x) ∨ (∀ x, q x) → ∀ x, p x ∨ q x := by { intros h _, cases h, { left, apply h }, { right, apply h } } end -- section open classical variables (α : Type) (p q : α → Prop) variable r : Prop example : α → ((∀ x : α, r) ↔ r) := λh, ⟨λh1, h1 h, λh1, (λh, h1)⟩ example : α → ((∀ x : α, r) ↔ r) := by { intro h, constructor, { intro h1, apply h1 h }, { intros, assumption } } example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := ⟨λh, by_cases (or.inr) (λh1, or.inl (λh2, (h h2).elim id (λh3, absurd h3 h1))), λh, h.elim (λh1, λh2, or.inl (h1 h2)) (λh1, λh2, or.inr h1)⟩ example : (∀ x, p x ∨ r) ↔ (∀ x, p x) ∨ r := by { constructor, { intro h, apply by_cases, { intro, right, assumption }, { intro, left, intro, cases (h _), assumption, contradiction } }, { intros h _, cases h, { left, apply h }, { right, assumption } } } example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := ⟨λh, λh1, λh2, h h2 h1, λh, λh1, λh2, h h2 h1⟩ example : (∀ x, r → p x) ↔ (r → ∀ x, p x) := by { constructor; { intros h h1 h2, apply (h h2 h1) } } end
6a5bfed889cf20261392c7dcf7bab49211ff46ea
4e3bf8e2b29061457a887ac8889e88fa5aa0e34c
/lean/love08_operational_semantics_exercise_solution.lean
5727395175c90fae1cdd9bb7dd7f86a64b379fcf
[]
no_license
mukeshtiwari/logical_verification_2019
9f964c067a71f65eb8884743273fbeef99e6503d
16f62717f55ed5b7b87e03ae0134791a9bef9b9a
refs/heads/master
1,619,158,844,208
1,585,139,500,000
1,585,139,500,000
249,906,380
0
0
null
1,585,118,728,000
1,585,118,727,000
null
UTF-8
Lean
false
false
7,404
lean
/- LoVe Exercise 8: Operational Semantics -/ import .love08_operational_semantics_demo namespace LoVe /- Question 1: Program Equivalence -/ /- For this question, we introduce the notation of program equivalence `p₁ ≈ p₂`. -/ def program_equiv (S₁ S₂ : program) : Prop := ∀s t, (S₁, s) ⟹ t ↔ (S₂, s) ⟹ t local infix ` ≈ ` := program_equiv /- Program equivalence is a equivalence relation, i.e., it is reflexive, symmetric, and transitive. -/ @[refl] lemma program_equiv.refl {S} : S ≈ S := assume s t, show (S, s) ⟹ t ↔ (S, s) ⟹ t, by refl @[symm] lemma program_equiv.symm {S₁ S₂}: S₁ ≈ S₂ → S₂ ≈ S₁ := assume h s t, show (S₂, s) ⟹ t ↔ (S₁, s) ⟹ t, from iff.symm (h s t) @[trans] lemma program_equiv.trans {S₁ S₂ S₃} (h₁₂ : S₁ ≈ S₂) (h₂₃ : S₂ ≈ S₃) : S₁ ≈ S₃ := assume s t, show (S₁, s) ⟹ t ↔ (S₃, s) ⟹ t, from iff.trans (h₁₂ s t) (h₂₃ s t) /- 1.1. Prove the following program equivalences. -/ lemma program_equiv.seq_skip_left {S} : skip ;; S ≈ S := begin intros s t, apply iff.intro, { intro h, cases h, cases h_h₁, assumption }, { intro h, exact big_step.seq big_step.skip h } end lemma program_equiv.seq_skip_right {S} : S ;; skip ≈ S := begin intros s t, apply iff.intro, { intro h, cases h, cases h_h₂, assumption }, { intro h, exact big_step.seq h big_step.skip } end lemma program_equiv.seq_congr {S₁ S₂ T₁ T₂} (hS : S₁ ≈ S₂) (hT : T₁ ≈ T₂) : S₁ ;; T₁ ≈ S₂ ;; T₂ := begin intros s t, apply iff.intro, { intros seq, cases seq, exact big_step.seq ((hS _ _).1 seq_h₁) ((hT _ _).1 seq_h₂) }, { intros seq, cases seq, exact big_step.seq ((hS _ _).2 seq_h₁) ((hT _ _).2 seq_h₂) } end lemma program_equiv.ite_seq_while {b S} : ite b (S ;; while b S) skip ≈ while b S := begin intros s t, apply iff.intro, { intro ite, cases ite, { cases ite_hbody, apply big_step.while_true, repeat { assumption } }, { cases ite_hbody, apply big_step.while_false, repeat { assumption } } }, { intro while, cases while, { apply big_step.ite_true while_hcond, apply big_step.seq, repeat { assumption } }, { apply big_step.ite_false while_hcond, exact big_step.skip } } end /- 1.2. Prove one more equivalence. -/ lemma program_equiv.skip_assign_id {x} : assign x (λs, s x) ≈ skip := begin intros s t, apply iff.intro, { intro asn, cases asn, simp * at * }, { intro sk, cases sk, simp * at * } end /- Question 2: Guarded Command Language (GCL) -/ /- In 1976, E. W. Dijkstra introduced the guarded command language, a minimalistic imperative language with built-in nondeterminism. A grammar for one of its variants is given below: S ::= x := e -- assignment | assert b -- assertion | S ; S -- sequential composition | S | ⋯ | S -- nondeterministic choice | loop S -- nondeterministic iteration Assignment and sequential composition are as in the WHILE language. The other statements have the following semantics: * `assert b` aborts if `b` evaluates to false; otherwise, the command is a no-op. * `S | ⋯ | S` chooses **any** of the branches and executes it, ignoring the other branches. * `loop S` executes `S` **any** number of times. In Lean, GCL is captured by the following inductive type: -/ inductive gcl (σ : Type) : Type | assign : string → (σ → ℕ) → gcl | assert : (σ → Prop) → gcl | seq : gcl → gcl → gcl | choice : list gcl → gcl | loop : gcl → gcl infixr ` ;; `:90 := gcl.seq namespace gcl /- The parameter `σ` abstracts over the state type. It is necessary to work around a bug in Lean. The big-step semantics is defined as follows: -/ inductive big_step : (gcl state × state) → state → Prop | assign {x a s} : big_step (assign x a, s) (s{x ↦ a s}) | assert {b : state → Prop} {s} (hcond : b s) : big_step (assert b, s) s | seq {S T s t u} (h₁ : big_step (S, s) t) (h₂ : big_step (T, t) u) : big_step (S ;; T, s) u | choice {Ss : list (gcl state)} {s t} (i : ℕ) (hless : i < list.length Ss) (hbody : big_step (list.nth_le Ss i hless, s) t) : big_step (choice Ss, s) t | loop_base {S s} : big_step (loop S, s) s | loop_step {S s u} (t) (hbody : big_step (S, s) t) (hrest : big_step (loop S, t) u) : big_step (loop S, s) u /- Convenience syntax: -/ infix ` ~~> `:110 := big_step /- 2.1. Prove the following inversion rules, as we did in the lecture for the WHILE language. -/ @[simp] lemma big_step_assign_iff {x a s t} : (assign x a, s) ~~> t ↔ t = s{x ↦ a s} := begin apply iff.intro, { intro h, cases h, refl }, { intro h, rw h, exact big_step.assign } end @[simp] lemma big_step_assert {b s t} : (assert b, s) ~~> t ↔ t = s ∧ b s := begin apply iff.intro, { intro as, cases as, simp * at * }, { intros h, cases h, rw h_left, apply big_step.assert h_right } end @[simp] lemma big_step_seq_iff {S₁ S₂ s t} : (S₁ ;; S₂, s) ~~> t ↔ (∃u, (S₁, s) ~~> u ∧ (S₂, u) ~~> t) := begin apply iff.intro, { intro h, cases h, apply exists.intro, apply and.intro, repeat { assumption } }, { intro h, cases h, cases h_h, apply big_step.seq, repeat { assumption } } end lemma big_step_loop {S s u} : (loop S, s) ~~> u ↔ (s = u ∨ (∃t, (S, s) ~~> t ∧ (loop S, t) ~~> u)) := begin apply iff.intro, { intro lo, cases lo, { apply or.intro_left, refl }, { apply or.intro_right, apply exists.intro lo_t, apply and.intro, repeat { assumption } } }, { intro h, cases h, { rw h, apply big_step.loop_base }, { cases h, cases h_h, apply big_step.loop_step, repeat { assumption } } } end @[simp] lemma big_step_choice {Ss s t} : (choice Ss, s) ~~> t ↔ (∃(i : ℕ) (hless : i < list.length Ss), (list.nth_le Ss i hless, s) ~~> t) := begin apply iff.intro, { intro ch, cases ch, apply exists.intro ch_i, apply exists.intro ch_hless, assumption }, { intro h, cases h, cases h_h, apply big_step.choice, repeat { assumption } } end /- 2.2. Complete the translation below of a deterministic program to a GCL program, by filling in the `sorry` placeholders below. -/ def of_program : program → gcl state | program.skip := assert (λ_, true) | (program.assign x f) := assign x f | (program.seq S₁ S₂) := of_program S₁ ;; of_program S₂ | (program.ite b S₁ S₂) := choice [seq (assert b) (of_program S₁), seq (assert (λs, ¬ b s)) (of_program S₂)] | (program.while b S) := seq (loop (seq (assert b) (of_program S))) (assert (λs, ¬ b s)) /- 2.3. In the definition of `of_program` above, `skip` is translated to `assert (λ_, true)`. Looking at the big-step semantics of both constructs, we can convince ourselves that it makes sense. Can you think of other correct ways to define the `skip` case? -/ /- Here are two other possibilities: * `loop (assert (λ_, false))` * `assign "x" (λs, s "x")` There are of course infinitely many variants, e.g. `seq` of the above two solutions. -/ end gcl end LoVe
e8fea1cafaa76df347f4a938d87ad07d828fcf71
86d328c7fd9114507f3e8380e2b3d2f83ef6c647
/repl.lean
06a2450b3dc867500b9e46fe0a6a05c842723e79
[]
no_license
forked-from-1kasper/lambda
05ada15e7abdaa5f453bfe3792c086f04f363f76
696363514f3730951a90e86474940135a2339c0b
refs/heads/master
1,623,388,766,920
1,607,249,080,000
1,607,249,080,000
128,524,636
2
1
null
null
null
null
UTF-8
Lean
false
false
5,319
lean
import lambda.parsing lambda.types lambda.unicode import system.io data.buffer.parser open parsing types parser (hiding nat) def mk_env (env : list (string × term)) (t : term) : term := match list.unzip env with | (names, terms) := multi_app (multi_lam names t) terms end def add_to_env (env : list (string × term)) : string × term → sum string (list (string × term)) | (name, t) := if name ∈ env.unzip.fst then sum.inl $ sformat! "error: term “{name}” is already defined" else sum.inr $ env ++ pure (name, t) namespace io.error def avoid_error {α : Type} (m : io α) : io.error → io α | (io.error.other s) := (io.put_str_ln s) >> m | (io.error.sys n) := (io.put_str_ln $ sformat! "System error #{n}") >> m end io.error def help : string := " :help print this summary or command-specific help :quit exit the interpreter :env show variables in the scope :show_depth show current recursion depth :depth [nat] set recursion depth :show_import_depth show current import depth :import_depth [nat] set import depth :clear_env clear environment :load [filename] load file “filename” let name := body creates a new variable “name” with value “body”" structure repl_configuration := (env : list (string × term)) (recursion_depth : nat) (import_depth : nat) def read_from_file : nat → repl_configuration → string → io repl_configuration | 0 conf _ := pure conf | (nat.succ n) conf filename := do filehandle ← io.mk_file_handle filename io.mode.read, new_conf ← io.iterate conf (λ (conf : repl_configuration), do eof ← io.fs.is_eof filehandle, if eof then pure none else do line ← (flip option.get_or_else "") <$> unicode.utf8_to_string <$> io.fs.get_line filehandle, let file_eval := eval conf.recursion_depth ∘ mk_env conf.env, match run_string Command line with | (sum.inr $ repl_command.term t) := do let (evaluated, info) := file_eval t, io.put_str_ln $ sformat! "{line} ⇒ {evaluated} ({info})", pure conf | (sum.inr $ repl_command.bind name t) := match add_to_env conf.env (name, (file_eval t).1) with | sum.inr new_env := pure $ some { conf with env := new_env } | sum.inl error_msg := io.fail error_msg end | (sum.inr $ repl_command.load filename) := some <$> (read_from_file n conf filename) | (sum.inl er) := do io.put_str_ln er, pure none | _ := pure $ some conf end), io.fs.close filehandle, pure new_conf def loop : repl_configuration → io (option repl_configuration) | conf := let repl_eval := eval conf.recursion_depth ∘ mk_env conf.env in do io.put_str "λ> ", line ← io.get_line, match run_string Command line with | (sum.inr repl_command.quit) := pure none | (sum.inr repl_command.help) := io.put_str_ln help >> pure conf | (sum.inr repl_command.env) := do list.foldl (>>) (pure ()) $ list.map (λ (var : string × term), io.put_str_ln $ sformat! "{var.1} := {var.2}") conf.env, pure conf | (sum.inr repl_command.clear_env) := pure $ some { conf with env := [] } | (sum.inr $ repl_command.load filename) := some <$> read_from_file conf.import_depth conf filename | (sum.inr $ repl_command.depth depth) := pure $ some { conf with recursion_depth := depth } | (sum.inr $ repl_command.import_depth depth) := pure $ some { conf with import_depth := depth } | (sum.inr repl_command.show_depth) := do io.put_str_ln $ to_string conf.recursion_depth, pure conf | (sum.inr repl_command.show_import_depth) := do io.put_str_ln $ to_string conf.import_depth, pure conf | (sum.inr $ repl_command.bind name t) := match add_to_env conf.env (name, (repl_eval t).1) with | sum.inr new_env := pure $ some { conf with env := new_env } | sum.inl error_msg := io.put_str_ln error_msg >> pure (some conf) end | (sum.inr $ repl_command.term t) := let res := repl_eval t in do io.put_str_ln $ sformat! "{res.1}\n-- {res.2}", pure conf | (sum.inr repl_command.nothing) := pure conf | (sum.inl er) := do io.put_str_ln er, pure conf end def basic_env : list (string × term) := [("I", term.lam "x" (term.var "x")), ("K", multi_lam ["x", "y"] (term.var "x")), ("S", multi_lam ["f", "g", "x"] (term.app (term.app (term.var "f") (term.var "x")) (term.app (term.var "g") (term.var "x"))))] def initial_conf : repl_configuration := { import_depth := 1000, recursion_depth := 1000, env := basic_env } def load_from_files (files : list string) : io repl_configuration := list.foldl (λ (c : io repl_configuration) (filename : string), do conf ← c, io.put_str_ln $ sformat! "Loading file “{filename}”.", read_from_file conf.import_depth conf filename) (pure initial_conf) files def main : io unit := do args ← io.cmdline_args, conf ← load_from_files args, io.put_str_ln "Type “:help” for help.", io.iterate conf (λ (c : repl_configuration), io.catch (loop c) (io.error.avoid_error $ pure c)) >> pure ()
bc37d603a3f24c23178c122827168bf39507dec4
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/norm.lean
760a5bbe59dd5b6276ceb217aaf225fbc32c7ec9
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
12,055
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import field_theory.primitive_element import linear_algebra.determinant import linear_algebra.matrix.charpoly.coeff import linear_algebra.matrix.to_linear_equiv import field_theory.is_alg_closed.algebraic_closure /-! # Norm for (finite) ring extensions Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`, the determinant of the linear map given by multiplying by `s` gives information about the roots of the minimal polynomial of `s` over `R`. ## Implementation notes Typically, the norm is defined specifically for finite field extensions. The current definition is as general as possible and the assumption that we have fields or that the extension is finite is added to the lemmas as needed. We only define the norm for left multiplication (`algebra.left_mul_matrix`, i.e. `algebra.lmul_left`). For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway. See also `algebra.trace`, which is defined similarly as the trace of `algebra.left_mul_matrix`. ## References * https://en.wikipedia.org/wiki/Field_norm -/ universes u v w variables {R S T : Type*} [comm_ring R] [is_domain R] [comm_ring S] variables [algebra R S] variables {K L F : Type*} [field K] [field L] [field F] variables [algebra K L] [algebra K F] variables {ι : Type w} [fintype ι] open finite_dimensional open linear_map open matrix polynomial open_locale big_operators open_locale matrix namespace algebra variables (R) /-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/ noncomputable def norm : S →* R := linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl lemma norm_eq_one_of_not_exists_basis (h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 := by { rw [norm_apply, linear_map.det], split_ifs with h, refl } variables {R} -- Can't be a `simp` lemma because it depends on a choice of basis lemma norm_eq_matrix_det [decidable_eq ι] (b : basis ι R S) (s : S) : norm R s = matrix.det (algebra.left_mul_matrix b s) := by rw [norm_apply, ← linear_map.det_to_matrix b, to_matrix_lmul_eq] /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/ lemma norm_algebra_map_of_basis (b : basis ι R S) (x : R) : norm R (algebra_map R S x) = x ^ fintype.card ι := begin haveI := classical.dec_eq ι, rw [norm_apply, ← det_to_matrix b, lmul_algebra_map], convert @det_diagonal _ _ _ _ _ (λ (i : ι), x), { ext i j, rw [to_matrix_lsmul, matrix.diagonal] }, { rw [finset.prod_const, finset.card_univ] } end /-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. (If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.) -/ @[simp] lemma norm_algebra_map (x : K) : norm K (algebra_map K L x) = x ^ finrank K L := begin by_cases H : ∃ (s : finset L), nonempty (basis s K L), { rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] }, { rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero], rintros ⟨s, ⟨b⟩⟩, exact H ⟨s, ⟨b⟩⟩ }, end section eq_prod_roots /-- Given `pb : power_basis K S`, then the norm of `pb.gen` is `(-1) ^ pb.dim * coeff (minpoly K pb.gen) 0`. -/ lemma power_basis.norm_gen_eq_coeff_zero_minpoly [algebra K S] (pb : power_basis K S) : norm K pb.gen = (-1) ^ pb.dim * coeff (minpoly K pb.gen) 0 := begin rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix, fintype.card_fin] end /-- Given `pb : power_basis K S`, then the norm of `pb.gen` is `((minpoly K pb.gen).map (algebra_map K F)).roots.prod`. -/ lemma power_basis.norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S) (hf : (minpoly K pb.gen).splits (algebra_map K F)) : algebra_map K F (norm K pb.gen) = ((minpoly K pb.gen).map (algebra_map K F)).roots.prod := begin rw [power_basis.norm_gen_eq_coeff_zero_minpoly, ← pb.nat_degree_minpoly, ring_hom.map_mul, ← coeff_map, prod_roots_eq_coeff_zero_of_monic_of_split (monic_map _ (minpoly.monic (power_basis.is_integral_gen _))) ((splits_id_iff_splits _).2 hf), nat_degree_map, map_pow, ← mul_assoc, ← mul_pow], simp end end eq_prod_roots section eq_zero_iff lemma norm_eq_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x = 0 ↔ x = 0 := begin have hι : nonempty ι := b.index_nonempty, letI := classical.dec_eq ι, rw algebra.norm_eq_matrix_det b, split, { rw ← matrix.exists_mul_vec_eq_zero_iff, rintros ⟨v, v_ne, hv⟩, rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply, algebra.left_mul_matrix_mul_vec_repr] at hv, refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _), { simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i }, { contrapose! v_ne with sum_eq, apply b.equiv_fun.symm.injective, rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } }, { rintro rfl, rw [alg_hom.map_zero, matrix.det_zero hι] }, end lemma norm_ne_zero_iff_of_basis [is_domain S] (b : basis ι R S) {x : S} : algebra.norm R x ≠ 0 ↔ x ≠ 0 := not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b) /-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff [finite_dimensional K L] {x : L} : algebra.norm K x = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) /-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/ @[simp] lemma norm_eq_zero_iff' [finite_dimensional K L] {x : L} : linear_map.det (algebra.lmul K L x) = 0 ↔ x = 0 := algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L) end eq_zero_iff open intermediate_field variable (K) lemma norm_eq_norm_adjoin [finite_dimensional K L] [is_separable K L] (x : L) : norm K x = norm K (adjoin_simple.gen K x) ^ finrank K⟮x⟯ L := begin letI := is_separable_tower_top_of_is_separable K K⟮x⟯ L, let pbL := field.power_basis_of_finite_of_separable K⟮x⟯ L, let pbx := intermediate_field.adjoin.power_basis (is_separable.is_integral K x), rw [← adjoin_simple.algebra_map_gen K x, norm_eq_matrix_det (pbx.basis.smul pbL.basis) _, smul_left_mul_matrix_algebra_map, det_block_diagonal, norm_eq_matrix_det pbx.basis], simp only [finset.card_fin, finset.prod_const], congr, rw [← power_basis.finrank, adjoin_simple.algebra_map_gen K x] end variable {K} section intermediate_field lemma _root_.intermediate_field.adjoin_simple.norm_gen_eq_one {x : L} (hx : ¬_root_.is_integral K x) : norm K (adjoin_simple.gen K x) = 1 := begin rw [norm_eq_one_of_not_exists_basis], contrapose! hx, obtain ⟨s, ⟨b⟩⟩ := hx, refine is_integral_of_mem_of_fg (K⟮x⟯).to_subalgebra _ x _, { exact (submodule.fg_iff_finite_dimensional _).mpr (of_finset_basis b) }, { exact intermediate_field.subset_adjoin K _ (set.mem_singleton x) } end lemma _root_.intermediate_field.adjoin_simple.norm_gen_eq_prod_roots (x : L) (hf : (minpoly K x).splits (algebra_map K F)) : (algebra_map K F) (norm K (adjoin_simple.gen K x)) = ((minpoly K x).map (algebra_map K F)).roots.prod := begin have injKxL : function.injective (algebra_map K⟮x⟯ L) := ring_hom.injective _, by_cases hx : _root_.is_integral K x, swap, { simp [minpoly.eq_zero hx, intermediate_field.adjoin_simple.norm_gen_eq_one hx] }, have hx' : _root_.is_integral K (adjoin_simple.gen K x), { rwa [← is_integral_algebra_map_iff injKxL, adjoin_simple.algebra_map_gen], apply_instance }, rw [← adjoin.power_basis_gen hx, power_basis.norm_gen_eq_prod_roots]; rw [adjoin.power_basis_gen hx, minpoly.eq_of_algebra_map_eq injKxL hx']; try { simp only [adjoin_simple.algebra_map_gen _ _] }, exact hf end end intermediate_field section eq_prod_embeddings open intermediate_field intermediate_field.adjoin_simple polynomial variables (E : Type*) [field E] [algebra K E] lemma norm_eq_prod_embeddings_gen (pb : power_basis K L) (hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) : algebra_map K E (norm K pb.gen) = (@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ, σ pb.gen) := begin letI := classical.dec_eq E, rw [power_basis.norm_gen_eq_prod_roots pb hE, fintype.prod_equiv pb.lift_equiv', finset.prod_mem_multiset, finset.prod_eq_multiset_prod, multiset.to_finset_val, multiset.erase_dup_eq_self.mpr, multiset.map_id], { exact nodup_roots ((separable_map _).mpr hfx) }, { intro x, refl }, { intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] } end lemma norm_eq_prod_roots [is_separable K L] [finite_dimensional K L] {x : L} (hF : (minpoly K x).splits (algebra_map K F)) : algebra_map K F (norm K x) = ((minpoly K x).map (algebra_map K F)).roots.prod ^ finrank K⟮x⟯ L := by rw [norm_eq_norm_adjoin K x, map_pow, intermediate_field.adjoin_simple.norm_gen_eq_prod_roots _ hF] variable (F) lemma prod_embeddings_eq_finrank_pow [algebra L F] [is_scalar_tower K L F][is_alg_closed E] [is_separable K F] [finite_dimensional K F] (pb : power_basis K L) : ∏ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) = ((@@finset.univ (power_basis.alg_hom.fintype pb)).prod (λ σ : L →ₐ[K] E, σ pb.gen)) ^ finrank L F := begin haveI : finite_dimensional L F := finite_dimensional.right K L F, haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F, letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb, letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) := _, rw [fintype.prod_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen), ← finset.univ_sigma_univ, finset.prod_sigma, ← finset.prod_pow], refine finset.prod_congr rfl (λ σ _, _), { letI : algebra L E := σ.to_ring_hom.to_algebra, simp only [finset.prod_const, finset.card_univ], congr, rw alg_hom.card L F E }, { intros σ, simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply, is_scalar_tower.coe_to_alg_hom'] } end variable (K) /-- For `L/K` a finite separable extension of fields and `E` an algebraically closed extension of `K`, the norm (down to `K`) of an element `x` of `L` is equal to the product of the images of `x` over all the `K`-embeddings `σ` of `L` into `E`. -/ lemma norm_eq_prod_embeddings [finite_dimensional K L] [is_separable K L] [is_alg_closed E] {x : L} : algebra_map K E (norm K x) = ∏ σ : L →ₐ[K] E, σ x := begin have hx := is_separable.is_integral K x, rw [norm_eq_norm_adjoin K x, ring_hom.map_pow, ← adjoin.power_basis_gen hx, norm_eq_prod_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _)], { exact (prod_embeddings_eq_finrank_pow L E (adjoin.power_basis hx)).symm }, { haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L, exact is_separable.separable K _ } end lemma is_integral_norm [algebra S L] [algebra S K] [is_scalar_tower S K L] [is_separable K L] [finite_dimensional K L] {x : L} (hx : _root_.is_integral S x) : _root_.is_integral S (norm K x) := begin have hx' : _root_.is_integral K x := is_integral_of_is_scalar_tower _ hx, rw [← is_integral_algebra_map_iff (algebra_map K (algebraic_closure L)).injective, norm_eq_prod_roots], { refine (is_integral.multiset_prod (λ y hy, _)).pow _, rw mem_roots_map (minpoly.ne_zero hx') at hy, use [minpoly S x, minpoly.monic hx], rw ← aeval_def at ⊢ hy, exact minpoly.aeval_of_is_scalar_tower S x y hy }, { apply is_alg_closed.splits_codomain }, { apply_instance } end end eq_prod_embeddings end algebra
be57c1e1828527583f54e413498ede056c0d5f95
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/sigma/basic.lean
954537a403716bc524b28ed9dcb0bfbfa063a870
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
9,891
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 meta.univs import tactic.lint import tactic.ext /-! # Sigma types This file proves basic results about sigma types. A sigma type is a dependent pair type. Like `α × β` but where the type of the second component depends on the first component. This can be seen as a generalization of the sum type `α ⊕ β`: * `α ⊕ β` is made of stuff which is either of type `α` or `β`. * Given `α : ι → Type*`, `sigma α` is made of stuff which is of type `α i` for some `i : ι`. One effectively recovers a type isomorphic to `α ⊕ β` by taking a `ι` with exactly two elements. See `equiv.sum_equiv_sigma_bool`. `Σ x, A x` is notation for `sigma A` (note the difference with the big operator `∑`). `Σ x y z ..., A x y z ...` is notation for `Σ x, Σ y, Σ z, ..., A x y z ...`. Here we have `α : Type*`, `β : α → Type*`, `γ : Π a : α, β a → Type*`, ..., `A : Π (a : α) (b : β a) (c : γ a b) ..., Type*` with `x : α` `y : β x`, `z : γ x y`, ... ## Notes The definition of `sigma` takes values in `Type*`. This effectively forbids `Prop`- valued sigma types. To that effect, we have `psigma`, which takes value in `Sort*` and carries a more complicated universe signature in consequence. -/ section sigma variables {α α₁ α₂ : Type*} {β : α → Type*} {β₁ : α₁ → Type*} {β₂ : α₂ → Type*} namespace sigma instance [inhabited α] [inhabited (β default)] : inhabited (sigma β) := ⟨⟨default, default⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (sigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, sigma.no_confusion h (λe₁ e₂, n e₁)) end @[simp, nolint simp_nf] -- sometimes the built-in injectivity support does not work theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : sigma.mk a₁ b₁ = ⟨a₂, b₂⟩ ↔ (a₁ = a₂ ∧ b₁ == b₂) := by simp @[simp] theorem eta : ∀ x : Σ a, β a, sigma.mk x.1 x.2 = x | ⟨i, x⟩ := rfl @[ext] lemma ext {x₀ x₁ : sigma β} (h₀ : x₀.1 = x₁.1) (h₁ : x₀.2 == x₁.2) : x₀ = x₁ := by { cases x₀, cases x₁, cases h₀, cases h₁, refl } lemma ext_iff {x₀ x₁ : sigma β} : x₀ = x₁ ↔ x₀.1 = x₁.1 ∧ x₀.2 == x₁.2 := by { cases x₀, cases x₁, exact sigma.mk.inj_iff } /-- A specialized ext lemma for equality of sigma types over an indexed subtype. -/ @[ext] lemma subtype_ext {β : Type*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ a, subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨a₀, b₀, hb₀⟩ ⟨a₁, b₁, hb₁⟩ rfl rfl := rfl lemma subtype_ext_iff {β : Type*} {p : α → β → Prop} {x₀ x₁ : Σ a, subtype (p a)} : x₀ = x₁ ↔ x₀.fst = x₁.fst ∧ (x₀.snd : β) = x₁.snd := ⟨λ h, h ▸ ⟨rfl, rfl⟩, λ ⟨h₁, h₂⟩, subtype_ext h₁ h₂⟩ @[simp] theorem «forall» {p : (Σ a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : (Σ a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) (x : sigma β₁) : sigma β₂ := ⟨f₁ x.1, f₂ x.1 x.2⟩ end sigma lemma sigma_mk_injective {i : α} : function.injective (@sigma.mk α β i) | _ _ rfl := rfl lemma function.injective.sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.injective f₁) (h₂ : ∀ a, function.injective (f₂ a)) : function.injective (sigma.map f₁ f₂) | ⟨i, x⟩ ⟨j, y⟩ h := begin obtain rfl : i = j, from h₁ (sigma.mk.inj_iff.mp h).1, obtain rfl : x = y, from h₂ i (sigma_mk_injective h), refl end lemma function.injective.of_sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h : function.injective (sigma.map f₁ f₂)) (a : α₁) : function.injective (f₂ a) := λ x y hxy, sigma_mk_injective $ @h ⟨a, x⟩ ⟨a, y⟩ (sigma.ext rfl (heq_iff_eq.2 hxy)) lemma function.injective.sigma_map_iff {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.injective f₁) : function.injective (sigma.map f₁ f₂) ↔ ∀ a, function.injective (f₂ a) := ⟨λ h, h.of_sigma_map, h₁.sigma_map⟩ lemma function.surjective.sigma_map {f₁ : α₁ → α₂} {f₂ : Πa, β₁ a → β₂ (f₁ a)} (h₁ : function.surjective f₁) (h₂ : ∀ a, function.surjective (f₂ a)) : function.surjective (sigma.map f₁ f₂) := begin simp only [function.surjective, sigma.forall, h₁.forall], exact λ i, (h₂ _).forall.2 (λ x, ⟨⟨i, x⟩, rfl⟩) end /-- Interpret a function on `Σ x : α, β x` as a dependent function with two arguments. This also exists as an `equiv` as `equiv.Pi_curry γ`. -/ def sigma.curry {γ : Π a, β a → Type*} (f : Π x : sigma β, γ x.1 x.2) (x : α) (y : β x) : γ x y := f ⟨x,y⟩ /-- Interpret a dependent function with two arguments as a function on `Σ x : α, β x`. This also exists as an `equiv` as `(equiv.Pi_curry γ).symm`. -/ def sigma.uncurry {γ : Π a, β a → Type*} (f : Π x (y : β x), γ x y) (x : sigma β) : γ x.1 x.2 := f x.1 x.2 @[simp] lemma sigma.uncurry_curry {γ : Π a, β a → Type*} (f : Π x : sigma β, γ x.1 x.2) : sigma.uncurry (sigma.curry f) = f := funext $ λ ⟨i, j⟩, rfl @[simp] lemma sigma.curry_uncurry {γ : Π a, β a → Type*} (f : Π x (y : β x), γ x y) : sigma.curry (sigma.uncurry f) = f := rfl /-- Convert a product type to a Σ-type. -/ def prod.to_sigma {α β} (p : α × β) : Σ _ : α, β := ⟨p.1, p.2⟩ @[simp] lemma prod.fst_to_sigma {α β} (x : α × β) : (prod.to_sigma x).fst = x.fst := rfl @[simp] lemma prod.snd_to_sigma {α β} (x : α × β) : (prod.to_sigma x).snd = x.snd := rfl @[simp] lemma prod.to_sigma_mk {α β} (x : α) (y : β) : (x, y).to_sigma = ⟨x, y⟩ := rfl -- we generate this manually as `@[derive has_reflect]` fails @[instance] protected meta def {u v} sigma.reflect [reflected_univ.{u}] [reflected_univ.{v}] {α : Type u} (β : α → Type v) [reflected _ α] [reflected _ β] [hα : has_reflect α] [hβ : Π i, has_reflect (β i)] : has_reflect (Σ a, β a) := λ ⟨a, b⟩, (by reflect_name : reflected _ @sigma.mk.{u v}).subst₄ `(α) `(β) `(a) `(b) end sigma section psigma variables {α : Sort*} {β : α → Sort*} namespace psigma /-- Nondependent eliminator for `psigma`. -/ def elim {γ} (f : ∀ a, β a → γ) (a : psigma β) : γ := psigma.cases_on a f @[simp] theorem elim_val {γ} (f : ∀ a, β a → γ) (a b) : psigma.elim f ⟨a, b⟩ = f a b := rfl instance [inhabited α] [inhabited (β default)] : inhabited (psigma β) := ⟨⟨default, default⟩⟩ instance [h₁ : decidable_eq α] [h₂ : ∀a, decidable_eq (β a)] : decidable_eq (psigma β) | ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ := match a₁, b₁, a₂, b₂, h₁ a₁ a₂ with | _, b₁, _, b₂, is_true (eq.refl a) := match b₁, b₂, h₂ a b₁ b₂ with | _, _, is_true (eq.refl b) := is_true rfl | b₁, b₂, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n $ eq_of_heq e₂)) end | a₁, _, a₂, _, is_false n := is_false (assume h, psigma.no_confusion h (λe₁ e₂, n e₁)) end theorem mk.inj_iff {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂} : @psigma.mk α β a₁ b₁ = @psigma.mk α β a₂ b₂ ↔ (a₁ = a₂ ∧ b₁ == b₂) := iff.intro psigma.mk.inj $ assume ⟨h₁, h₂⟩, match a₁, a₂, b₁, b₂, h₁, h₂ with _, _, _, _, eq.refl a, heq.refl b := rfl end @[ext] lemma ext {x₀ x₁ : psigma β} (h₀ : x₀.1 = x₁.1) (h₁ : x₀.2 == x₁.2) : x₀ = x₁ := by { cases x₀, cases x₁, cases h₀, cases h₁, refl } lemma ext_iff {x₀ x₁ : psigma β} : x₀ = x₁ ↔ x₀.1 = x₁.1 ∧ x₀.2 == x₁.2 := by { cases x₀, cases x₁, exact psigma.mk.inj_iff } @[simp] theorem «forall» {p : (Σ' a, β a) → Prop} : (∀ x, p x) ↔ (∀ a b, p ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem «exists» {p : (Σ' a, β a) → Prop} : (∃ x, p x) ↔ (∃ a b, p ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ /-- A specialized ext lemma for equality of psigma types over an indexed subtype. -/ @[ext] lemma subtype_ext {β : Sort*} {p : α → β → Prop} : ∀ {x₀ x₁ : Σ' a, subtype (p a)}, x₀.fst = x₁.fst → (x₀.snd : β) = x₁.snd → x₀ = x₁ | ⟨a₀, b₀, hb₀⟩ ⟨a₁, b₁, hb₁⟩ rfl rfl := rfl lemma subtype_ext_iff {β : Sort*} {p : α → β → Prop} {x₀ x₁ : Σ' a, subtype (p a)} : x₀ = x₁ ↔ x₀.fst = x₁.fst ∧ (x₀.snd : β) = x₁.snd := ⟨λ h, h ▸ ⟨rfl, rfl⟩, λ ⟨h₁, h₂⟩, subtype_ext h₁ h₂⟩ variables {α₁ : Sort*} {α₂ : Sort*} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} /-- Map the left and right components of a sigma -/ def map (f₁ : α₁ → α₂) (f₂ : Πa, β₁ a → β₂ (f₁ a)) : psigma β₁ → psigma β₂ | ⟨a, b⟩ := ⟨f₁ a, f₂ a b⟩ end psigma end psigma
e382cfa93c4be9de56e6607c085322231894926b
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/is_limit.lean
56ce006946f2a9b7e8b953e92fa9609437daf8eb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
38,203
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.adjunction.basic import category_theory.limits.cones /-! # 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 * `is_limit c`, for `c : cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, See also `category_theory.limits.has_limits` which further builds: * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit 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 theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits -- declare the `v`'s first; see `category_theory.category` for an explanation universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ variables {J : Type u₁} [category.{v₁} J] {K : Type u₂} [category.{v₂} K] variables {C : Type u₃} [category.{v₃} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. See <https://stacks.math.columbia.edu/tag/002E>. -/ @[nolint has_nonempty_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- 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 : is_limit t) (α : F ⟶ G) : s.X ⟶ t.X := P.lift ((cones.postcompose α).obj s) @[simp, reassoc] lemma map_π {F G : J ⥤ C} (c : cone F) {d : cone G} (hd : is_limit d) (α : F ⟶ G) (j : J) : hd.map c α ≫ d.π.app j = c.π.app j ≫ α.app j := fac _ _ _ lemma lift_self {c : cone F} (t : is_limit c) : t.lift c = 𝟙 c.X := (t.uniq _ _ (λ j, id_comp _)).symm /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ @[simps] def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Restating the definition of a limit cone in terms of the ∃! operator. -/ lemma exists_unique {t : cone F} (h : is_limit t) (s : cone F) : ∃! (l : s.X ⟶ t.X), ∀ j, l ≫ t.π.app j = s.π.app j := ⟨h.lift s, h.fac s, h.uniq s⟩ /-- Noncomputably make a colimit cocone from the existence of unique factorizations. -/ def of_exists_unique {t : cone F} (ht : ∀ s : cone F, ∃! l : s.X ⟶ t.X, ∀ j, l ≫ t.π.app j = s.π.app j) : is_limit t := by { choose s hs hs' using ht, exact ⟨s, hs, hs'⟩ } /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ @[simps] def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Any cone morphism between limit cones is an isomorphism. -/ lemma hom_is_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) (f : s ⟶ t) : is_iso f := ⟨⟨P.lift_cone_morphism t, ⟨P.uniq_cone_morphism, Q.uniq_cone_morphism⟩⟩⟩ /-- Limits of `F` are unique up to isomorphism. -/ def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma cone_point_unique_up_to_iso_hom_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).hom ≫ t.π.app j = s.π.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma cone_point_unique_up_to_iso_inv_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).inv ≫ s.π.app j = t.π.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_hom {r s t : cone F} (P : is_limit s) (Q : is_limit t) : P.lift r ≫ (cone_point_unique_up_to_iso P Q).hom = Q.lift r := Q.uniq _ _ (by simp) @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_inv {r s t : cone F} (P : is_limit s) (Q : is_limit t) : Q.lift r ≫ (cone_point_unique_up_to_iso 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 of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) @[simp] lemma of_iso_limit_lift {r t : cone F} (P : is_limit r) (i : r ≅ t) (s) : (P.of_iso_limit i).lift s = P.lift s ≫ i.hom.hom := rfl /-- Isomorphism of cones preserves whether or not they are limiting cones. -/ def equiv_iso_limit {r t : cone F} (i : r ≅ t) : is_limit r ≃ is_limit t := { to_fun := λ h, h.of_iso_limit i, inv_fun := λ h, h.of_iso_limit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_limit_apply {r t : cone F} (i : r ≅ t) (P : is_limit r) : equiv_iso_limit i P = P.of_iso_limit i := rfl @[simp] lemma equiv_iso_limit_symm_apply {r t : cone F} (i : r ≅ t) (P : is_limit t) : (equiv_iso_limit i).symm P = P.of_iso_limit 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 of_point_iso {r t : cone F} (P : is_limit r) [i : is_iso (P.lift t)] : is_limit t := of_iso_limit P begin haveI : is_iso (P.lift_cone_morphism t).hom := i, haveI : is_iso (P.lift_cone_morphism t) := cones.cone_iso_of_hom_iso _, symmetry, apply as_iso (P.lift_cone_morphism t), end variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (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 of_right_adjoint {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (h.obj c) := mk_cone_morphism (λ s, (adjunction.of_right_adjoint h).hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_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 of_cone_equiv {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} : is_limit (h.functor.obj c) ≃ is_limit c := { to_fun := λ P, of_iso_limit (of_right_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_right_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cone_equiv_apply_desc {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit (h.functor.obj c)) (s) : (of_cone_equiv h P).lift s = ((h.unit_iso.hom.app s).hom ≫ (h.functor.inv.map (P.lift_cone_morphism (h.functor.obj s))).hom) ≫ (h.unit_iso.inv.app c).hom := rfl @[simp] lemma of_cone_equiv_symm_apply_desc {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit c) (s) : ((of_cone_equiv h).symm P).lift s = (h.counit_iso.inv.app s).hom ≫ (h.functor.map (P.lift_cone_morphism (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 postcompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone F) : is_limit ((cones.postcompose α.hom).obj c) ≃ is_limit c := of_cone_equiv (cones.postcompose_equivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone G) : is_limit ((cones.postcompose α.inv).obj c) ≃ is_limit c := postcompose_hom_equiv α.symm c /-- Constructing an equivalence `is_limit c ≃ is_limit d` from a natural isomorphism between the underlying functors, and then an isomorphism between `c` transported along this and `d`. -/ def equiv_of_nat_iso_of_iso {F G : J ⥤ C} (α : F ≅ G) (c : cone F) (d : cone G) (w : (cones.postcompose α.hom).obj c ≅ d) : is_limit c ≃ is_limit d := (postcompose_hom_equiv α _).symm.trans (equiv_iso_limit w) /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : s.X ≅ t.X := { hom := Q.map s w.hom, inv := P.map t w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy), } @[reassoc] lemma cone_points_iso_of_nat_iso_hom_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).hom ≫ t.π.app j = s.π.app j ≫ w.hom.app j := by simp @[reassoc] lemma cone_points_iso_of_nat_iso_inv_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).inv ≫ s.π.app j = t.π.app j ≫ w.inv.app j := by simp @[reassoc] lemma lift_comp_cone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {r s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : P.lift r ≫ (cone_points_iso_of_nat_iso P Q w).hom = Q.map r w.hom := Q.hom_ext (by simp) @[reassoc] lemma lift_comp_cone_points_iso_of_nat_iso_inv {F G : J ⥤ C} {r s : cone G} {t : cone F} (P : is_limit t) (Q : is_limit s) (w : F ≅ G) : Q.lift r ≫ (cone_points_iso_of_nat_iso P Q w).inv = P.map r w.inv := P.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cone F} (P : is_limit s) (e : K ≌ J) : is_limit (s.whisker e.functor) := of_right_adjoint (cones.whiskering_equivalence e).functor P /-- If `s : cone F` whiskered by an equivalence `e` is a limit cone, so is `s`. -/ def of_whisker_equivalence {s : cone F} (e : K ≌ J) (P : is_limit (s.whisker e.functor)) : is_limit s := equiv_iso_limit ((cones.whiskering_equivalence e).unit_iso.app s).symm (of_right_adjoint (cones.whiskering_equivalence e).inverse P : _) /-- Given an equivalence of diagrams `e`, `s` is a limit cone iff `s.whisker e.functor` is. -/ def whisker_equivalence_equiv {s : cone F} (e : K ≌ J) : is_limit s ≃ is_limit (s.whisker e.functor) := ⟨λ h, h.whisker_equivalence e, of_whisker_equivalence e, by tidy, by tidy⟩ /-- We can prove two cone points `(s : cone F).X` and `(t.cone G).X` 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 cone_points_iso_of_equivalence {F : J ⥤ C} {s : cone F} {G : K ⥤ C} {t : cone G} (P : is_limit s) (Q : is_limit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := Q.lift ((cones.equivalence_of_reindexing e.symm w').functor.obj s), inv := P.lift ((cones.equivalence_of_reindexing e w).functor.obj t), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cone.whisker_π, limits.cones.postcompose_obj_π, fac, whisker_left_app, assoc, id_comp, inv_fun_id_assoc_hom_app, fac_assoc, nat_trans.comp_app], rw [counit_app_functor, ←functor.comp_map, w.hom.naturality], simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : ulift.{u₁} (W ⟶ t.X : Type v₃) ≅ (const J).obj W ⟶ F := { hom := λ f, (t.extend f.down).π, inv := λ π, ⟨h.lift { X := W, π := π }⟩, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : ulift.{u₁} (W ⟶ t.X)) : (is_limit.hom_iso 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 vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ⋙ ulift_functor.{u₁} ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ulift.{u₁} ((W ⟶ t.X) : Type v₃) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- 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 of_faithful {t : cone F} {D : Type u₄} [category.{v₄} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u₄} [category.{v₄} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := begin apply postcompose_inv_equiv (iso_whisker_left K h : _) (G.map_cone c) _, apply t.of_iso_limit (postcompose_whisker_left_map_cone h.symm c).symm, end /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : yoneda.obj X ⋙ ulift_functor.{u₁} ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) ⟨f⟩ } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := (h.inv.app (op s.X) s.π).down @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, convert congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, exact ulift.up_down _ end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_arg ulift.down (congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) ⟨f⟩ : _) /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom 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`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr' with j, have t := congr_fun (h.hom.naturality f.op) ⟨𝟙 X⟩, dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ⋙ ulift_functor.{u₁} ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp [cone.extend], cases s, congr' with j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. See <https://stacks.math.columbia.edu/tag/002F>. -/ @[nolint has_nonempty_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp,reassoc] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- 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 : is_colimit s) (t : cocone G) (α : F ⟶ G) : s.X ⟶ t.X := P.desc ((cocones.precompose α).obj t) @[simp, reassoc] lemma ι_map {F G : J ⥤ C} {c : cocone F} (hc : is_colimit c) (d : cocone G) (α : F ⟶ G) (j : J) : c.ι.app j ≫ is_colimit.map hc d α = α.app j ≫ d.ι.app j := fac _ _ _ @[simp] lemma desc_self {t : cocone F} (h : is_colimit t) : h.desc t = 𝟙 t.X := (h.uniq _ _ (λ j, comp_id _)).symm /- Repackaging the definition in terms of cocone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cocone. -/ @[simps] def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism 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. -/ lemma exists_unique {t : cocone F} (h : is_colimit t) (s : cocone F) : ∃! (d : t.X ⟶ s.X), ∀ 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 of_exists_unique {t : cocone F} (ht : ∀ s : cocone F, ∃! d : t.X ⟶ s.X, ∀ j, t.ι.app j ≫ d = s.ι.app j) : is_colimit t := by { choose s hs hs' using ht, exact ⟨s, hs, hs'⟩ } /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ @[simps] def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Any cocone morphism between colimit cocones is an isomorphism. -/ lemma hom_is_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (f : s ⟶ t) : is_iso f := ⟨⟨Q.desc_cocone_morphism s, ⟨P.uniq_cocone_morphism, Q.uniq_cocone_morphism⟩⟩⟩ /-- Colimits of `F` are unique up to isomorphism. -/ def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_hom {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : s.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).hom = t.ι.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_inv {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : t.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).inv = s.ι.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma cocone_point_unique_up_to_iso_hom_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso P Q).hom ≫ Q.desc r = P.desc r := P.uniq _ _ (by simp) @[simp, reassoc] lemma cocone_point_unique_up_to_iso_inv_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso 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 of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) @[simp] lemma of_iso_colimit_desc {r t : cocone F} (P : is_colimit r) (i : r ≅ t) (s) : (P.of_iso_colimit i).desc s = i.inv.hom ≫ P.desc s := rfl /-- Isomorphism of cocones preserves whether or not they are colimiting cocones. -/ def equiv_iso_colimit {r t : cocone F} (i : r ≅ t) : is_colimit r ≃ is_colimit t := { to_fun := λ h, h.of_iso_colimit i, inv_fun := λ h, h.of_iso_colimit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_colimit_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit r) : equiv_iso_colimit i P = P.of_iso_colimit i := rfl @[simp] lemma equiv_iso_colimit_symm_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit t) : (equiv_iso_colimit i).symm P = P.of_iso_colimit 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 of_point_iso {r t : cocone F} (P : is_colimit r) [i : is_iso (P.desc t)] : is_colimit t := of_iso_colimit P begin haveI : is_iso (P.desc_cocone_morphism t).hom := i, haveI : is_iso (P.desc_cocone_morphism t) := cocones.cocone_iso_of_hom_iso _, apply as_iso (P.desc_cocone_morphism t), end variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ 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 of_left_adjoint {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (h.obj c) := mk_cocone_morphism (λ s, ((adjunction.of_left_adjoint h).hom_equiv c s).symm (t.desc_cocone_morphism _)) (λ s m, (adjunction.hom_equiv_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 of_cocone_equiv {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} : is_colimit (h.functor.obj c) ≃ is_colimit c := { to_fun := λ P, of_iso_colimit (of_left_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_left_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cocone_equiv_apply_desc {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit (h.functor.obj c)) (s) : (of_cocone_equiv h P).desc s = (h.unit.app c).hom ≫ (h.inverse.map (P.desc_cocone_morphism (h.functor.obj s))).hom ≫ (h.unit_inv.app s).hom := rfl @[simp] lemma of_cocone_equiv_symm_apply_desc {D : Type u₄} [category.{v₄} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit c) (s) : ((of_cocone_equiv h).symm P).desc s = (h.functor.map (P.desc_cocone_morphism (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 precompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone G) : is_colimit ((cocones.precompose α.hom).obj c) ≃ is_colimit c := of_cocone_equiv (cocones.precompose_equivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone F) : is_colimit ((cocones.precompose α.inv).obj c) ≃ is_colimit c := precompose_hom_equiv α.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 equiv_of_nat_iso_of_iso {F G : J ⥤ C} (α : F ≅ G) (c : cocone F) (d : cocone G) (w : (cocones.precompose α.inv).obj c ≅ d) : is_colimit c ≃ is_colimit d := (precompose_inv_equiv α _).symm.trans (equiv_iso_colimit w) /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cocone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : s.X ≅ t.X := { hom := P.map t w.hom, inv := Q.map s w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy) } @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : s.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).hom = w.hom.app j ≫ t.ι.app j := by simp @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_inv {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : t.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).inv = w.inv.app j ≫ s.ι.app j := by simp @[reassoc] lemma cocone_points_iso_of_nat_iso_hom_desc {F G : J ⥤ C} {s : cocone F} {r t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : (cocone_points_iso_of_nat_iso P Q w).hom ≫ Q.desc r = P.map _ w.hom := P.hom_ext (by simp) @[reassoc] lemma cocone_points_iso_of_nat_iso_inv_desc {F G : J ⥤ C} {s : cocone G} {r t : cocone F} (P : is_colimit t) (Q : is_colimit s) (w : F ≅ G) : (cocone_points_iso_of_nat_iso P Q w).inv ≫ P.desc r = Q.map _ w.inv := Q.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cocone F` is a colimit cocone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cocone F} (P : is_colimit s) (e : K ≌ J) : is_colimit (s.whisker e.functor) := of_left_adjoint (cocones.whiskering_equivalence e).functor P /-- If `s : cocone F` whiskered by an equivalence `e` is a colimit cocone, so is `s`. -/ def of_whisker_equivalence {s : cocone F} (e : K ≌ J) (P : is_colimit (s.whisker e.functor)) : is_colimit s := equiv_iso_colimit ((cocones.whiskering_equivalence e).unit_iso.app s).symm (of_left_adjoint (cocones.whiskering_equivalence e).inverse P : _) /-- Given an equivalence of diagrams `e`, `s` is a colimit cocone iff `s.whisker e.functor` is. -/ def whisker_equivalence_equiv {s : cocone F} (e : K ≌ J) : is_colimit s ≃ is_colimit (s.whisker e.functor) := ⟨λ h, h.whisker_equivalence e, of_whisker_equivalence e, by tidy, by tidy⟩ /-- We can prove two cocone points `(s : cocone F).X` and `(t.cocone G).X` 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 cocone_points_iso_of_equivalence {F : J ⥤ C} {s : cocone F} {G : K ⥤ C} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := P.desc ((cocones.equivalence_of_reindexing e w).functor.obj t), inv := Q.desc ((cocones.equivalence_of_reindexing e.symm w').functor.obj s), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cocone.whisker_ι, fac, inv_fun_id_assoc_inv_app, whisker_left_app, assoc, comp_id, limits.cocones.precompose_obj_ι, fac_assoc, nat_trans.comp_app], rw [counit_inv_app_functor, ←functor.comp_map, ←w.inv.naturality_assoc], dsimp, simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : ulift.{u₁} (t.X ⟶ W : Type v₃) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f.down).ι, inv := λ ι, ⟨h.desc { X := W, ι := ι }⟩, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : ulift (t.X ⟶ W)) : (is_colimit.hom_iso 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 vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ⋙ ulift_functor.{u₁} ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ulift.{u₁} ((t.X ⟶ W) : Type v₃) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- 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 of_faithful {t : cocone F} {D : Type u₄} [category.{v₄} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a colimit implies `G.map_cone c` is also a colimit. -/ def map_cocone_equiv {D : Type u₄} [category.{v₄} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cocone K} (t : is_colimit (F.map_cocone c)) : is_colimit (G.map_cocone c) := begin apply is_colimit.of_iso_colimit _ (precompose_whisker_left_map_cocone h c), apply (precompose_inv_equiv (iso_whisker_left K h : _) _).symm t, end /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ⋙ ulift_functor.{u₁} ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y ⟨f⟩ } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := (h.inv.app s.X s.ι).down @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, convert congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, exact ulift.up_down _ end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_arg ulift.down (congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) ⟨f⟩ : _) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom 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`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr' with j, have t := congr_fun (h.hom.naturality f) ⟨𝟙 X⟩, dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ⋙ ulift_functor.{u₁} ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp [cocone.extend], cases s, congr' with j, exact w j, end } end end is_colimit end category_theory.limits
e5ac73641e2066ae0aa9ec9890424747b7202317
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/topologie-espaces-normés/cpge_ten_03.lean
29ca022794f4258f7e02a3b0100707c02cd254f2
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
365
lean
import topology.basic import algebra.module.basic import algebra.module.submodule import analysis.normed_space.basic -- Montrer que si un sous-espace vectoriel F d'un espace normé E est ouvert alors F = E . theorem exo {R E: Type*} [normed_field R] [normed_group E] [normed_space R E] (F: subspace R E): is_open F.carrier -> forall x: E, set.mem x F := sorry
a538c32a48bc9eeafcaf30095ce657725603941a
f20db13587f4dd28a4b1fbd31953afd491691fa0
/tests/lean/interactive/rb_map_ts.lean
3ad10741c51960651c778dae6e3e062380c84343
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
2,177
lean
meta def mytac := state_t (name_map nat) tactic meta instance : monad mytac := state_t.monad _ _ meta instance : monad.has_monad_lift tactic mytac := monad.monad_transformer_lift (state_t (name_map nat)) tactic meta instance (α : Type) : has_coe (tactic α) (mytac α) := ⟨monad.monad_lift⟩ namespace mytac meta def step {α : Type} (t : mytac α) : mytac unit := t >> return () meta def istep {α : Type} (line0 col0 line col : nat) (t : mytac α) : mytac unit := λ v s, result.cases_on (@scope_trace _ line col (λ_, t v s)) (λ ⟨a, v⟩ new_s, result.success ((), v) new_s) (λ opt_msg_thunk e new_s, match opt_msg_thunk with | some msg_thunk := let msg := λ _ : unit, msg_thunk () ++ format.line ++ to_fmt "value: " ++ to_fmt v ++ format.line ++ to_fmt "state:" ++ format.line ++ new_s^.to_format in interaction_monad.result.exception (some msg) (some ⟨line, col⟩) new_s | none := interaction_monad.silent_fail new_s end) meta def execute (tac : mytac unit) : tactic unit := tac (name_map.mk nat) >> return () meta def save_info (p : pos) : mytac unit := do v ← state_t.read, s ← tactic.read, tactic.save_info_thunk p (λ _, to_fmt "Custom state: " ++ to_fmt v ++ format.line ++ tactic_state.to_format s) namespace interactive meta def intros : mytac unit := tactic.intros >> return () meta def constructor : mytac unit := tactic.constructor >> return () meta def trace (s : string) : mytac unit := tactic.trace s meta def assumption : mytac unit := tactic.assumption open lean.parser open interactive open interactive.types meta def add (n : parse ident) (v : nat) : mytac unit := do m ← state_t.read, state_t.write (m^.insert n v) end interactive end mytac lemma ex₁ (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, add x 10, trace "test", --^ "command": "info" constructor, add y 20, assumption, --^ "command": "info" assumption end #print ex₁ lemma ex₂ (p q : Prop) : p → q → p ∧ q := begin [mytac] intros, add x 10, trace "test", constructor, add y 20, assumption, --^ "command": "info" assumption end #print ex₂
111ec706fb49ce4342828ce75cd53a2a21107e28
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.5.lean
033ff5d46e9ae6adb84b0661f01b0f91f17cea25
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
528
lean
/- page 78 -/ import standard import data.nat open nat inductive weekday : Type := | sunday : weekday | monday : weekday | tuesday : weekday | wednesday : weekday | thursday : weekday | friday : weekday | saturday : weekday -- BEGIN namespace weekday local abbreviation cases_on := @weekday.cases_on definition number_of_day (d : weekday) : nat := cases_on d 1 2 3 4 5 6 7 end weekday eval weekday.number_of_day weekday.sunday open weekday (renaming cases_on → cases_on) eval number_of_day sunday check cases_on -- END
801fe2eb3c74115a7f7d1b1c6d2f8d49fb2d7cd5
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/set.lean
a024e02950ae41d15de0ec3513475e832e870a43
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
1,473
lean
universe u -- Type of subsets of α. A subset of α is a predicate over α def set2 (α : Type u) : Type u := α → Prop --#check @set2 --#check @set variable α : Type u def elem (x:α) (a : set α) := a x notation e ∈ a := elem e a lemma setext : ∀ {a b : set α}, (∀ (x:α), x ∈ a ↔ x ∈ b) → a = b := begin intros a b H, apply funext, intros x, apply propext, apply H end definition empty2 : set α := λ_, false --#check @empty2 --#check @empty --notation ∅ := empty2 def inter (a b : set α) : set α := λ x, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b lemma inter_self : ∀ (a : set α), a ∩ a = a := begin intros a, apply funext, intros x, apply propext, split, {intros H, cases H with H1 H2, assumption}, {intros H, split; assumption} end lemma inter_empty : ∀ (a : set α), a ∩ ∅ = ∅ := begin intros a, apply funext, intros x, apply propext, split, {intros H, cases H with H1 H2, assumption}, {intros H, split, {exfalso, assumption}, {assumption}} end lemma empty_lemma : ∀ (a : set α), ∅ ∩ a = ∅ := begin intros a, apply funext, intros x, apply propext, split, {intros H, cases H with H1 H2, assumption}, {intros H, split, {assumption}, {exfalso, assumption}} end lemma inter_comm : ∀ (a b : set α), a ∩ b = b ∩ a := begin intros a b, apply funext, intros x, apply propext, split; intros H; cases H with H1 H2; split; assumption end
6c840f568a1e3f1a0229f497b87c2e27391c25a9
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/inner_product_space/spectrum.lean
e79c6c18ddf81b422fa9669954451ec8f2aa00c1
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,840
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 analysis.inner_product_space.rayleigh import analysis.inner_product_space.pi_L2 /-! # 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: * `is_self_adjoint.conj_eigenvalue_eq_self`: the eigenvalues are real * `is_self_adjoint.orthogonal_family_eigenspaces`: the eigenspaces are orthogonal * `is_self_adjoint.orthogonal_supr_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 `is_self_adjoint.diagonalization` provides a linear isometry equivalence `E` to the direct sum of the eigenspaces of `T`. The theorem `is_self_adjoint.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 `is_self_adjoint.eigenvector_basis` provides an orthonormal basis for `E` consisting of eigenvectors of `T`, with `is_self_adjoint.eigenvalues` giving the corresponding list of eigenvalues, as real numbers. The definition `is_self_adjoint.diagonalization_basis` gives the associated linear isometry equivalence from `E` to Euclidean space, and the theorem `is_self_adjoint.diagonalization_basis_apply_self_apply` states that, when `T` is transferred via this equivalence to an operator on Euclidean space, it acts diagonally. 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 -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] [dec_𝕜 : decidable_eq 𝕜] variables {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 E _ x y open_locale big_operators complex_conjugate open module.End namespace inner_product_space namespace is_self_adjoint variables {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) include hT /-- A self-adjoint operator preserves orthogonal complements of its eigenspaces. -/ lemma invariant_orthogonal_eigenspace (μ : 𝕜) (v : E) (hv : v ∈ (eigenspace T μ)ᗮ) : T v ∈ (eigenspace T μ)ᗮ := begin intros w hw, have : T w = (μ:𝕜) • w := by rwa mem_eigenspace_iff at hw, simp [← hT w, this, inner_smul_left, hv w hw] end /-- The eigenvalues of a self-adjoint operator are real. -/ lemma conj_eigenvalue_eq_self {μ : 𝕜} (hμ : has_eigenvalue T μ) : conj μ = μ := begin obtain ⟨v, hv₁, hv₂⟩ := hμ.exists_has_eigenvector, rw mem_eigenspace_iff at hv₁, simpa [hv₂, inner_smul_left, inner_smul_right, hv₁] using hT v v end /-- The eigenspaces of a self-adjoint operator are mutually orthogonal. -/ lemma orthogonal_family_eigenspaces : @orthogonal_family 𝕜 _ _ _ _ (λ μ, eigenspace T μ) _ (λ μ, (eigenspace T μ).subtypeₗᵢ) := begin rintros μ ν hμν ⟨v, hv⟩ ⟨w, hw⟩, by_cases hv' : v = 0, { simp [hv'] }, have H := hT.conj_eigenvalue_eq_self (has_eigenvalue_of_has_eigenvector ⟨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 end lemma orthogonal_family_eigenspaces' : @orthogonal_family 𝕜 _ _ _ _ (λ μ : eigenvalues T, eigenspace T μ) _ (λ μ, (eigenspace T μ).subtypeₗᵢ) := hT.orthogonal_family_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. -/ lemma orthogonal_supr_eigenspaces_invariant ⦃v : E⦄ (hv : v ∈ (⨆ μ, eigenspace T μ)ᗮ) : T v ∈ (⨆ μ, eigenspace T μ)ᗮ := begin rw ← submodule.infi_orthogonal at ⊢ hv, exact T.infi_invariant hT.invariant_orthogonal_eigenspace v hv end /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on an inner product space has no eigenvalues. -/ lemma orthogonal_supr_eigenspaces (μ : 𝕜) : eigenspace (T.restrict hT.orthogonal_supr_eigenspaces_invariant) μ = ⊥ := begin set p : submodule 𝕜 E := (⨆ μ, eigenspace T μ)ᗮ, refine eigenspace_restrict_eq_bot hT.orthogonal_supr_eigenspaces_invariant _, have H₂ : p ≤ (eigenspace T μ)ᗮ := submodule.orthogonal_le (le_supr _ _), exact (eigenspace T μ).orthogonal_disjoint.mono_right H₂ end /-! ### Finite-dimensional theory -/ variables [finite_dimensional 𝕜 E] /-- The mutual orthogonal complement of the eigenspaces of a self-adjoint operator on a finite-dimensional inner product space is trivial. -/ lemma orthogonal_supr_eigenspaces_eq_bot : (⨆ μ, eigenspace T μ)ᗮ = ⊥ := begin have hT' : is_self_adjoint _ := hT.restrict_invariant hT.orthogonal_supr_eigenspaces_invariant, -- a self-adjoint operator on a nontrivial inner product space has an eigenvalue haveI := hT'.subsingleton_of_no_eigenvalue_finite_dimensional hT.orthogonal_supr_eigenspaces, exact submodule.eq_bot_of_subsingleton _, end lemma orthogonal_supr_eigenspaces_eq_bot' : (⨆ μ : eigenvalues T, eigenspace T μ)ᗮ = ⊥ := show (⨆ μ : {μ // (eigenspace T μ) ≠ ⊥}, eigenspace T μ)ᗮ = ⊥, by rw [supr_ne_bot_subtype, hT.orthogonal_supr_eigenspaces_eq_bot] include dec_𝕜 /-- The eigenspaces of a self-adjoint operator on a finite-dimensional inner product space `E` give an internal direct sum decomposition of `E`. -/ lemma direct_sum_submodule_is_internal : direct_sum.submodule_is_internal (λ μ : eigenvalues T, eigenspace T μ) := hT.orthogonal_family_eigenspaces'.submodule_is_internal_iff.mpr hT.orthogonal_supr_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 : E ≃ₗᵢ[𝕜] pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ) := hT.direct_sum_submodule_is_internal.isometry_L2_of_orthogonal_family hT.orthogonal_family_eigenspaces' @[simp] lemma diagonalization_symm_apply (w : pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ)) : hT.diagonalization.symm w = ∑ μ, w μ := hT.direct_sum_submodule_is_internal.isometry_L2_of_orthogonal_family_symm_apply hT.orthogonal_family_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`. -/ lemma diagonalization_apply_self_apply (v : E) (μ : eigenvalues T) : hT.diagonalization (T v) μ = (μ : 𝕜) • hT.diagonalization v μ := begin suffices : ∀ w : pi_Lp 2 (λ μ : eigenvalues T, eigenspace T μ), (T (hT.diagonalization.symm w)) = hT.diagonalization.symm (λ μ, (μ : 𝕜) • w μ), { simpa [linear_isometry_equiv.symm_apply_apply, -is_self_adjoint.diagonalization_symm_apply] using congr_arg (λ w, hT.diagonalization w μ) (this (hT.diagonalization v)) }, intros w, have hwT : ∀ μ : eigenvalues T, T (w μ) = (μ : 𝕜) • w μ, { intros μ, simpa [mem_eigenspace_iff] using (w μ).prop }, simp [hwT], end end version1 section version2 variables {n : ℕ} (hn : finite_dimensional.finrank 𝕜 E = n) /-- A choice of orthonormal basis of eigenvectors for self-adjoint operator `T` on a finite-dimensional inner product space `E`. TODO Postcompose with a permutation so that these eigenvectors are listed in increasing order of eigenvalue. -/ noncomputable def eigenvector_basis : basis (fin n) 𝕜 E := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis hn lemma eigenvector_basis_orthonormal : orthonormal 𝕜 (hT.eigenvector_basis hn) := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_orthonormal hn hT.orthogonal_family_eigenspaces' /-- The sequence of real eigenvalues associated to the standard orthonormal basis of eigenvectors for a self-adjoint operator `T` on `E`. TODO Postcompose with a permutation so that these eigenvalues are listed in increasing order. -/ noncomputable def eigenvalues (i : fin n) : ℝ := @is_R_or_C.re 𝕜 _ $ hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_index hn i lemma has_eigenvector_eigenvector_basis (i : fin n) : has_eigenvector T (hT.eigenvalues hn i) (hT.eigenvector_basis hn i) := begin let v : E := hT.eigenvector_basis hn i, let μ : 𝕜 := hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_index hn i, change has_eigenvector T (is_R_or_C.re μ) v, have key : has_eigenvector T μ v, { have H₁ : v ∈ eigenspace T μ, { exact hT.direct_sum_submodule_is_internal.subordinate_orthonormal_basis_subordinate hn i }, have H₂ : v ≠ 0 := (hT.eigenvector_basis_orthonormal hn).ne_zero i, exact ⟨H₁, H₂⟩ }, have re_μ : ↑(is_R_or_C.re μ) = μ, { rw ← is_R_or_C.eq_conj_iff_re, exact hT.conj_eigenvalue_eq_self (has_eigenvalue_of_has_eigenvector key) }, simpa [re_μ] using key, end lemma has_eigenvalue_eigenvalues (i : fin n) : has_eigenvalue T (hT.eigenvalues hn i) := module.End.has_eigenvalue_of_has_eigenvector (hT.has_eigenvector_eigenvector_basis hn i) attribute [irreducible] eigenvector_basis eigenvalues @[simp] lemma apply_eigenvector_basis (i : fin n) : T (hT.eigenvector_basis hn i) = (hT.eigenvalues hn i : 𝕜) • hT.eigenvector_basis hn i := mem_eigenspace_iff.mp (hT.has_eigenvector_eigenvector_basis hn i).1 /-- An isometry from an inner product space `E` to Euclidean space, induced by a choice of orthonormal basis of eigenvectors for a self-adjoint operator `T` on `E`. -/ noncomputable def diagonalization_basis : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 (fin n) := ((hT.eigenvector_basis hn).to_orthonormal_basis (hT.eigenvector_basis_orthonormal hn)).repr @[simp] lemma diagonalization_basis_symm_apply (w : euclidean_space 𝕜 (fin n)) : (hT.diagonalization_basis hn).symm w = ∑ i, w i • hT.eigenvector_basis hn i := by simp [diagonalization_basis] /-- *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`. -/ lemma diagonalization_basis_apply_self_apply (v : E) (i : fin n) : hT.diagonalization_basis hn (T v) i = hT.eigenvalues hn i * hT.diagonalization_basis hn v i := begin suffices : ∀ w : euclidean_space 𝕜 (fin n), T ((hT.diagonalization_basis hn).symm w) = (hT.diagonalization_basis hn).symm (λ i, hT.eigenvalues hn i * w i), { simpa [-diagonalization_basis_symm_apply] using congr_arg (λ v, hT.diagonalization_basis hn v i) (this (hT.diagonalization_basis hn v)) }, intros w, simp [mul_comm, mul_smul], end end version2 end is_self_adjoint end inner_product_space section nonneg @[simp] lemma inner_product_apply_eigenvector {μ : 𝕜} {v : E} {T : E →ₗ[𝕜] E} (h : v ∈ module.End.eigenspace T μ) : ⟪v, T v⟫ = μ * ∥v∥ ^ 2 := by simp only [mem_eigenspace_iff.mp h, inner_smul_right, inner_self_eq_norm_sq_to_K] lemma eigenvalue_nonneg_of_nonneg {μ : ℝ} {T : E →ₗ[𝕜] E} (hμ : has_eigenvalue T μ) (hnn : ∀ (x : E), 0 ≤ is_R_or_C.re ⟪x, T x⟫) : 0 ≤ μ := begin obtain ⟨v, hv⟩ := hμ.exists_has_eigenvector, have hpos : 0 < ∥v∥ ^ 2, by simpa only [sq_pos_iff, norm_ne_zero_iff] using hv.2, have : is_R_or_C.re ⟪v, T v⟫ = μ * ∥v∥ ^ 2, { exact_mod_cast congr_arg is_R_or_C.re (inner_product_apply_eigenvector hv.1) }, exact (zero_le_mul_right hpos).mp (this ▸ hnn v), end lemma eigenvalue_pos_of_pos {μ : ℝ} {T : E →ₗ[𝕜] E} (hμ : has_eigenvalue T μ) (hnn : ∀ (x : E), 0 < is_R_or_C.re ⟪x, T x⟫) : 0 < μ := begin obtain ⟨v, hv⟩ := hμ.exists_has_eigenvector, have hpos : 0 < ∥v∥ ^ 2, by simpa only [sq_pos_iff, norm_ne_zero_iff] using hv.2, have : is_R_or_C.re ⟪v, T v⟫ = μ * ∥v∥ ^ 2, { exact_mod_cast congr_arg is_R_or_C.re (inner_product_apply_eigenvector hv.1) }, exact (zero_lt_mul_right hpos).mp (this ▸ hnn v), end end nonneg
9455fec69c3cabcd603eb8310e3ef2129c5a1f7e
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/uniform_space/basic.lean
20d976a0e9e3ae4c88e59e2f97cd0093a38992a3
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
41,957
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, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter.basic order.filter.lift topology.separation open set lattice filter classical open_locale classical topological_space set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.rfl } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.rfl } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[ext] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity localized "notation `𝓤` := uniformity" in uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := assume s hs, show {x | (a, a) ∈ s} ∈ f, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, comp_rel t t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f) : (𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (comp_rel s s)) = ((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_principal.comp (monotone_comp_rel monotone_const monotone_id) ... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : s ∈ 𝓝 x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : 𝓝 x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : 𝓝 x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, (𝓤 α).sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ 𝓝 x := have 𝓝 x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ 𝓝 y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (𝓝 a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (𝓝 a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_principal.comp $ monotone_preimage.comp monotone_preimage ) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (𝓝 x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ hg.comp monotone_preimage ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (𝓝 a) (𝓝 b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (𝓝 a).lift (λs:set α, (𝓝 b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_principal.comp (monotone_prod monotone_const monotone_id), exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : 𝓝 (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ 𝓝 (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (𝓝 (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, {x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b (𝓤 α) lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : uniform_continuous (g ∘ f) := hg.comp hf end uniform_space end open_locale uniformity section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, t.uniformity ≤ s.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, le_trans h₁ h₂ } instance : has_Inf (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma Inf_le {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : Inf tt ≤ t := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma le_Inf {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t ≤ t') : t ≤ Inf tt := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_top (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_bot (uniform_space α) := ⟨{ to_topological_space := ⊥, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Inf {x | a ≤ x ∧ b ≤ x}, le_sup_left := λ a b, le_Inf (λ _ ⟨h, _⟩, h), le_sup_right := λ a b, le_Inf (λ _ ⟨_, h⟩, h), sup_le := λ a b c h₁ h₂, Inf_le ⟨h₁, h₂⟩, inf := λ a b, Inf {a, b}, le_inf := λ a b c h₁ h₂, le_Inf (λ u h, by { cases h, exact h.symm ▸ h₂, exact (mem_singleton_iff.1 h).symm ▸ h₁ }), inf_le_left := λ a b, Inf_le (by simp), inf_le_right := λ a b, Inf_le (by simp), top := ⊤, le_top := λ a, show a.uniformity ≤ ⊤, from le_top, bot := ⊥, bot_le := λ u, u.refl, Sup := λ tt, Inf {t | ∀ t' ∈ tt, t' ≤ t}, le_Sup := λ s u h, le_Inf (λ u' h', h' u h), Sup_le := λ s u h, Inf_le h, Inf := Inf, le_Inf := λ s a hs, le_Inf hs, Inf_le := λ s a ha, Inf_le ha, ..uniform_space.partial_order } lemma infi_uniformity {ι : Sort*} {u : ι → uniform_space α} : (infi u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma inf_uniformity {u v : uniform_space α} : (u ⊓ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊓ v) = (⨅i (h : i = u ∨ i = v), i), by simp [infi_or, infi_inf_eq], calc (u ⊓ v).uniformity = ((⨅i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [infi_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊥⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_swap_uniformity.comp tendsto_comap, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] {f : α → β} : uniform_continuous f ↔ uα ≤ uβ.comap f := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := rfl lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma uniform_continuous.continuous [uniform_space α] [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_le_induced.mpr $ to_topological_space_mono $ uniform_continuous_iff.1 hf lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := rfl lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := top_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊤) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊤) lemma to_topological_space_infi {ι : Sort*} {u : ι → uniform_space α} : (infi u).to_topological_space = ⨅i, (u i).to_topological_space := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_infi, nhds_eq_uniformity], change (infi u).uniformity.lift' (preimage $ prod.mk a) = _, begin rw [infi_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, (@nhds_eq_uniformity α (u i) a).symm), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (le_infi $ assume i, to_topological_space_mono $ infi_le _ _) (have infi u = ⊤, from top_unique $ le_infi $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (infi u) = ⊤, from this.symm ▸ to_topological_space_top, this.symm ▸ le_top)) lemma to_topological_space_Inf {s : set (uniform_space α)} : (Inf s).to_topological_space = (⨅i∈s, @uniform_space.to_topological_space α i) := begin rw [Inf_eq_infi, to_topological_space_infi], apply congr rfl, funext x, exact to_topological_space_infi end lemma to_topological_space_inf {u v : uniform_space α} : (u ⊓ v).to_topological_space = u.to_topological_space ⊓ v.to_topological_space := by rw [to_topological_space_Inf, infi_pair] instance : uniform_space empty := ⊥ instance : uniform_space unit := ⊥ instance : uniform_space bool := ⊥ instance : uniform_space ℕ := ⊥ instance : uniform_space ℤ := ⊥ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ 𝓝 a) : tendsto f (𝓝 a) (𝓝 (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊓ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_inf, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : 𝓤 (α × β) = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := inf_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invarant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@inf_le_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@inf_le_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := h.comp (uniform_continuous_id.prod_mk uniform_continuous_const) lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := h.comp (uniform_continuous_const.prod_mk uniform_continuous_id) lemma to_topological_space_prod {α} {β} [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod section open uniform_space function variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] local notation f `∘₂` g := function.bicompr f g def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (uncurry' f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (uncurry' f) := iff.rfl lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [←uncurry'_curry f] {occs := occurrences.pos [2]} ; refl lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hg : uniform_continuous g) (hf : uniform_continuous₂ f) : uniform_continuous₂ (g ∘₂ f) := hg.comp hf end lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
20851bb9d9965d3690315137b02bd4d66ff6778e
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Lean/Elab/App.lean
577dd11eb60d4f7e5e4bccd453cc1a0a6da7a0df
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,014
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.FindMVar import Init.Lean.Elab.Term import Init.Lean.Elab.Binders namespace Lean namespace Elab namespace Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass private def ensureArgType (ref : Syntax) (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do argType ← inferType ref arg; ensureHasTypeAux ref expectedType argType arg f private def elabArg (ref : Syntax) (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => ensureArgType ref f val expectedType | Arg.stx val => do val ← elabTerm val expectedType; ensureArgType ref f val expectedType private def mkArrow (d b : Expr) : TermElabM Expr := do n ← mkFreshAnonymousName; pure $ Lean.mkForall n BinderInfo.default d b /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do v ← mkFreshLevelMVar ref; type ← mkArrow α (mkSort v); γ ← mkFreshExprMVar ref type; u ← getLevel ref α; let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ]; mvar ← mkFreshExprMVar ref coeFunInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; synthesized ← catch (withoutMacroStackAtErr $ synthesizeInstMVarCore ref mvarId) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("function expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "function expected"); if synthesized then pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else throwError ref "function expected" /-- Auxiliary structure used to elaborate function application arguments. -/ structure ElabAppArgsCtx := (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) -- if true, all arguments are treated as explicit (argIdx : Nat := 0) -- position of next explicit argument to be processed (namedArgs : Array NamedArg) -- remaining named arguments to be processed (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (foundExplicit : Bool := false) -- true if an explicit argument has already been processed /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => getForallBody i (namedArgs.eraseIdx idx) b | none => if !c.binderInfo.isExplicit then getForallBody i namedArgs b else if i > 0 then getForallBody (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody i namedArgs b else some type | i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean HasAdd.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`) 2- The resultant type does not contain any type metavariable. 3- The resultant type contains a nontype metavariable. We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in the Hindley&Milner fragment. For example, consider the following definitions ``` def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m) ``` Now, consider ``` def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 := foo x1 x2 = foo y1 y2 ``` When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`. If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`, by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since `bv 64` is **not** definitionally equal to `bv 32`. -/ private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit := unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do match ctx.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := ctx.args.size - ctx.argIdx; match getForallBody numRemainingArgs ctx.namedArgs eType with | none => pure () | some eTypeBody => unless eTypeBody.hasLooseBVars $ when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do isDefEq ctx.ref expectedType eTypeBody; pure () private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool := if h : ctx.argIdx < ctx.args.size then match ctx.args.get ⟨ctx.argIdx, h⟩ with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true | _ => false else false /- Elaborate function application arguments. -/ private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr | ctx, e, eType => do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed trace `Elab.app.finalize ctx.ref $ fun _ => e; match ctx.expectedType? with | none => pure () | some expectedType => do { -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. isDefEq ctx.ref expectedType eType; pure () }; synthesizeAppInstMVars ctx.ref ctx.instMVars; pure e }; eType ← whnfForall ctx.ref eType; match eType with | Expr.forallE n d b c => match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := ctx.namedArgs.get! idx; let namedArgs := ctx.namedArgs.eraseIdx idx; argElab ← elabArg ctx.ref e arg.val d; propagateExpectedType ctx eType; elabAppArgsAux { foundExplicit := true, namedArgs := namedArgs, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { propagateExpectedType ctx eType; let ctx := { foundExplicit := true, .. ctx }; if h : ctx.argIdx < ctx.args.size then do argElab ← elabArg ctx.ref e (ctx.args.get ⟨ctx.argIdx, h⟩) d; elabAppArgsAux { argIdx := ctx.argIdx + 1, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with | false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal) | false, _, some (Expr.const tacticDecl _ _) => do env ← getEnv; match evalSyntaxConstant env tacticDecl with | Except.error err => throwError ctx.ref err | Except.ok tacticSyntax => do tacticBlock ← `(begin $(tacticSyntax.getArgs)* end); -- tacticBlock does not have any position information -- use ctx.ref.getHeadInfo if available let tacticBlock := match ctx.ref.getHeadInfo with | some info => tacticBlock.replaceInfo info | _ => tacticBlock; let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type` argElab ← elabArg ctx.ref e (Arg.stx tacticBlock) d; elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab) | false, _, some _ => throwError ctx.ref "invalid autoParam, argument must be a constant" | _, _, _ => if ctx.namedArgs.isEmpty then finalize () else throwError ctx.ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) }; match c.binderInfo with | BinderInfo.implicit => if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d; typeMVars ← condM (isTypeFormer ctx.ref a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars); elabAppArgsAux { typeMVars := typeMVars, .. ctx } (mkApp e a) (b.instantiate1 a) | BinderInfo.instImplicit => if ctx.explicit && nextArgIsHole ctx then do /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) else if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) | _ => processExplictArg () | _ => if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then finalize () else do e ← tryCoeFun ctx.ref eType e; eType ← inferType ctx.ref e; elabAppArgsAux ctx e eType private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType ref f; fType ← instantiateMVars ref fType; trace `Elab.app.args ref $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType; unless (namedArgs.isEmpty && args.isEmpty) $ tryPostponeIfMVar fType; elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError ref "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError ref e eType "invalid projection, structure expected"; let fieldNames := getStructureFields env structName; if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv (fullName : Name) : TermElabM LValResolution := do { match env.find? fullName with | some _ => pure $ LValResolution.const structName fullName | none => throwLValError ref e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; lctx ← getLCtx; match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv fullName | none => searchEnv fullName }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Message → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore ref eType; tryPostponeIfMVar eType; catch (resolveLValAux ref e eType lval) (fun ex => match ex with | Exception.postpone => throw ex | Exception.ex Elab.Exception.unsupportedSyntax => throw ex | Exception.ex (Elab.Exception.error errMsg) => do eType? ← unfoldDefinition? ref eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push errMsg) | none => do previousExceptions.forM $ fun ex => logMessage errMsg; throw (Exception.ex (Elab.Exception.error errMsg))) private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType ref e; resolveLValLoop ref e lval eType #[] private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError ref "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst ref projFunName; elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false) e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError ref $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs ref f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal ref f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections ref baseStructName structName f; projFn ← mkConst ref (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseName constName => do projFn ← mkConst ref constName; if lvals.isEmpty then do projFnType ← inferType ref projFn; args ← addLValArg ref baseName constName f args 0 namedArgs projFnType; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType ref fvar; args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType; elabAppArgs ref fvar namedArgs args expectedType? explicit else do f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst ref fullName; if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs ref getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier"; elabAppLValsAux ref namedArgs args expectedType? explicit f lvals def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do let lvls := stx.getArg 1; lvls.foldSepRevArgsM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] private partial def elabAppFnId (ref : Syntax) (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := match fIdent with | Syntax.ident _ _ n preresolved => do funLVals ← resolveName fIdent n preresolved fExplicitUnivs; funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnsupportedSyntax private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.isIdent then -- A raw identifier is not a valid Term. Recall that `Term.id` is defined as `parser! ident >> optional (explicitUniv <|> namedPattern)` -- We handle it here to make macro development more comfortable. elabAppFnId ref f [] lvals namedArgs args expectedType? explicit acc else if f.getKind == choiceKind then f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc else match_syntax f with | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get!; elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc | `($(e).$field:ident) => let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n)); elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc | `($id:ident$us:explicitUniv*) => do -- Remark: `id.<namedPattern>` should already have been expanded us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0); elabAppFnId ref id us lvals namedArgs args expectedType? explicit acc | `(@$id:id) => elabAppFn id lvals namedArgs args expectedType? true acc | `(@$t) => throwUnsupportedSyntax -- invalid occurrence of `@` | _ => do s ← observing $ do { f ← elabTerm f none; elabAppLVals ref f lvals namedArgs args expectedType? explicit }; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do strPos ← getPos stx; pos ← getPosition strPos; if pos == msg.pos then pure msg.data else pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error errMsg s => toMessageData errMsg stx; throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do lctx ← getLCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else mergeFailures candidates f private partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do let f := stx.getArg 0; (namedArgs, args) ← (stx.getArg 1).getArgs.foldlM (fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do let (namedArgs, args) := acc; if stx.getKind == `Lean.Parser.Term.namedArgument then do -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := (stx.getArg 1).getId.eraseMacroScopes; let val := stx.getArg 3; namedArgs ← addNamedArg stx namedArgs { name := name, val := Arg.stx val }; pure (namedArgs, args) else pure (namedArgs, args.push $ Arg.stx stx)) (#[], #[]); pure (f, namedArgs, args) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx; elabAppAux stx f namedArgs args expectedType? def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx stx #[] #[] expectedType? @[builtinTermElab «id»] def elabId : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$id:id) => elabAtom stx expectedType? -- Recall that `elabApp` also has support for `@` | `(@($t)) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | `(@$t) => elabTermWithoutImplicitLambdas t expectedType? -- `@` is being used just to disable implicit lambdas | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom /- A raw identiier is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/ @[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom @[builtinTermElab sortApp] def elabSortApp : TermElab := fun stx _ => do u ← elabLevel (stx.getArg 1); if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do pure $ mkSort u else pure $ mkSort (mkLevelSucc u) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
0cf3ca780fd2720e40db1996c68b74aeb722799d
88fb7558b0636ec6b181f2a548ac11ad3919f8a5
/library/init/data/list/instances.lean
6ca265f0d04587de815b7006377b014cbb8b9038
[ "Apache-2.0" ]
permissive
moritayasuaki/lean
9f666c323cb6fa1f31ac597d777914aed41e3b7a
ae96ebf6ee953088c235ff7ae0e8c95066ba8001
refs/heads/master
1,611,135,440,814
1,493,852,869,000
1,493,852,869,000
90,269,903
0
0
null
1,493,906,291,000
1,493,906,291,000
null
UTF-8
Lean
false
false
2,361
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.lemmas import init.meta.mk_dec_eq_instance open list universes u v local attribute [simp] map join ret list.append append_nil section variables {α : Type u} {β : Type v} (x : α) (xs ys : list α) (f : α → list β) private lemma nil_bind : list.bind nil f = nil := by simp [list.bind] private lemma cons_bind : list.bind (x :: xs) f = f x ++ list.bind xs f := by simp [list.bind] private lemma append_bind : list.bind (xs ++ ys) f = list.bind xs f ++ list.bind ys f := begin induction xs, { refl }, { simph [cons_bind] } end end local attribute [simp] nil_bind cons_bind append_bind instance : monad list := {pure := @list.ret, bind := @list.bind, id_map := begin intros _ xs, induction xs with x xs ih, { refl }, { dsimp at ih, dsimp, simph } end, pure_bind := by simp_intros, bind_assoc := begin intros _ _ _ xs _ _, induction xs, { refl }, { simph } end} instance : alternative list := { list.monad with failure := @list.nil, orelse := @list.append } instance {α : Type u} [decidable_eq α] : decidable_eq (list α) := by tactic.mk_dec_eq_instance instance : decidable_eq string := list.decidable_eq namespace list variables {α : Type u} [decidable_eq α] variables (p : α → Prop) [decidable_pred p] instance decidable_bex : ∀ (l : list α), decidable (∃ x ∈ l, p x) | [] := is_false (by intro; cases a; cases a_2; cases a) | (x::xs) := if hx : p x then is_true ⟨x, or.inl rfl, hx⟩ else match decidable_bex xs with | is_true hxs := is_true $ begin cases hxs with x' hx', cases hx' with hx' hpx', existsi x', existsi (or.inr hx'), assumption, exact x' = x end | is_false hxs := is_false $ begin intro hxxs, cases hxxs with x' hx', cases hx' with hx' hpx', cases hx', cc, apply hxs, existsi x', existsi a, assumption end end instance decidable_ball (l : list α) : decidable (∀ x ∈ l, p x) := if h : ∃ x ∈ l, ¬ p x then is_false $ begin cases h with x h, cases h with hx h, intro h', apply h, apply h', assumption end else is_true $ λ x hx, if h' : p x then h' else false.elim $ h ⟨x, hx, h'⟩ end list
9e41b9f84310030087e8b369e4e738f7b8ff6c13
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/category/Group/biproducts.lean
e538a3a229693b12906366265ce77b8db23cbd09
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
3,007
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group.basic import algebra.category.Group.preadditive import category_theory.limits.shapes.biproducts import algebra.pi_instances /-! # The category of abelian groups has finite biproducts -/ open category_theory open category_theory.limits open_locale big_operators universe u namespace AddCommGroup instance has_binary_product (G H : AddCommGroup.{u}) : has_binary_product G H := { cone := { X := AddCommGroup.of (G × H), π := { app := λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H) }}, is_limit := { lift := λ s, add_monoid_hom.prod (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := begin rintros s (⟨⟩|⟨⟩); { ext x, dsimp, simp, }, end, uniq' := λ s m w, begin ext; [rw ← w walking_pair.left, rw ← w walking_pair.right]; refl, end, } } instance (G H : AddCommGroup.{u}) : has_binary_biproduct G H := has_binary_biproduct.of_has_binary_product _ _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the cartesian product of the underlying types: example (G H : AddCommGroup.{u}) : ((G ⊞ H : AddCommGroup) : Type u) = (G × H) := rfl -- Furthermore, our biproduct will automatically function as a coproduct. example (G H : AddCommGroup.{u}) : has_colimit (pair G H) := by apply_instance variables {J : Type u} (F : (discrete J) ⥤ AddCommGroup.{u}) namespace has_limit /-- The map from an arbitrary cone over a indexed family of abelian groups to the cartesian product of those groups. -/ def lift (s : cone F) : s.X ⟶ AddCommGroup.of (Π j, F.obj j) := { to_fun := λ x j, s.π.app j x, map_zero' := by { ext, simp }, map_add' := λ x y, by { ext, simp }, } @[simp] lemma lift_apply (s : cone F) (x : s.X) (j : J) : (lift F s) x j = s.π.app j x := rfl instance has_limit_discrete : has_limit F := { cone := { X := AddCommGroup.of (Π j, F.obj j), π := discrete.nat_trans (λ j, add_monoid_hom.apply (λ j, F.obj j) j), }, is_limit := { lift := lift F, fac' := λ s j, by { ext, dsimp, simp, }, uniq' := λ s m w, begin ext x j, dsimp only [has_limit.lift], simp only [add_monoid_hom.coe_mk], exact congr_arg (λ f : s.X ⟶ F.obj j, (f : s.X → F.obj j) x) (w j), end, }, } end has_limit section open has_limit variables [decidable_eq J] [fintype J] instance (f : J → AddCommGroup.{u}) : has_biproduct f := has_biproduct.of_has_product _ -- We verify that the underlying type of the biproduct we've just defined is definitionally -- the dependent function type: example (f : J → AddCommGroup.{u}) : ((⨁ f : AddCommGroup) : Type u) = (Π j, f j) := rfl end instance : has_finite_biproducts AddCommGroup := ⟨λ J _ _, { has_biproduct := λ f, by exactI infer_instance }⟩ end AddCommGroup
5fbe6e42adabd8bdcb16677555f94828ee80958d
abd85493667895c57a7507870867b28124b3998f
/src/geometry/euclidean.lean
b6ef811dfb3e371ef42a612d63cdd0a24033129d
[ "Apache-2.0" ]
permissive
pechersky/mathlib
d56eef16bddb0bfc8bc552b05b7270aff5944393
f1df14c2214ee114c9738e733efd5de174deb95d
refs/heads/master
1,666,714,392,571
1,591,747,567,000
1,591,747,567,000
270,557,274
0
0
Apache-2.0
1,591,597,975,000
1,591,597,974,000
null
UTF-8
Lean
false
false
19,060
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import analysis.normed_space.real_inner_product import analysis.normed_space.add_torsor noncomputable theory open_locale classical open_locale real /-! # Euclidean spaces This file defines Euclidean affine spaces. ## Implementation notes Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ /-- A `euclidean_affine_space V P` is an affine space with points `P` over an `inner_product_space V`. -/ abbreviation euclidean_affine_space (V : Type*) (P : Type*) [inner_product_space V] [metric_space P] := normed_add_torsor V P example (n : Type*) [fintype n] : euclidean_affine_space (euclidean_space n) (euclidean_space n) := by apply_instance namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left' _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw cos_angle, by_cases h : (∥x∥ * ∥y∥) = 0, { rw [h, mul_zero], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { exact div_mul_cancel _ h } end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), pow_two, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), inner_self_eq_norm_square, inner_self_eq_norm_square], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff (x y : V) : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin unfold angle, rw [←inner_div_norm_mul_norm_eq_one_iff, ←real.arccos_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff (x y : V) : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin unfold angle, rw [←inner_div_norm_mul_norm_eq_neg_one_iff, ←real.arccos_neg_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rw angle_eq_pi_iff at h, rcases h with ⟨hx, ⟨r, ⟨hr, hxy⟩⟩⟩, rw [hxy, angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : inner x y = 0 ↔ angle x y = π / 2 := begin split, { intro h, unfold angle, rw [h, zero_div, real.arccos_zero] }, { intro h, unfold angle at h, rw ←real.arccos_zero at h, have h2 : inner x y / (∥x∥ * ∥y∥) = 0 := real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h, by_cases h : (∥x∥ * ∥y∥) = 0, { cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { rwa div_eq_zero_iff h at h2 } }, end /-- Pythagorean theorem, if-and-only-if vector angle form. -/ lemma norm_add_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two (x y : V) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 := begin rw norm_add_square_eq_norm_square_add_norm_square_iff_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, vector angle form. -/ lemma norm_add_square_eq_norm_square_add_norm_square' (x y : V) (h : angle x y = π / 2) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two (x y : V) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ angle x y = π / 2 := begin rw norm_sub_square_eq_norm_square_add_norm_square_iff_inner_eq_zero, exact inner_eq_zero_iff_angle_eq_pi_div_two x y end /-- Pythagorean theorem, subtracting vectors, vector angle form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square' (x y : V) (h : angle x y = π / 2) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two x y).2 h /-- Law of cosines (cosine rule), vector angle form. -/ lemma norm_sub_square_eq_norm_square_add_norm_square_sub_two_mul_norm_mul_norm_mul_cos_angle (x y : V) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) := by rw [(show 2 * ∥x∥ * ∥y∥ * real.cos (angle x y) = 2 * (real.cos (angle x y) * (∥x∥ * ∥y∥)), by ring), cos_angle_mul_norm_mul_norm, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square, inner_sub_sub_self, sub_add_eq_add_sub] /-- Pons asinorum, vector angle form. -/ lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : angle x (x - y) = angle y (y - x) := begin refine real.cos_inj_of_nonneg_of_le_pi (angle_nonneg _ _) (angle_le_pi _ _) (angle_nonneg _ _) (angle_le_pi _ _) _, rw [cos_angle, cos_angle, h, ←neg_sub, norm_neg, neg_sub, inner_sub_right, inner_sub_right, inner_self_eq_norm_square, inner_self_eq_norm_square, h, inner_comm x y] end /-- Converse of pons asinorum, vector angle form. -/ lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V} (h : angle x (x - y) = angle y (y - x)) (hpi : angle x y ≠ π) : ∥x∥ = ∥y∥ := begin replace h := real.arccos_inj (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x (x - y))).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one x (x - y))).2 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one y (y - x))).1 (abs_le.mp (abs_inner_div_norm_mul_norm_le_one y (y - x))).2 h, by_cases hxy : x = y, { rw hxy }, { rw [←norm_neg (y - x), neg_sub, mul_comm, mul_comm ∥y∥, div_eq_mul_inv, div_eq_mul_inv, mul_inv', mul_inv', ←mul_assoc, ←mul_assoc] at h, replace h := mul_right_cancel' (inv_ne_zero (λ hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h, rw [inner_sub_right, inner_sub_right, inner_comm y x, inner_self_eq_norm_square, inner_self_eq_norm_square, mul_sub_right_distrib, mul_sub_right_distrib, mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub, ←mul_sub_left_distrib] at h, by_cases hx0 : x = 0, { rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h, rw [hx0, norm_zero, h] }, { by_cases hy0 : y = 0, { rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h, rw [hy0, norm_zero, h] }, { rw [inv_sub_inv (λ hz, hx0 (norm_eq_zero.1 hz)) (λ hz, hy0 (norm_eq_zero.1 hz)), ←neg_sub, ←mul_div_assoc, mul_comm, mul_div_assoc, ←mul_neg_one] at h, symmetry, by_contradiction hyx, replace h := (mul_left_cancel' (sub_ne_zero_of_ne hyx) h).symm, rw [inner_div_norm_mul_norm_eq_neg_one_iff, ←angle_eq_pi_iff] at h, exact hpi h } } } end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open add_torsor inner_product_geometry variables (V : Type*) {P : Type*} [inner_product_space V] [metric_space P] [euclidean_affine_space V P] include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ V p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ V p1 p2 p3 = ∠ V p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ V p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ V p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ V p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ V p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ V p1 p2 p1 = 0 := angle_self (λ he, h ((vsub_eq_zero_iff_eq V).1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = π) : ∠ V p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos' (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev V p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = π) : ∠ V p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left V h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ V p2 p3 p4 = π) : ∠ V p1 p2 p3 = ∠ V p1 p2 p4 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, symmetry, convert angle_smul_right_of_pos _ _ (add_pos' (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ←neg_vsub_eq_vsub_rev V p2 p3, smul_neg], simp [←hpr] end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ V p2 p3 p4 = π) : ∠ V p1 p3 p2 + ∠ V p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm V p1 p3 p2, angle_comm V p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- Pythagorean theorem, if-and-only-if angle-at-point form. -/ lemma dist_square_eq_dist_square_add_dist_square_iff_angle_eq_pi_div_two (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 ↔ ∠ V p1 p2 p3 = π / 2 := by erw [metric_space.dist_comm p3 p2, dist_eq_norm V p1 p3, dist_eq_norm V p1 p2, dist_eq_norm V p2 p3, ←norm_sub_square_eq_norm_square_add_norm_square_iff_angle_eq_pi_div_two, vsub_sub_vsub_cancel_right V p1, ←neg_vsub_eq_vsub_rev V p2 p3, norm_neg] /-- Law of cosines (cosine rule), angle-at-point form. -/ lemma dist_square_eq_dist_square_add_dist_square_sub_two_mul_dist_mul_dist_mul_cos_angle (p1 p2 p3 : P) : dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 - 2 * dist p1 p2 * dist p3 p2 * real.cos (∠ V p1 p2 p3) := begin rw [dist_eq_norm V p1 p3, dist_eq_norm V p1 p2, dist_eq_norm V p3 p2], unfold angle, convert norm_sub_square_eq_norm_square_add_norm_square_sub_two_mul_norm_mul_norm_mul_cos_angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2 : V), { exact (vsub_sub_vsub_cancel_right V p1 p3 p2).symm }, { exact (vsub_sub_vsub_cancel_right V p1 p3 p2).symm } end /-- Pons asinorum, angle-at-point form. -/ lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) : ∠ V p1 p2 p3 = ∠ V p1 p3 p2 := begin rw [dist_eq_norm V p1 p2, dist_eq_norm V p1 p3] at h, unfold angle, convert angle_sub_eq_angle_sub_rev_of_norm_eq h, { exact (vsub_sub_vsub_cancel_left V p3 p2 p1).symm }, { exact (vsub_sub_vsub_cancel_left V p2 p3 p1).symm } end /-- Converse of pons asinorum, angle-at-point form. -/ lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : ∠ V p1 p2 p3 = ∠ V p1 p3 p2) (hpi : ∠ V p2 p1 p3 ≠ π) : dist p1 p2 = dist p1 p3 := begin unfold angle at h hpi, rw [dist_eq_norm V p1 p2, dist_eq_norm V p1 p3], rw [←angle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi, rw [←vsub_sub_vsub_cancel_left V p3 p2 p1, ←vsub_sub_vsub_cancel_left V p2 p3 p1] at h, exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi end end euclidean_geometry
20b5c541039e90566e70081da076fd957abbfddc
dd24e6c3b8dc14dc504f8a906fc04c51e4312e6b
/src/mywork/lectures/lecture_5.lean
5e08e65cb52a73fceac1f273aadff1b4ad21d37e
[]
no_license
njeyasingh/CS-2120
dd781a90dd0645b74e61cee1813483fb7cb4a111
b3356f665a246f295b3f1e6d61901bfca331810d
refs/heads/main
1,693,294,711,274
1,635,188,659,000
1,635,188,659,000
399,945,420
0
0
null
null
null
null
UTF-8
Lean
false
false
2,656
lean
/- INTRODUCTION and ELIMINATION RULES -/ /- For ∀ x, P x (every x has property P) - introduction rule: assume arbitrary x, then show P x - elimination rule: *apply* a proof of ∀ x, P x, as a kind of function to a specific value of x, say k, to produce a proof of P k. -/ theorem silly : ∀ (n : ℕ), true := begin assume (n : ℕ), exact true.intro, end /- The proposition true is unconditionally true, as proven by an always available proof called (in Lean) true.intro. -/ #check silly 7 /- The check command will tell you the type of any expression (aka term) in Lean. Here we can see that silly is like a function, and that when we apply it to the specific argument, 7, we get back a proof of the resulting proposition (which is just, "true"). We'll soon be equipped to deal with more interesting "return types". -/ /- For P → Q (if P is true then Q must also be true) - introduction rule: assume arbitrary P, then show Q - elimination rule: *apply* a proof of P → Q, as a kind of function, to any proof of P to derive a proof of Q! -/ def foo : ∀ (x : ℕ), x = 0 → x + 1 = 1 := begin assume x h, rw h, end /- assume that if a proof that x=0, in that context it shows that x + 1 = 1 - start with the assumption is a natural number - that number is 0 and that if you add that number plus one = 1 how do you prove this? -- enable to makep progress : have a proof that x=0 - elimination rule -- substitution rule -- get the equivilant rule -/ /- Wow! ∀ and → sure do seem similar. Indeed they're the same! They define function types. We construct a proof of ∀ or → by assuming the premise and showing that in that context we can derive a result of the conclusion type. We can then use a proof of a ∀ or → by treating it as a function that can be applied to a specific value to derive a proof *for that specific value. Indeed, in Lean, → is really just another notation for forall! -/ /- Introduction rule foe and A Give a proff of P and a proof of -0 get back a proof of ( P ^ Q)-/ axioms (P Q: Prop) #check P #check ( P ∧ Q) axioms (p : P) (q : Q) example: P ∧ Q := and.intro p q /-Prove that if arbitary propositions P and Q are true ( which is to say that the proposition P ∧ Q is also true. Proof: the conjecture that P ∧ Q is true is proved by application of the introduction rule for and. ) -/ example: 0=0 ∧ 1 =1 := begin apply and.intro apply eq.refl 0, apply eg.refl 1, end theorem bar: 0 = 0 ∧ 1 =1 := begin apply and.intro (eq.refl 0)(eq.refl 1), end #check bar #check and.elim_left theorem and_communtative : V ( P Q : Prop), P ∧ Q
731d800b5b71d486cb3ed78d928a263e616e53d5
a4673261e60b025e2c8c825dfa4ab9108246c32e
/tests/lean/run/macroid.lean
83c661799df540d6f95bdbf3289220c07eaa66fe
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
567
lean
syntax "[" ident "↦" term "]" : term macro_rules `([$x ↦ $v]) => `(fun $x => $v) #check [x ↦ x + 1] syntax "case!" ident ":" term "with" term "," term : term macro_rules `(case! $h : $c with $t, $e) => `((fun $h => cond $h $t $e) $c) #check case! h : 0 == 0 with h, not h syntax "case2!" ident ":" term "with" term "," term : term macro_rules `(case2! $h : $c with $t, $e) => `(let $h := $c; cond $h $t $e) #check case2! h : 0 == 0 with h, not h syntax "test" term : term macro_rules `(test $x:ident) => `(let $x := 0; $x) #check fun (x : Nat) => test x
a40d8761b5f387d71c63b94ddd9a7ae850b79d52
6f1049e897f569e5c47237de40321e62f0181948
/src/exercises/06_sub_sequences.lean
421ff0751f17abae6b5b22eb4f61908a97724f6c
[ "Apache-2.0" ]
permissive
anrddh/tutorials
f654a0807b9523608544836d9a81939f8e1dceb8
3ba43804e7b632201c494cdaa8da5406f1a255f9
refs/heads/master
1,655,542,921,827
1,588,846,595,000
1,588,846,595,000
262,330,134
0
0
null
1,588,944,346,000
1,588,944,345,000
null
UTF-8
Lean
false
false
3,264
lean
import tuto_lib /- This file continues the elementary study of limits of sequences. It can be skipped if the previous file was too easy, it won't introduce any new tactic or trick. Remember useful lemmas: abs_le (x y : ℝ) : |x| ≤ y ↔ -y ≤ x ∧ x ≤ y abs_add (x y : ℝ) : |x + y| ≤ |x| + |y| abs_sub (x y : ℝ) : |x - y| = |y - x| ge_max_iff (p q r) : r ≥ max p q ↔ r ≥ p ∧ r ≥ q le_max_left p q : p ≤ max p q le_max_right p q : q ≤ max p q and the definition: def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε You can also use a property proved in the previous file: unique_limit : seq_limit u l → seq_limit u l' → l = l' def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m -/ variable { φ : ℕ → ℕ} /- The next lemma is proved by an easy induction, but we haven't seen induction in this tutorial. If you did the natural number game then you can delete the proof below and try to reconstruct it. -/ /-- An extraction is greater than id -/ lemma id_le_extraction' : extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end /-- Extractions take arbitrarily large values for arbitrarily large inputs. -/ -- 0039 lemma extraction_ge : extraction φ → ∀ N N', ∃ n ≥ N', φ n ≥ N := begin sorry end /-- A real number `a` is a cluster point of a sequence `u` if `u` has a subsequence converging to `a`. def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a -/ variables {u : ℕ → ℝ} {a l : ℝ} /- In the exercise, we use `∃ n ≥ N, ...` which is the abbreviation of `∃ n, n ≥ N ∧ ...`. Lean can read this abbreviation, but displays as the confusing : `∃ (n : ℕ) (H : n ≥ N)` One gets used to it. Alternatively, one can get rid of it using the lemma exists_prop {p q : Prop} : (∃ (h : p), q) ↔ p ∧ q -/ /-- If `a` is a cluster point of `u` then there are values of `u` arbitrarily close to `a` for arbitrarily large input. -/ -- 0040 lemma near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε := begin sorry end /- The above exercice can be done in five lines. Hint: you can use the anonymous constructor syntax when proving existential statements. -/ /-- If `u` tends to `l` then its subsequences tend to `l`. -/ -- 0041 lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin sorry end /-- If `u` tends to `l` all its cluster points are equal to `l`. -/ -- 0042 lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l := begin sorry end /-- cauchy_sequence sequence -/ def cauchy_sequence (u : ℕ → ℝ) := ∀ ε > 0, ∃ N, ∀ p q, p ≥ N → q ≥ N → |u p - u q| ≤ ε -- 0043 example : (∃ l, seq_limit u l) → cauchy_sequence u := begin sorry end /- In the next exercise, you can reuse near_cluster : cluster_point u a → ∀ ε > 0, ∀ N, ∃ n ≥ N, |u n - a| ≤ ε -/ -- 0044 example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l := begin sorry end
e9babc6ec430e42f45bfda67aca866c96ebc5208
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed/group/basic.lean
67af706a829f8835dfd81d50935ff60591670921
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
55,211
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.module.ulift import analysis.normed.group.seminorm import order.liminf_limsup import topology.algebra.uniform_group import topology.metric_space.algebra import topology.metric_space.isometry import topology.sequences /-! # Normed (semi)groups In this file we define four classes: * `has_norm`, `has_nnnorm`: auxiliary classes endowing a type `α` with a function `norm : α → ℝ` (notation: `∥x∥`) and `nnnorm : α → ℝ≥0` (notation: `∥x∥₊`), respectively; * `seminormed_add_comm_group`: a seminormed group is an additive group with a norm and a pseudo-metric space structures that agree with each other: `∀ x y, dist x y = ∥x - y∥`; * `normed_add_comm_group`: a normed group is an additive group with a norm and a metric space structures that agree with each other: `∀ x y, dist x y = ∥x - y∥`. We also prove basic properties of (semi)normed groups and provide some instances. ## Tags normed group -/ variables {α ι E F G : Type*} open filter metric open_locale topological_space big_operators nnreal ennreal uniformity pointwise /-- Auxiliary class, endowing a type `E` with a function `norm : E → ℝ` with notation `∥x∥`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (E : Type*) := (norm : E → ℝ) export has_norm (norm) notation `∥` e `∥` := norm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a pseudometric space structure. -/ class seminormed_add_comm_group (E : Type*) extends has_norm E, add_comm_group E, pseudo_metric_space E := (dist_eq : ∀ x y : E, dist x y = norm (x - y)) /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_add_comm_group (E : Type*) extends has_norm E, add_comm_group E, metric_space E := (dist_eq : ∀ x y : E, dist x y = norm (x - y)) /-- A normed group is a seminormed group. -/ @[priority 100] -- see Note [lower instance priority] instance normed_add_comm_group.to_seminormed_add_comm_group [h : normed_add_comm_group E] : seminormed_add_comm_group E := { .. h } /-- Construct a seminormed group from a translation invariant pseudodistance. -/ def seminormed_add_comm_group.of_add_dist [has_norm E] [add_comm_group E] [pseudo_metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist x y ≤ dist (x + z) (y + z)) : seminormed_add_comm_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x - y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def seminormed_add_comm_group.of_add_dist' [has_norm E] [add_comm_group E] [pseudo_metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist (x + z) (y + z) ≤ dist x y) : seminormed_add_comm_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x - y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A seminormed group can be built from a seminorm that satisfies algebraic properties. This is formalised in this structure. -/ structure seminormed_add_comm_group.core (E : Type*) [add_comm_group E] [has_norm E] : Prop := (norm_zero : ∥(0 : E)∥ = 0) (triangle : ∀ x y : E, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : E, ∥-x∥ = ∥x∥) /-- Constructing a seminormed group from core properties of a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. Note that in most cases this instance creates bad definitional equalities (e.g., it does not take into account a possibly existing `uniform_space` instance on `E`). -/ def seminormed_add_comm_group.of_core (E : Type*) [add_comm_group E] [has_norm E] (C : seminormed_add_comm_group.core E) : seminormed_add_comm_group E := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, by simp [C.norm_zero], dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } instance : normed_add_comm_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ∥r∥ = 0 := rfl noncomputable instance : normed_add_comm_group ℝ := { norm := λ x, |x|, dist_eq := assume x y, rfl } @[simp] lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = |r| := rfl section seminormed_add_comm_group variables [seminormed_add_comm_group E] [seminormed_add_comm_group F] [seminormed_add_comm_group G] lemma dist_eq_norm (g h : E) : dist g h = ∥g - h∥ := seminormed_add_comm_group.dist_eq _ _ lemma dist_eq_norm' (g h : E) : dist g h = ∥h - g∥ := by rw [dist_comm, dist_eq_norm] @[simp] lemma dist_zero_right (g : E) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] @[simp] lemma dist_zero_left : dist (0 : E) = norm := funext $ λ g, by rw [dist_comm, dist_zero_right] lemma isometry.norm_map_of_map_zero {f : E → F} (hi : isometry f) (h0 : f 0 = 0) (x : E) : ∥f x∥ = ∥x∥ := by rw [←dist_zero_right, ←h0, hi.dist_eq, dist_zero_right] lemma tendsto_norm_cocompact_at_top [proper_space E] : tendsto norm (cocompact E) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0 : E) lemma norm_sub_rev (g h : E) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : E) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : E) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : E) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] lemma dist_neg (x y : E) : dist (-x) y = dist x (-y) := by simp_rw [dist_eq_norm, ←norm_neg (-x - y), neg_sub, sub_neg_eq_add, add_comm] @[simp] lemma dist_neg_neg (g h : E) : dist (-g) (-h) = dist g h := by rw [dist_neg, neg_neg] @[simp] lemma dist_sub_left (g h₁ h₂ : E) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : E) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := by simpa only [sub_eq_add_neg] using dist_add_right _ _ _ @[simp] theorem dist_self_add_right (g h : E) : dist g (g + h) = ∥h∥ := by rw [← dist_zero_left, ← dist_add_left g 0 h, add_zero] @[simp] theorem dist_self_add_left (g h : E) : dist (g + h) g = ∥h∥ := by rw [dist_comm, dist_self_add_right] @[simp] theorem dist_self_sub_right (g h : E) : dist g (g - h) = ∥h∥ := by rw [sub_eq_add_neg, dist_self_add_right, norm_neg] @[simp] theorem dist_self_sub_left (g h : E) : dist (g - h) g = ∥h∥ := by rw [dist_comm, dist_self_sub_right] /-- In a (semi)normed group, negation `x ↦ -x` tends to infinity at infinity. TODO: use `bornology.cobounded` instead of `filter.comap has_norm.norm filter.at_top`. -/ lemma filter.tendsto_neg_cobounded : tendsto (has_neg.neg : E → E) (comap norm at_top) (comap norm at_top) := by simpa only [norm_neg, tendsto_comap_iff, (∘)] using tendsto_comap /-- **Triangle inequality** for the norm. -/ lemma norm_add_le (g h : E) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : E} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma norm_add₃_le (x y z : E) : ∥x + y + z∥ ≤ ∥x∥ + ∥y∥ + ∥z∥ := norm_add_le_of_le (norm_add_le _ _) le_rfl lemma dist_add_add_le (g₁ g₂ h₁ h₂ : E) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : E} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : E) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂) lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : E} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : E) : |dist g₁ h₁ - dist g₂ h₂| ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : E) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } section open tactic tactic.positivity /-- Extension for the `positivity` tactic: norms are nonnegative. -/ @[positivity] meta def _root_.tactic.positivity_norm : expr → tactic strictness | `(∥%%a∥) := nonnegative <$> mk_app ``norm_nonneg [a] | _ := failed end @[simp] lemma norm_zero : ∥(0 : E)∥ = 0 := by rw [← dist_zero_right, dist_self] lemma ne_zero_of_norm_ne_zero {g : E} : ∥g∥ ≠ 0 → g ≠ 0 := mt $ by { rintro rfl, exact norm_zero } @[nontriviality] lemma norm_of_subsingleton [subsingleton E] (x : E) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_multiset_sum_le (m : multiset E) : ∥m.sum∥ ≤ (m.map (λ x, ∥x∥)).sum := m.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le (s : finset ι) (f : ι → E) : ∥∑ i in s, f i∥ ≤ ∑ i in s, ∥f i∥ := s.le_sum_of_subadditive norm norm_zero norm_add_le f lemma norm_sum_le_of_le (s : finset ι) {f : ι → E} {n : ι → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma dist_sum_sum_le_of_le (s : finset ι) {f g : ι → E} {d : ι → ℝ} (h : ∀ b ∈ s, dist (f b) (g b) ≤ d b) : dist (∑ b in s, f b) (∑ b in s, g b) ≤ ∑ b in s, d b := begin simp only [dist_eq_norm, ← finset.sum_sub_distrib] at *, exact norm_sum_le_of_le s h end lemma dist_sum_sum_le (s : finset ι) (f g : ι → E) : dist (∑ b in s, f b) (∑ b in s, g b) ≤ ∑ b in s, dist (f b) (g b) := dist_sum_sum_le_of_le s (λ _ _, le_rfl) lemma norm_sub_le (g h : E) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : E} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : E) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : E) : |∥g∥ - ∥h∥| ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : E) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : E) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h /-- The direct path from `0` to `v` is shorter than the path with `u` inserted in between. -/ lemma norm_le_insert (u v : E) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma norm_le_insert' (u v : E) : ∥u∥ ≤ ∥v∥ + ∥u - v∥ := by { rw norm_sub_rev, exact norm_le_insert v u } lemma norm_le_add_norm_add (u v : E) : ∥u∥ ≤ ∥u + v∥ + ∥v∥ := calc ∥u∥ = ∥u + v - v∥ : by rw add_sub_cancel ... ≤ ∥u + v∥ + ∥v∥ : norm_sub_le _ _ lemma ball_eq (y : E) (ε : ℝ) : metric.ball y ε = { x | ∥x - y∥ < ε} := by { ext, simp [dist_eq_norm], } lemma ball_zero_eq (ε : ℝ) : ball (0 : E) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : E} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma add_mem_ball_iff_norm {g h : E} {r : ℝ} : g + h ∈ ball g r ↔ ∥h∥ < r := by rw [mem_ball_iff_norm, add_sub_cancel'] lemma mem_ball_iff_norm' {g h : E} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] @[simp] lemma mem_ball_zero_iff {ε : ℝ} {x : E} : x ∈ ball (0 : E) ε ↔ ∥x∥ < ε := by rw [mem_ball, dist_zero_right] lemma mem_closed_ball_iff_norm {g h : E} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] @[simp] lemma mem_closed_ball_zero_iff {ε : ℝ} {x : E} : x ∈ closed_ball (0 : E) ε ↔ ∥x∥ ≤ ε := by rw [mem_closed_ball, dist_zero_right] lemma add_mem_closed_ball_iff_norm {g h : E} {r : ℝ} : g + h ∈ closed_ball g r ↔ ∥h∥ ≤ r := by rw [mem_closed_ball_iff_norm, add_sub_cancel'] lemma mem_closed_ball_iff_norm' {g h : E} {r : ℝ} : h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r := by rw [mem_closed_ball', dist_eq_norm] lemma norm_le_of_mem_closed_ball {g h : E} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_le_norm_add_const_of_dist_le {a b : E} {c : ℝ} (h : dist a b ≤ c) : ∥a∥ ≤ ∥b∥ + c := norm_le_of_mem_closed_ball h lemma norm_lt_of_mem_ball {g h : E} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_norm_add_const_of_dist_lt {a b : E} {c : ℝ} (h : dist a b < c) : ∥a∥ < ∥b∥ + c := norm_lt_of_mem_ball h lemma bounded_iff_forall_norm_le {s : set E} : bounded s ↔ ∃ C, ∀ x ∈ s, ∥x∥ ≤ C := by simpa only [set.subset_def, mem_closed_ball_iff_norm, sub_zero] using bounded_iff_subset_ball (0 : E) @[simp] lemma preimage_add_ball (x y : E) (r : ℝ) : ((+) y) ⁻¹' (ball x r) = ball (x - y) r := begin ext z, simp only [dist_eq_norm, set.mem_preimage, mem_ball], abel end @[simp] lemma preimage_add_closed_ball (x y : E) (r : ℝ) : ((+) y) ⁻¹' (closed_ball x r) = closed_ball (x - y) r := begin ext z, simp only [dist_eq_norm, set.mem_preimage, mem_closed_ball], abel end @[simp] lemma mem_sphere_iff_norm (v w : E) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r := by simp [dist_eq_norm] @[simp] lemma mem_sphere_zero_iff_norm {w : E} {r : ℝ} : w ∈ sphere (0:E) r ↔ ∥w∥ = r := by simp [dist_eq_norm] @[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:E) r) : ∥(x:E)∥ = r := mem_sphere_zero_iff_norm.mp x.2 lemma preimage_add_sphere (x y : E) (r : ℝ) : ((+) y) ⁻¹' (sphere x r) = sphere (x - y) r := begin ext z, simp only [set.mem_preimage, mem_sphere_iff_norm], abel end lemma ne_zero_of_mem_sphere {r : ℝ} (hr : r ≠ 0) (x : sphere (0 : E) r) : (x : E) ≠ 0 := ne_zero_of_norm_ne_zero $ by rwa norm_eq_of_mem_sphere x lemma ne_zero_of_mem_unit_sphere (x : sphere (0:E) 1) : (x:E) ≠ 0 := ne_zero_of_mem_sphere one_ne_zero _ variables (E) /-- The norm of a seminormed group as an additive group seminorm. -/ def norm_add_group_seminorm : add_group_seminorm E := ⟨norm, norm_zero, norm_add_le, norm_neg⟩ @[simp] lemma coe_norm_add_group_seminorm : ⇑(norm_add_group_seminorm E) = norm := rfl variables {E} namespace isometric -- TODO This material is superseded by similar constructions such as -- `affine_isometry_equiv.const_vadd`; deduplicate /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : E) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : E) : (isometric.add_right x : E → E) = λ y, y + x := rfl lemma add_right_apply (x y : E) : (isometric.add_right x : E → E) y = y + x := rfl @[simp] lemma add_right_symm (x : E) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : E) : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : E) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : E) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : E) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (E) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : E ≃ᵢ E := { isometry_to_fun := isometry.of_dist_eq $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg E } variable {E} @[simp] lemma neg_symm : (isometric.neg E).symm = isometric.neg E := rfl @[simp] lemma neg_to_equiv : (isometric.neg E).to_equiv = equiv.neg E := rfl @[simp] lemma coe_neg : ⇑(isometric.neg E) = has_neg.neg := rfl end isometric theorem normed_add_comm_group.tendsto_nhds_zero {f : α → E} {l : filter α} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_add_comm_group.tendsto_nhds_nhds {f : E → F} {x : E} {y : F} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] lemma normed_add_comm_group.cauchy_seq_iff [nonempty α] [semilattice_sup α] {u : α → E} : cauchy_seq u ↔ ∀ ε > 0, ∃ N, ∀ m, N ≤ m → ∀ n, N ≤ n → ∥u m - u n∥ < ε := by simp [metric.cauchy_seq_iff, dist_eq_norm] lemma normed_add_comm_group.nhds_basis_norm_lt (x : E) : (𝓝 x).has_basis (λ (ε : ℝ), 0 < ε) (λ (ε : ℝ), { y | ∥y - x∥ < ε }) := begin simp_rw ← ball_eq, exact metric.nhds_basis_ball, end lemma normed_add_comm_group.nhds_zero_basis_norm_lt : (𝓝 (0 : E)).has_basis (λ (ε : ℝ), 0 < ε) (λ (ε : ℝ), { y | ∥y∥ < ε }) := begin convert normed_add_comm_group.nhds_basis_norm_lt (0 : E), simp, end lemma normed_add_comm_group.uniformity_basis_dist : (𝓤 E).has_basis (λ (ε : ℝ), 0 < ε) (λ ε, {p : E × E | ∥p.fst - p.snd∥ < ε}) := begin convert metric.uniformity_basis_dist, simp [dist_eq_norm] end section tendsto_uniformly /-- The results in this section do not require `E'` to any particular structure -/ variables {E' : Type*} {f : ι → E' → G} {s : set E'} {l : filter ι} lemma normed_add_comm_group.tendsto_uniformly_on_zero : tendsto_uniformly_on f 0 l s ↔ ∀ ε > 0, ∀ᶠ (N : ι) in l, ∀ x : E', x ∈ s → ∥f N x∥ < ε := by simp_rw [tendsto_uniformly_on_iff, pi.zero_apply, dist_zero_left] lemma normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero {l' : filter E'} : uniform_cauchy_seq_on_filter f l l' ↔ tendsto_uniformly_on_filter (λ n : ι × ι, λ z : E', f n.fst z - f n.snd z) 0 (l.prod l) l' := begin split, { intros hf u hu, obtain ⟨ε, hε, H⟩ := uniformity_basis_dist.mem_uniformity_iff.mp hu, refine (hf {p : G × G | dist p.fst p.snd < ε} $ dist_mem_uniformity hε).mono (λ x hx, H 0 (f x.fst.fst x.snd - f x.fst.snd x.snd) _), simpa [dist_eq_norm, norm_sub_rev] using hx, }, { intros hf u hu, obtain ⟨ε, hε, H⟩ := uniformity_basis_dist.mem_uniformity_iff.mp hu, refine (hf {p : G × G | dist p.fst p.snd < ε} $ dist_mem_uniformity hε).mono (λ x hx, H (f x.fst.fst x.snd) (f x.fst.snd x.snd) _), simpa [dist_eq_norm, norm_sub_rev] using hx, }, end lemma normed_add_comm_group.uniform_cauchy_seq_on_iff_tendsto_uniformly_on_zero : uniform_cauchy_seq_on f l s ↔ tendsto_uniformly_on (λ n : ι × ι, λ z : E', f n.fst z - f n.snd z) 0 (l.prod l) s := begin rw tendsto_uniformly_on_iff_tendsto_uniformly_on_filter, rw uniform_cauchy_seq_on_iff_uniform_cauchy_seq_on_filter, exact normed_add_comm_group.uniform_cauchy_seq_on_filter_iff_tendsto_uniformly_on_filter_zero, end end tendsto_uniformly open finset /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom_class.lipschitz_of_bound {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : E → F} {C : ℝ≥0} {s : set E} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : E → F} {C : ℝ≥0} {s : set E} (h : lipschitz_on_with C f s) {x y : E} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in lemma lipschitz_on_with.norm_sub_le_of_le {f : E → F} {C : ℝ≥0} {s : set E} (h : lipschitz_on_with C f s){x y : E} (x_in : x ∈ s) (y_in : y ∈ s) {d : ℝ} (hd : ∥x - y∥ ≤ d) : ∥f x - f y∥ ≤ C * d := (h.norm_sub_le x_in y_in).trans $ mul_le_mul_of_nonneg_left hd C.2 lemma lipschitz_with_iff_norm_sub_le {f : E → F} {C : ℝ≥0} : lipschitz_with C f ↔ ∀ x y, ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_with_iff_dist_le_mul, dist_eq_norm] alias lipschitz_with_iff_norm_sub_le ↔ lipschitz_with.norm_sub_le _ lemma lipschitz_with.norm_sub_le_of_le {f : E → F} {C : ℝ≥0} (h : lipschitz_with C f) {x y : E} {d : ℝ} (hd : ∥x - y∥ ≤ d) : ∥f x - f y∥ ≤ C * d := (h.norm_sub_le x y).trans $ mul_le_mul_of_nonneg_left hd C.2 /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. -/ lemma add_monoid_hom_class.continuous_of_bound {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (add_monoid_hom_class.lipschitz_of_bound f C h).continuous lemma add_monoid_hom_class.uniform_continuous_of_bound {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (add_monoid_hom_class.lipschitz_of_bound f C h).uniform_continuous lemma is_compact.exists_bound_of_continuous_on [topological_space α] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : ∃ C, ∀ x ∈ s, ∥f x∥ ≤ C := begin have : bounded (f '' s) := (hs.image_of_continuous_on hf).bounded, rcases bounded_iff_forall_norm_le.1 this with ⟨C, hC⟩, exact ⟨C, λ x hx, hC _ (set.mem_image_of_mem _ hx)⟩, end lemma add_monoid_hom_class.isometry_iff_norm {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ := begin simp only [isometry_iff_dist_eq, dist_eq_norm, ←map_sub], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 0 end lemma add_monoid_hom_class.isometry_of_norm {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := (add_monoid_hom_class.isometry_iff_norm f).2 hf lemma controlled_sum_of_mem_closure {s : add_subgroup E} {g : E} (hg : g ∈ closure (s : set E)) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ v : ℕ → E, tendsto (λ n, ∑ i in range (n+1), v i) at_top (𝓝 g) ∧ (∀ n, v n ∈ s) ∧ ∥v 0 - g∥ < b 0 ∧ ∀ n > 0, ∥v n∥ < b n := begin obtain ⟨u : ℕ → E, u_in : ∀ n, u n ∈ s, lim_u : tendsto u at_top (𝓝 g)⟩ := mem_closure_iff_seq_limit.mp hg, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ∀ n ≥ n₀, ∥u n - g∥ < b 0, { have : {x | ∥x - g∥ < b 0} ∈ 𝓝 g, { simp_rw ← dist_eq_norm, exact metric.ball_mem_nhds _ (b_pos _) }, exact filter.tendsto_at_top'.mp lim_u _ this }, set z : ℕ → E := λ n, u (n + n₀), have lim_z : tendsto z at_top (𝓝 g) := lim_u.comp (tendsto_add_at_top_nat n₀), have mem_𝓤 : ∀ n, {p : E × E | ∥p.1 - p.2∥ < b (n + 1)} ∈ 𝓤 E := λ n, by simpa [← dist_eq_norm] using metric.dist_mem_uniformity (b_pos $ n+1), obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∥z (φ $ n + 1) - z (φ n)∥ < b (n + 1)⟩ := lim_z.cauchy_seq.subseq_mem mem_𝓤, set w : ℕ → E := z ∘ φ, have hw : tendsto w at_top (𝓝 g), from lim_z.comp φ_extr.tendsto_at_top, set v : ℕ → E := λ i, if i = 0 then w 0 else w i - w (i - 1), refine ⟨v, tendsto.congr (finset.eq_sum_range_sub' w) hw , _, hn₀ _ (n₀.le_add_left _), _⟩, { rintro ⟨⟩, { change w 0 ∈ s, apply u_in }, { apply s.sub_mem ; apply u_in }, }, { intros l hl, obtain ⟨k, rfl⟩ : ∃ k, l = k+1, exact nat.exists_eq_succ_of_ne_zero (ne_of_gt hl), apply hφ }, end lemma controlled_sum_of_mem_closure_range {j : E →+ F} {h : F} (Hh : h ∈ (closure $ (j.range : set F))) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ g : ℕ → E, tendsto (λ n, ∑ i in range (n+1), j (g i)) at_top (𝓝 h) ∧ ∥j (g 0) - h∥ < b 0 ∧ ∀ n > 0, ∥j (g n)∥ < b n := begin rcases controlled_sum_of_mem_closure Hh b_pos with ⟨v, sum_v, v_in, hv₀, hv_pos⟩, choose g hg using v_in, change ∀ (n : ℕ), j (g n) = v n at hg, refine ⟨g, by simpa [← hg] using sum_v, by simpa [hg 0] using hv₀, λ n hn, by simpa [hg] using hv_pos n hn⟩ end section nnnorm /-- Auxiliary class, endowing a type `α` with a function `nnnorm : α → ℝ≥0` with notation `∥x∥₊`. -/ class has_nnnorm (E : Type*) := (nnnorm : E → ℝ≥0) export has_nnnorm (nnnorm) notation `∥`e`∥₊` := nnnorm e @[priority 100] -- see Note [lower instance priority] instance seminormed_add_comm_group.to_has_nnnorm : has_nnnorm E := ⟨λ a, ⟨norm a, norm_nonneg a⟩⟩ @[simp, norm_cast] lemma coe_nnnorm (a : E) : (∥a∥₊ : ℝ) = norm a := rfl @[simp] lemma coe_comp_nnnorm : (coe : ℝ≥0 → ℝ) ∘ (nnnorm : E → ℝ≥0) = norm := rfl lemma norm_to_nnreal {a : E} : ∥a∥.to_nnreal = ∥a∥₊ := @real.to_nnreal_coe ∥a∥₊ lemma nndist_eq_nnnorm (a b : E) : nndist a b = ∥a - b∥₊ := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_zero : ∥(0 : E)∥₊ = 0 := nnreal.eq norm_zero lemma ne_zero_of_nnnorm_ne_zero {g : E} : ∥g∥₊ ≠ 0 → g ≠ 0 := mt $ by { rintro rfl, exact nnnorm_zero } lemma nnnorm_add_le (g h : E) : ∥g + h∥₊ ≤ ∥g∥₊ + ∥h∥₊ := nnreal.coe_le_coe.1 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : E) : ∥-g∥₊ = ∥g∥₊ := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : E) : nndist ∥g∥₊ ∥h∥₊ ≤ ∥g - h∥₊ := nnreal.coe_le_coe.1 $ dist_norm_norm_le g h /-- The direct path from `0` to `v` is shorter than the path with `u` inserted in between. -/ lemma nnnorm_le_insert (u v : E) : ∥v∥₊ ≤ ∥u∥₊ + ∥u - v∥₊ := norm_le_insert u v lemma nnnorm_le_insert' (u v : E) : ∥u∥₊ ≤ ∥v∥₊ + ∥u - v∥₊ := norm_le_insert' u v lemma nnnorm_le_add_nnnorm_add (u v : E) : ∥u∥₊ ≤ ∥u + v∥₊ + ∥v∥₊ := norm_le_add_norm_add u v lemma of_real_norm_eq_coe_nnnorm (x : E) : ennreal.of_real ∥x∥ = (∥x∥₊ : ℝ≥0∞) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : E) : edist x y = (∥x - y∥₊ : ℝ≥0∞) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : E) : edist x 0 = (∥x∥₊ : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma mem_emetric_ball_zero_iff {x : E} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : E) r ↔ ↑∥x∥₊ < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : E) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.1 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : E) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } @[simp] lemma edist_add_left (g h₁ h₂ : E) : edist (g + h₁) (g + h₂) = edist h₁ h₂ := by simp [edist_dist] @[simp] lemma edist_add_right (g₁ g₂ h : E) : edist (g₁ + h) (g₂ + h) = edist g₁ g₂ := by simp [edist_dist] lemma edist_neg (x y : E) : edist (-x) y = edist x (-y) := by simp_rw [edist_dist, dist_neg] @[simp] lemma edist_neg_neg (x y : E) : edist (-x) (-y) = edist x y := by rw [edist_neg, neg_neg] @[simp] lemma edist_sub_left (g h₁ h₂ : E) : edist (g - h₁) (g - h₂) = edist h₁ h₂ := by simp only [sub_eq_add_neg, edist_add_left, edist_neg_neg] @[simp] lemma edist_sub_right (g₁ g₂ h : E) : edist (g₁ - h) (g₂ - h) = edist g₁ g₂ := by simpa only [sub_eq_add_neg] using edist_add_right _ _ _ lemma nnnorm_multiset_sum_le (m : multiset E) : ∥m.sum∥₊ ≤ (m.map (λ x, ∥x∥₊)).sum := m.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le lemma nnnorm_sum_le (s : finset ι) (f : ι → E) : ∥∑ a in s, f a∥₊ ≤ ∑ a in s, ∥f a∥₊ := s.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le f lemma nnnorm_sum_le_of_le (s : finset ι) {f : ι → E} {n : ι → ℝ≥0} (h : ∀ b ∈ s, ∥f b∥₊ ≤ n b) : ∥∑ b in s, f b∥₊ ≤ ∑ b in s, n b := (norm_sum_le_of_le s h).trans_eq nnreal.coe_sum.symm lemma add_monoid_hom_class.lipschitz_of_bound_nnnorm {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) (C : ℝ≥0) (h : ∀ x, ∥f x∥₊ ≤ C * ∥x∥₊) : lipschitz_with C f := @real.to_nnreal_coe C ▸ add_monoid_hom_class.lipschitz_of_bound f C h lemma add_monoid_hom_class.antilipschitz_of_bound {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, map_sub] using h (x - y) lemma add_monoid_hom_class.bound_of_antilipschitz {𝓕 : Type*} [add_monoid_hom_class 𝓕 E F] (f : 𝓕) {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ∥x∥ ≤ K * ∥f x∥ := by simpa only [dist_zero_right, map_zero] using h.le_mul_dist x 0 end nnnorm namespace lipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} lemma neg (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, (edist_neg_neg _ _).trans_le $ hf x y lemma add (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma sub (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg end lipschitz_with namespace antilipschitz_with variables [pseudo_emetric_space α] {K Kf Kg : ℝ≥0} {f g : α → E} lemma add_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin letI : pseudo_metric_space α := pseudo_emetric_space.to_pseudo_metric_space hf.edist_ne_top, refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ tsub_pos_iff_lt.2 hK), rw [mul_comm, nnreal.coe_sub hK.le, sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end lemma add_sub_lipschitz_with (hf : antilipschitz_with Kf f) (hg : lipschitz_with Kg (g - f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.sub_apply, add_sub_cancel'_right] using hf.add_lipschitz_with hg hK lemma le_mul_norm_sub {f : E → F} (hf : antilipschitz_with K f) (x y : E) : ∥x - y∥ ≤ K * ∥f x - f y∥ := by simp [← dist_eq_norm, hf.le_mul_dist x y] end antilipschitz_with /-- A group homomorphism from an `add_comm_group` to a `seminormed_add_comm_group` induces a `seminormed_add_comm_group` structure on the domain. See note [reducible non-instances] -/ @[reducible] def seminormed_add_comm_group.induced {E} [add_comm_group E] (f : E →+ F) : seminormed_add_comm_group E := { norm := λ x, ∥f x∥, dist_eq := λ x y, by simpa only [add_monoid_hom.map_sub, ← dist_eq_norm], .. pseudo_metric_space.induced f seminormed_add_comm_group.to_pseudo_metric_space, } /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ instance add_subgroup.seminormed_add_comm_group (s : add_subgroup E) : seminormed_add_comm_group s := seminormed_add_comm_group.induced s.subtype /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp] lemma add_subgroup.coe_norm {E : Type*} [seminormed_add_comm_group E] {s : add_subgroup E} (x : s) : ∥(x : s)∥ = ∥(x:E)∥ := rfl /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. This is a reversed version of the `simp` lemma `add_subgroup.coe_norm` for use by `norm_cast`. -/ @[norm_cast] lemma add_subgroup.norm_coe {E : Type*} [seminormed_add_comm_group E] {s : add_subgroup E} (x : s) : ∥(x : E)∥ = ∥(x : s)∥ := rfl /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.seminormed_add_comm_group {𝕜 E : Type*} {_ : ring 𝕜} [seminormed_add_comm_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : seminormed_add_comm_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `s` is equal to its norm in `E`. See note [implicit instance arguments]. -/ @[simp] lemma submodule.coe_norm {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [seminormed_add_comm_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : s)∥ = ∥(x : E)∥ := rfl /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. This is a reversed version of the `simp` lemma `submodule.coe_norm` for use by `norm_cast`. See note [implicit instance arguments]. -/ @[norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [seminormed_add_comm_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : E)∥ = ∥(x : s)∥ := rfl instance ulift.seminormed_add_comm_group : seminormed_add_comm_group (ulift E) := seminormed_add_comm_group.induced ⟨ulift.down, rfl, λ _ _, rfl⟩ lemma ulift.norm_def (x : ulift E) : ∥x∥ = ∥x.down∥ := rfl lemma ulift.nnnorm_def (x : ulift E) : ∥x∥₊ = ∥x.down∥₊ := rfl @[simp] lemma ulift.norm_up (x : E) : ∥ulift.up x∥ = ∥x∥ := rfl @[simp] lemma ulift.nnnorm_up (x : E) : ∥ulift.up x∥₊ = ∥x∥₊ := rfl /-- seminormed group instance on the product of two seminormed groups, using the sup norm. -/ noncomputable instance prod.seminormed_add_comm_group : seminormed_add_comm_group (E × F) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : E × F), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.norm_def (x : E × F) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : E × F) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : E × F) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : E × F) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : E × F} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff section pi variables {π : ι → Type*} [fintype ι] [Π i, seminormed_add_comm_group (π i)] (f : Π i, π i) /-- seminormed group instance on the product of finitely many seminormed groups, using the sup norm. -/ noncomputable instance pi.seminormed_add_comm_group : seminormed_add_comm_group (Π i, π i) := { norm := λ f, ↑(finset.univ.sup (λ b, ∥f b∥₊)), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = ∥x a - y a∥₊, from nndist_eq_nnnorm _ _ } lemma pi.norm_def : ∥f∥ = ↑(finset.univ.sup (λ b, ∥f b∥₊)) := rfl lemma pi.nnnorm_def : ∥f∥₊ = finset.univ.sup (λ b, ∥f b∥₊) := subtype.eta _ _ /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {r : ℝ} (hr : 0 ≤ r) {x : Π i, π i} : ∥x∥ ≤ r ↔ ∀ i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] lemma pi_nnnorm_le_iff {r : ℝ≥0} {x : Π i, π i} : ∥x∥₊ ≤ r ↔ ∀i, ∥x i∥₊ ≤ r := pi_norm_le_iff r.coe_nonneg /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_norm_lt_iff {r : ℝ} (hr : 0 < r) {x : Π i, π i} : ∥x∥ < r ↔ ∀ i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma pi_nnnorm_lt_iff {r : ℝ≥0} (hr : 0 < r) {x : Π i, π i} : ∥x∥₊ < r ↔ ∀ i, ∥x i∥₊ < r := pi_norm_lt_iff hr lemma norm_le_pi_norm (i : ι) : ∥f i∥ ≤ ∥f∥ := (pi_norm_le_iff $ norm_nonneg _).1 le_rfl i lemma nnnorm_le_pi_nnnorm (i : ι) : ∥f i∥₊ ≤ ∥f∥₊ := norm_le_pi_norm _ i @[simp] lemma pi_norm_const [nonempty ι] (a : E) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnnorm_const [nonempty ι] (a : E) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_norm_const a /-- The $L^1$ norm is less than the $L^\infty$ norm scaled by the cardinality. -/ lemma pi.sum_norm_apply_le_norm : ∑ i, ∥f i∥ ≤ fintype.card ι • ∥f∥ := finset.sum_le_card_nsmul _ _ _ $ λ i hi, norm_le_pi_norm _ i /-- The $L^1$ norm is less than the $L^\infty$ norm scaled by the cardinality. -/ lemma pi.sum_nnnorm_apply_le_nnnorm : ∑ i, ∥f i∥₊ ≤ fintype.card ι • ∥f∥₊ := nnreal.coe_sum.trans_le $ pi.sum_norm_apply_le_norm _ end pi lemma tendsto_iff_norm_tendsto_zero {f : α → E} {a : filter α} {b : E} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] } lemma tendsto_zero_iff_norm_tendsto_zero {f : α → E} {a : filter α} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) := by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] } lemma comap_norm_nhds_zero : comap norm (𝓝 0) = 𝓝 (0 : E) := by simpa only [dist_zero_right] using nhds_comap_dist (0 : E) /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.order`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : α → E} {g : α → ℝ} {t₀ : filter α} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : α → E} {g : α → ℝ} {t₀ : filter α} (h : ∀ n, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' lemma tendsto_norm_sub_self (x : E) : tendsto (λ g : E, ∥g - x∥) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:E)) (𝓝 x) _) lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : E → ℝ) := by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : E) lemma lipschitz_with_one_nnnorm : lipschitz_with 1 (has_nnnorm.nnnorm : E → ℝ≥0) := lipschitz_with_one_norm lemma uniform_continuous_norm : uniform_continuous (norm : E → ℝ) := lipschitz_with_one_norm.uniform_continuous lemma uniform_continuous_nnnorm : uniform_continuous (λ (a : E), ∥a∥₊) := uniform_continuous_norm.subtype_mk _ @[continuity] lemma continuous_norm : continuous (λg:E, ∥g∥) := uniform_continuous_norm.continuous @[continuity] lemma continuous_nnnorm : continuous (λ (a : E), ∥a∥₊) := uniform_continuous_nnnorm.continuous lemma tendsto_norm {x : E} : tendsto (λg : E, ∥g∥) (𝓝 x) (𝓝 ∥x∥) := continuous_norm.continuous_at lemma tendsto_norm_zero : tendsto (λg : E, ∥g∥) (𝓝 0) (𝓝 0) := continuous_norm.tendsto' 0 0 norm_zero /-- A helper lemma used to prove that the (scalar or usual) product of a function that tends to zero and a bounded function tends to zero. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `∥op x y∥ ≤ A * ∥x∥ * ∥y∥` for some constant A instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`. -/ lemma filter.tendsto.op_zero_is_bounded_under_le' {f : α → E} {g : α → F} {l : filter α} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) (op : E → F → G) (h_op : ∃ A, ∀ x y, ∥op x y∥ ≤ A * ∥x∥ * ∥y∥) : tendsto (λ x, op (f x) (g x)) l (𝓝 0) := begin cases h_op with A h_op, rcases hg with ⟨C, hC⟩, rw eventually_map at hC, rw normed_add_comm_group.tendsto_nhds_zero at hf ⊢, intros ε ε₀, rcases exists_pos_mul_lt ε₀ (A * C) with ⟨δ, δ₀, hδ⟩, filter_upwards [hf δ δ₀, hC] with i hf hg, refine (h_op _ _).trans_lt _, cases le_total A 0 with hA hA, { exact (mul_nonpos_of_nonpos_of_nonneg (mul_nonpos_of_nonpos_of_nonneg hA (norm_nonneg _)) (norm_nonneg _)).trans_lt ε₀ }, calc A * ∥f i∥ * ∥g i∥ ≤ A * δ * C : mul_le_mul (mul_le_mul_of_nonneg_left hf.le hA) hg (norm_nonneg _) (mul_nonneg hA δ₀.le) ... = A * C * δ : mul_right_comm _ _ _ ... < ε : hδ end /-- A helper lemma used to prove that the (scalar or usual) product of a function that tends to zero and a bounded function tends to zero. This lemma is formulated for any binary operation `op : E → F → G` with an estimate `∥op x y∥ ≤ ∥x∥ * ∥y∥` instead of multiplication so that it can be applied to `(*)`, `flip (*)`, `(•)`, and `flip (•)`. -/ lemma filter.tendsto.op_zero_is_bounded_under_le {f : α → E} {g : α → F} {l : filter α} (hf : tendsto f l (𝓝 0)) (hg : is_bounded_under (≤) l (norm ∘ g)) (op : E → F → G) (h_op : ∀ x y, ∥op x y∥ ≤ ∥x∥ * ∥y∥) : tendsto (λ x, op (f x) (g x)) l (𝓝 0) := hf.op_zero_is_bounded_under_le' hg op ⟨1, λ x y, (one_mul (∥x∥)).symm ▸ h_op x y⟩ section variables {l : filter α} {f : α → E} {a : E} lemma filter.tendsto.norm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto_norm.comp h lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥₊) l (𝓝 (∥a∥₊)) := tendsto.comp continuous_nnnorm.continuous_at h end section variables [topological_space α] {f : α → E} {s : set α} {a : α} {b : E} lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h lemma continuous.nnnorm (h : continuous f) : continuous (λ x, ∥f x∥₊) := continuous_nnnorm.comp h lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥₊) a := h.nnnorm lemma continuous_within_at.norm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥) s a := h.norm lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥₊) s a := h.nnnorm lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s := λ x hx, (h x hx).norm lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥₊) s := λ x hx, (h x hx).nnnorm end /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter α} {f : α → E} (h : tendsto (λ y, ∥f y∥) l at_top) (x : E) : ∀ᶠ y in l, f y ≠ x := (h.eventually_ne_at_top _).mono $ λ x, ne_of_apply_ne norm @[priority 100] -- see Note [lower instance priority] instance seminormed_add_comm_group.has_lipschitz_add : has_lipschitz_add E := { lipschitz_add := ⟨2, lipschitz_with.prod_fst.add lipschitz_with.prod_snd⟩ } /-- A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group E := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group E := by apply_instance -- short-circuit type class inference lemma seminormed_add_comm_group.mem_closure_iff {s : set E} {x : E} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, ∥x - y∥ < ε := by simp [metric.mem_closure_iff, dist_eq_norm] lemma norm_le_zero_iff' [t0_space E] {g : E} : ∥g∥ ≤ 0 ↔ g = 0 := begin letI : normed_add_comm_group E := { to_metric_space := metric.of_t0_pseudo_metric_space E, .. ‹seminormed_add_comm_group E› }, rw [← dist_zero_right], exact dist_le_zero end lemma norm_eq_zero_iff' [t0_space E] {g : E} : ∥g∥ = 0 ↔ g = 0 := (norm_nonneg g).le_iff_eq.symm.trans norm_le_zero_iff' lemma norm_pos_iff' [t0_space E] {g : E} : 0 < ∥g∥ ↔ g ≠ 0 := by rw [← not_le, norm_le_zero_iff'] lemma cauchy_seq_sum_of_eventually_eq {u v : ℕ → E} {N : ℕ} (huv : ∀ n ≥ N, u n = v n) (hv : cauchy_seq (λ n, ∑ k in range (n+1), v k)) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin let d : ℕ → E := λ n, ∑ k in range (n + 1), (u k - v k), rw show (λ n, ∑ k in range (n + 1), u k) = d + (λ n, ∑ k in range (n + 1), v k), by { ext n, simp [d] }, have : ∀ n ≥ N, d n = d N, { intros n hn, dsimp [d], rw eventually_constant_sum _ hn, intros m hm, simp [huv m hm] }, exact (tendsto_at_top_of_eventually_const this).cauchy_seq.add hv end end seminormed_add_comm_group section normed_add_comm_group /-- Construct a `normed_add_comm_group` from a `seminormed_add_comm_group` satisfying `∀ x, ∥x∥ = 0 → x = 0`. This avoids having to go back to the `(pseudo_)metric_space` level when declaring a `normed_add_comm_group` instance as a special case of a more general `seminormed_add_comm_group` instance. -/ def normed_add_comm_group.of_separation [h₁ : seminormed_add_comm_group E] (h₂ : ∀ x : E, ∥x∥ = 0 → x = 0) : normed_add_comm_group E := { to_metric_space := { eq_of_dist_eq_zero := λ x y hxy, by rw h₁.dist_eq at hxy; rw ← sub_eq_zero; exact h₂ _ hxy }, ..h₁ } /-- Construct a normed group from a translation invariant distance -/ def normed_add_comm_group.of_add_dist [has_norm E] [add_comm_group E] [metric_space E] (H1 : ∀ x : E, ∥x∥ = dist x 0) (H2 : ∀ x y z : E, dist x y ≤ dist (x + z) (y + z)) : normed_add_comm_group E := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_add_comm_group.core (E : Type*) [add_comm_group E] [has_norm E] : Prop := (norm_eq_zero_iff : ∀ x : E, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : E, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : E, ∥-x∥ = ∥x∥) /-- The `seminormed_add_comm_group.core` induced by a `normed_add_comm_group.core`. -/ lemma normed_add_comm_group.core.to_seminormed_add_comm_group.core {E : Type*} [add_comm_group E] [has_norm E] (C : normed_add_comm_group.core E) : seminormed_add_comm_group.core E := { norm_zero := (C.norm_eq_zero_iff 0).2 rfl, triangle := C.triangle, norm_neg := C.norm_neg } /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ def normed_add_comm_group.of_core (E : Type*) [add_comm_group E] [has_norm E] (C : normed_add_comm_group.core E) : normed_add_comm_group E := { eq_of_dist_eq_zero := λ x y h, begin rw [dist_eq_norm] at h, exact sub_eq_zero.mp ((C.norm_eq_zero_iff _).1 h) end ..seminormed_add_comm_group.of_core E (normed_add_comm_group.core.to_seminormed_add_comm_group.core C) } variables [normed_add_comm_group E] [normed_add_comm_group F] {x y : E} @[simp] lemma norm_eq_zero {g : E} : ∥g∥ = 0 ↔ g = 0 := norm_eq_zero_iff' lemma norm_ne_zero_iff {g : E} : ∥g∥ ≠ 0 ↔ g ≠ 0 := not_congr norm_eq_zero @[simp] lemma norm_pos_iff {g : E} : 0 < ∥ g ∥ ↔ g ≠ 0 := norm_pos_iff' @[simp] lemma norm_le_zero_iff {g : E} : ∥g∥ ≤ 0 ↔ g = 0 := norm_le_zero_iff' lemma norm_sub_eq_zero_iff {u v : E} : ∥u - v∥ = 0 ↔ u = v := by rw [norm_eq_zero, sub_eq_zero] lemma norm_sub_pos_iff : 0 < ∥x - y∥ ↔ x ≠ y := by { rw [(norm_nonneg _).lt_iff_ne, ne_comm], exact norm_sub_eq_zero_iff.not } lemma eq_of_norm_sub_le_zero {g h : E} (a : ∥g - h∥ ≤ 0) : g = h := by rwa [← sub_eq_zero, ← norm_le_zero_iff] lemma eq_of_norm_sub_eq_zero {u v : E} (h : ∥u - v∥ = 0) : u = v := norm_sub_eq_zero_iff.1 h @[simp] lemma nnnorm_eq_zero {a : E} : ∥a∥₊ = 0 ↔ a = 0 := by rw [← nnreal.coe_eq_zero, coe_nnnorm, norm_eq_zero] lemma nnnorm_ne_zero_iff {g : E} : ∥g∥₊ ≠ 0 ↔ g ≠ 0 := not_congr nnnorm_eq_zero variables (E) /-- The norm of a normed group as an additive group norm. -/ def norm_add_group_norm : add_group_norm E := ⟨norm, norm_zero, norm_add_le, norm_neg, λ {g : E}, norm_eq_zero.mp⟩ @[simp] lemma coe_norm_add_group_norm : ⇑(norm_add_group_norm E) = norm := rfl variables {E} /-- An injective group homomorphism from an `add_comm_group` to a `normed_add_comm_group` induces a `normed_add_comm_group` structure on the domain. See note [reducible non-instances]. -/ @[reducible] def normed_add_comm_group.induced {E} [add_comm_group E] (f : E →+ F) (h : function.injective f) : normed_add_comm_group E := { .. seminormed_add_comm_group.induced f, .. metric_space.induced f h normed_add_comm_group.to_metric_space, } /-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/ instance add_subgroup.normed_add_comm_group (s : add_subgroup E) : normed_add_comm_group s := normed_add_comm_group.induced s.subtype subtype.coe_injective /-- A submodule of a normed group is also a normed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.normed_add_comm_group {𝕜 E : Type*} {_ : ring 𝕜} [normed_add_comm_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_add_comm_group s := { ..submodule.seminormed_add_comm_group s } instance ulift.normed_add_comm_group : normed_add_comm_group (ulift E) := { ..ulift.seminormed_add_comm_group } /-- normed group instance on the product of two normed groups, using the sup norm. -/ noncomputable instance prod.normed_add_comm_group : normed_add_comm_group (E × F) := { ..prod.seminormed_add_comm_group } /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ noncomputable instance pi.normed_add_comm_group {π : ι → Type*} [fintype ι] [Π i, normed_add_comm_group (π i)] : normed_add_comm_group (Πi, π i) := { ..pi.seminormed_add_comm_group } lemma tendsto_norm_sub_self_punctured_nhds (a : E) : tendsto (λ x, ∥x - a∥) (𝓝[≠] a) (𝓝[>] 0) := (tendsto_norm_sub_self a).inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 $ sub_ne_zero.2 hx lemma tendsto_norm_nhds_within_zero : tendsto (norm : E → ℝ) (𝓝[≠] 0) (𝓝[>] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff.2 /-! Some relations with `has_compact_support` -/ lemma has_compact_support_norm_iff [topological_space α] {f : α → E} : has_compact_support (λ x, ∥ f x ∥) ↔ has_compact_support f := has_compact_support_comp_left $ λ x, norm_eq_zero alias has_compact_support_norm_iff ↔ _ has_compact_support.norm lemma continuous.bounded_above_of_compact_support [topological_space α] {f : α → E} (hf : continuous f) (hsupp : has_compact_support f) : ∃ C, ∀ x, ∥f x∥ ≤ C := by simpa [bdd_above_def] using hf.norm.bdd_above_range_of_has_compact_support hsupp.norm end normed_add_comm_group
0771827bf661ec10f1d6c96742c1bbcbed2b3a82
e8aa886451ad759d8f2621790f1748a9c7d9e820
/src/category_theory/limits/shapes/binary_products.lean
0145d00e34d4ace50a813398ede7b207258534ec
[ "Apache-2.0" ]
permissive
siegelzero/mathlib
04c39faa5d6c1d7799adff1f5cf0710c59def716
64fa9a2062bc18cdfac3b1bf03a1f714cb434f86
refs/heads/master
1,649,847,954,618
1,586,747,318,000
1,586,747,318,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,859
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.shapes.finite_products import category_theory.limits.shapes.terminal import category_theory.discrete_category /-! # Binary (co)products We define a category `walking_pair`, which is the index category for a binary (co)product diagram. A convenience method `pair X Y` constructs the functor from the walking pair, hitting the given objects. We define `prod X Y` and `coprod X Y` as limits and colimits of such functors. Typeclasses `has_binary_products` and `has_binary_coproducts` assert the existence of (co)limits shaped as walking pairs. -/ universes v u open category_theory namespace category_theory.limits /-- The type of objects for the diagram indexing a binary (co)product. -/ @[derive decidable_eq] inductive walking_pair : Type v | left | right open walking_pair instance fintype_walking_pair : fintype walking_pair := { elems := [left, right].to_finset, complete := λ x, by { cases x; simp } } variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 /-- The diagram on the walking pair, sending the two points to `X` and `Y`. -/ def pair (X Y : C) : discrete walking_pair ⥤ C := functor.of_function (λ j, walking_pair.cases_on j X Y) @[simp] lemma pair_obj_left (X Y : C) : (pair X Y).obj left = X := rfl @[simp] lemma pair_obj_right (X Y : C) : (pair X Y).obj right = Y := rfl section variables {F G : discrete walking_pair.{v} ⥤ C} (f : F.obj left ⟶ G.obj left) (g : F.obj right ⟶ G.obj right) /-- The natural transformation between two functors out of the walking pair, specified by its components. -/ def map_pair : F ⟶ G := { app := λ j, match j with | left := f | right := g end } @[simp] lemma map_pair_left : (map_pair f g).app left = f := rfl @[simp] lemma map_pair_right : (map_pair f g).app right = g := rfl /-- The natural isomorphism between two functors out of the walking pair, specified by its components. -/ @[simps] def map_pair_iso (f : F.obj left ≅ G.obj left) (g : F.obj right ≅ G.obj right) : F ≅ G := { hom := map_pair f.hom g.hom, inv := map_pair f.inv g.inv, hom_inv_id' := begin ext j, cases j; { dsimp, simp, } end, inv_hom_id' := begin ext j, cases j; { dsimp, simp, } end } end section variables {D : Type u} [𝒟 : category.{v} D] include 𝒟 /-- The natural isomorphism between `pair X Y ⋙ F` and `pair (F.obj X) (F.obj Y)`. -/ def pair_comp (X Y : C) (F : C ⥤ D) : pair X Y ⋙ F ≅ pair (F.obj X) (F.obj Y) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) end /-- Every functor out of the walking pair is naturally isomorphic (actually, equal) to a `pair` -/ def diagram_iso_pair (F : discrete walking_pair ⥤ C) : F ≅ pair (F.obj walking_pair.left) (F.obj walking_pair.right) := map_pair_iso (eq_to_iso rfl) (eq_to_iso rfl) abbreviation binary_fan (X Y : C) := cone (pair X Y) abbreviation binary_cofan (X Y : C) := cocone (pair X Y) variables {X Y : C} def binary_fan.mk {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : binary_fan X Y := { X := P, π := { app := λ j, walking_pair.cases_on j π₁ π₂ }} def binary_cofan.mk {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : binary_cofan X Y := { X := P, ι := { app := λ j, walking_pair.cases_on j ι₁ ι₂ }} @[simp] lemma binary_fan.mk_π_app_left {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.left = π₁ := rfl @[simp] lemma binary_fan.mk_π_app_right {P : C} (π₁ : P ⟶ X) (π₂ : P ⟶ Y) : (binary_fan.mk π₁ π₂).π.app walking_pair.right = π₂ := rfl @[simp] lemma binary_cofan.mk_ι_app_left {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.left = ι₁ := rfl @[simp] lemma binary_cofan.mk_ι_app_right {P : C} (ι₁ : X ⟶ P) (ι₂ : Y ⟶ P) : (binary_cofan.mk ι₁ ι₂).ι.app walking_pair.right = ι₂ := rfl abbreviation prod (X Y : C) [has_limit (pair X Y)] := limit (pair X Y) abbreviation coprod (X Y : C) [has_colimit (pair X Y)] := colimit (pair X Y) notation X ` ⨯ `:20 Y:20 := prod X Y notation X ` ⨿ `:20 Y:20 := coprod X Y abbreviation prod.fst {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ X := limit.π (pair X Y) walking_pair.left abbreviation prod.snd {X Y : C} [has_limit (pair X Y)] : X ⨯ Y ⟶ Y := limit.π (pair X Y) walking_pair.right abbreviation coprod.inl {X Y : C} [has_colimit (pair X Y)] : X ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.left abbreviation coprod.inr {X Y : C} [has_colimit (pair X Y)] : Y ⟶ X ⨿ Y := colimit.ι (pair X Y) walking_pair.right abbreviation prod.lift {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) : W ⟶ X ⨯ Y := limit.lift _ (binary_fan.mk f g) abbreviation coprod.desc {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) : X ⨿ Y ⟶ W := colimit.desc _ (binary_cofan.mk f g) instance prod.mono_lift_of_mono_left {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono f] : mono (prod.lift f g) := mono_of_mono_fac $ show prod.lift f g ≫ prod.fst = f, by simp instance prod.mono_lift_of_mono_right {W X Y : C} [has_limit (pair X Y)] (f : W ⟶ X) (g : W ⟶ Y) [mono g] : mono (prod.lift f g) := mono_of_mono_fac $ show prod.lift f g ≫ prod.snd = g, by simp instance coprod.epi_desc_of_epi_left {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi f] : epi (coprod.desc f g) := epi_of_epi_fac $ show coprod.inl ≫ coprod.desc f g = f, by simp instance coprod.epi_desc_of_epi_right {W X Y : C} [has_colimit (pair X Y)] (f : X ⟶ W) (g : Y ⟶ W) [epi g] : epi (coprod.desc f g) := epi_of_epi_fac $ show coprod.inr ≫ coprod.desc f g = g, by simp abbreviation prod.map {W X Y Z : C} [has_limits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨯ X ⟶ Y ⨯ Z := lim.map (map_pair f g) abbreviation coprod.map {W X Y Z : C} [has_colimits_of_shape.{v} (discrete walking_pair) C] (f : W ⟶ Y) (g : X ⟶ Z) : W ⨿ X ⟶ Y ⨿ Z := colim.map (map_pair f g) variables (C) class has_binary_products := (has_limits_of_shape : has_limits_of_shape.{v} (discrete walking_pair) C) class has_binary_coproducts := (has_colimits_of_shape : has_colimits_of_shape.{v} (discrete walking_pair) C) attribute [instance] has_binary_products.has_limits_of_shape has_binary_coproducts.has_colimits_of_shape @[priority 100] -- see Note [lower instance priority] instance [has_finite_products.{v} C] : has_binary_products.{v} C := { has_limits_of_shape := by apply_instance } @[priority 100] -- see Note [lower instance priority] instance [has_finite_coproducts.{v} C] : has_binary_coproducts.{v} C := { has_colimits_of_shape := by apply_instance } /-- If `C` has all limits of diagrams `pair X Y`, then it has all binary products -/ def has_binary_products_of_has_limit_pair [Π {X Y : C}, has_limit (pair X Y)] : has_binary_products.{v} C := { has_limits_of_shape := { has_limit := λ F, has_limit_of_iso (diagram_iso_pair F).symm } } /-- If `C` has all colimits of diagrams `pair X Y`, then it has all binary coproducts -/ def has_binary_coproducts_of_has_colimit_pair [Π {X Y : C}, has_colimit (pair X Y)] : has_binary_coproducts.{v} C := { has_colimits_of_shape := { has_colimit := λ F, has_colimit_of_iso (diagram_iso_pair F) } } section variables {C} [has_binary_products.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary product. -/ @[simps] def prod.braiding (P Q : C) : P ⨯ Q ≅ Q ⨯ P := { hom := prod.lift prod.snd prod.fst, inv := prod.lift prod.snd prod.fst } @[simp] lemma prod.symmetry' (P Q : C) : prod.lift prod.snd prod.fst ≫ prod.lift prod.snd prod.fst = 𝟙 (P ⨯ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma prod.symmetry (P Q : C) : (prod.braiding P Q).hom ≫ (prod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary products. -/ @[simps] def prod.associator (P Q R : C) : (P ⨯ Q) ⨯ R ≅ P ⨯ (Q ⨯ R) := { hom := prod.lift (prod.fst ≫ prod.fst) (prod.lift (prod.fst ≫ prod.snd) prod.snd), inv := prod.lift (prod.lift prod.fst (prod.snd ≫ prod.fst)) (prod.snd ≫ prod.snd) } lemma prod.pentagon (W X Y Z : C) : prod.map ((prod.associator W X Y).hom) (𝟙 Z) ≫ (prod.associator W (X ⨯ Y) Z).hom ≫ prod.map (𝟙 W) ((prod.associator X Y Z).hom) = (prod.associator (W ⨯ X) Y Z).hom ≫ (prod.associator W X (Y⨯Z)).hom := by tidy lemma prod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : prod.map (prod.map f₁ f₂) f₃ ≫ (prod.associator Y₁ Y₂ Y₃).hom = (prod.associator X₁ X₂ X₃).hom ≫ prod.map f₁ (prod.map f₂ f₃) := by tidy variables [has_terminal.{v} C] /-- The left unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.left_unitor (P : C) : ⊤_ C ⨯ P ≅ P := { hom := prod.snd, inv := prod.lift (terminal.from P) (𝟙 _) } /-- The right unitor isomorphism for binary products with the terminal object. -/ @[simps] def prod.right_unitor (P : C) : P ⨯ ⊤_ C ≅ P := { hom := prod.fst, inv := prod.lift (𝟙 _) (terminal.from P) } lemma prod.triangle (X Y : C) : (prod.associator X (⊤_ C) Y).hom ≫ prod.map (𝟙 X) ((prod.left_unitor Y).hom) = prod.map ((prod.right_unitor X).hom) (𝟙 Y) := by tidy end section variables {C} [has_binary_coproducts.{v} C] local attribute [tidy] tactic.case_bash /-- The braiding isomorphism which swaps a binary coproduct. -/ @[simps] def coprod.braiding (P Q : C) : P ⨿ Q ≅ Q ⨿ P := { hom := coprod.desc coprod.inr coprod.inl, inv := coprod.desc coprod.inr coprod.inl } @[simp] lemma coprod.symmetry' (P Q : C) : coprod.desc coprod.inr coprod.inl ≫ coprod.desc coprod.inr coprod.inl = 𝟙 (P ⨿ Q) := by tidy /-- The braiding isomorphism is symmetric. -/ lemma coprod.symmetry (P Q : C) : (coprod.braiding P Q).hom ≫ (coprod.braiding Q P).hom = 𝟙 _ := by simp /-- The associator isomorphism for binary coproducts. -/ @[simps] def coprod.associator (P Q R : C) : (P ⨿ Q) ⨿ R ≅ P ⨿ (Q ⨿ R) := { hom := coprod.desc (coprod.desc coprod.inl (coprod.inl ≫ coprod.inr)) (coprod.inr ≫ coprod.inr), inv := coprod.desc (coprod.inl ≫ coprod.inl) (coprod.desc (coprod.inr ≫ coprod.inl) coprod.inr) } lemma coprod.pentagon (W X Y Z : C) : coprod.map ((coprod.associator W X Y).hom) (𝟙 Z) ≫ (coprod.associator W (X⨿Y) Z).hom ≫ coprod.map (𝟙 W) ((coprod.associator X Y Z).hom) = (coprod.associator (W⨿X) Y Z).hom ≫ (coprod.associator W X (Y⨿Z)).hom := by tidy lemma coprod.associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : coprod.map (coprod.map f₁ f₂) f₃ ≫ (coprod.associator Y₁ Y₂ Y₃).hom = (coprod.associator X₁ X₂ X₃).hom ≫ coprod.map f₁ (coprod.map f₂ f₃) := by tidy variables [has_initial.{v} C] /-- The left unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.left_unitor (P : C) : ⊥_ C ⨿ P ≅ P := { hom := coprod.desc (initial.to P) (𝟙 _), inv := coprod.inr } /-- The right unitor isomorphism for binary coproducts with the initial object. -/ @[simps] def coprod.right_unitor (P : C) : P ⨿ ⊥_ C ≅ P := { hom := coprod.desc (𝟙 _) (initial.to P), inv := coprod.inl } lemma coprod.triangle (X Y : C) : (coprod.associator X (⊥_ C) Y).hom ≫ coprod.map (𝟙 X) ((coprod.left_unitor Y).hom) = coprod.map ((coprod.right_unitor X).hom) (𝟙 Y) := by tidy end end category_theory.limits
b1632d7eee2cf399d2cff7c589444cf89bda8b5e
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/logic/nontrivial.lean
4163cc2d272f6cbef91e5d7ae4e78b7c688c54cd
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,463
lean
/- Copyright (c) 2020 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 data.pi import data.prod import data.subtype import logic.unique import logic.function.basic /-! # Nontrivial types A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `nontrivial` formalizing this property. -/ variables {α : Type*} {β : Type*} open_locale classical /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class nontrivial (α : Type*) : Prop := (exists_pair_ne : ∃ (x y : α), x ≠ y) lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y := ⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩ lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y := nontrivial.exists_pair_ne -- See Note [decidable namespace] protected lemma decidable.exists_ne [nontrivial α] [decidable_eq α] (x : α) : ∃ y, y ≠ x := begin rcases exists_pair_ne α with ⟨y, y', h⟩, by_cases hx : x = y, { rw ← hx at h, exact ⟨y', h.symm⟩ }, { exact ⟨y, ne.symm hx⟩ } end lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x := by classical; exact decidable.exists_ne x -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α := ⟨⟨x, y, h⟩⟩ -- `x` and `y` are explicit here, as they are often needed to guide typechecking of `h`. lemma nontrivial_of_lt [preorder α] (x y : α) (h : x < y) : nontrivial α := ⟨⟨x, y, ne_of_lt h⟩⟩ lemma nontrivial_iff_exists_ne (x : α) : nontrivial α ↔ ∃ y, y ≠ x := ⟨λ h, @exists_ne α h x, λ ⟨y, hy⟩, nontrivial_of_ne _ _ hy⟩ lemma subtype.nontrivial_iff_exists_ne (p : α → Prop) (x : subtype p) : nontrivial (subtype p) ↔ ∃ (y : α) (hy : p y), y ≠ x := by simp only [nontrivial_iff_exists_ne x, subtype.exists, ne.def, subtype.ext_iff, subtype.coe_mk] instance : nontrivial Prop := ⟨⟨true, false, true_ne_false⟩⟩ /-- See Note [lower instance priority] Note that since this and `nonempty_of_inhabited` are the most "obvious" way to find a nonempty instance if no direct instance can be found, we give this a higher priority than the usual `100`. -/ @[priority 500] instance nontrivial.to_nonempty [nontrivial α] : nonempty α := let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩ attribute [instance, priority 500] nonempty_of_inhabited /-- An inhabited type is either nontrivial, or has a unique element. -/ noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] : psum (nontrivial α) (unique α) := if h : nontrivial α then psum.inl h else psum.inr { default := default α, uniq := λ (x : α), begin change x = default α, contrapose! h, use [x, default α] end } lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y := ⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩ lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α := by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl } lemma not_subsingleton (α) [h : nontrivial α] : ¬subsingleton α := let ⟨⟨x, y, hxy⟩⟩ := h in λ ⟨h'⟩, hxy $ h' x y /-- A type is either a subsingleton or nontrivial. -/ lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α := by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ } lemma false_of_nontrivial_of_subsingleton (α : Type*) [nontrivial α] [subsingleton α] : false := let ⟨x, y, h⟩ := exists_pair_ne α in h $ subsingleton.elim x y instance option.nontrivial [nonempty α] : nontrivial (option α) := by { inhabit α, use [none, some (default α)] } /-- Pushforward a `nontrivial` instance along an injective function. -/ protected lemma function.injective.nontrivial [nontrivial α] {f : α → β} (hf : function.injective f) : nontrivial β := let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩ /-- Pullback a `nontrivial` instance along a surjective function. -/ protected lemma function.surjective.nontrivial [nontrivial β] {f : α → β} (hf : function.surjective f) : nontrivial α := begin rcases exists_pair_ne β with ⟨x, y, h⟩, rcases hf x with ⟨x', hx'⟩, rcases hf y with ⟨y', hy'⟩, have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] }, exact ⟨⟨x', y', this⟩⟩ end /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected lemma function.injective.exists_ne [nontrivial α] {f : α → β} (hf : function.injective f) (y : β) : ∃ x, f x ≠ y := begin rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩, by_cases h : f x₂ = y, { exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ }, { exact ⟨x₂, h⟩ } end instance nontrivial_prod_right [nonempty α] [nontrivial β] : nontrivial (α × β) := prod.snd_surjective.nontrivial instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) := prod.fst_surjective.nontrivial namespace pi variables {I : Type*} {f : I → Type*} /-- A pi type is nontrivial if it's nonempty everywhere and nontrivial somewhere. -/ lemma nontrivial_at (i' : I) [inst : Π i, nonempty (f i)] [nontrivial (f i')] : nontrivial (Π i : I, f i) := by classical; exact (function.update_injective (λ i, classical.choice (inst i)) i').nontrivial /-- As a convenience, provide an instance automatically if `(f (default I))` is nontrivial. If a different index has the non-trivial type, then use `haveI := nontrivial_at that_index`. -/ instance nontrivial [inhabited I] [inst : Π i, nonempty (f i)] [nontrivial (f (default I))] : nontrivial (Π i : I, f i) := nontrivial_at (default I) end pi instance function.nontrivial [h : nonempty α] [nontrivial β] : nontrivial (α → β) := h.elim $ λ a, pi.nontrivial_at a mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic" protected lemma subsingleton.le [preorder α] [subsingleton α] (x y : α) : x ≤ y := le_of_eq (subsingleton.elim x y) attribute [nontriviality] eq_iff_true_of_subsingleton subsingleton.le namespace tactic /-- Tries to generate a `nontrivial α` instance by performing case analysis on `subsingleton_or_nontrivial α`, attempting to discharge the subsingleton branch using lemmas with `@[nontriviality]` attribute, including `subsingleton.le` and `eq_iff_true_of_subsingleton`. -/ meta def nontriviality_by_elim (α : expr) (lems : interactive.parse simp_arg_list) : tactic unit := do alternative ← to_expr ``(subsingleton_or_nontrivial %%α), n ← get_unused_name "_inst", tactic.cases alternative [n, n], (solve1 $ do reset_instance_cache, apply_instance <|> interactive.simp none none ff lems [`nontriviality] (interactive.loc.ns [none])) <|> fail format!"Could not prove goal assuming `subsingleton {α}`", reset_instance_cache /-- Tries to generate a `nontrivial α` instance using `nontrivial_of_ne` or `nontrivial_of_lt` and local hypotheses. -/ meta def nontriviality_by_assumption (α : expr) : tactic unit := do n ← get_unused_name "_inst", to_expr ``(nontrivial %%α) >>= assert n, apply_instance <|> `[solve_by_elim [nontrivial_of_ne, nontrivial_of_lt]], reset_instance_cache end tactic namespace tactic.interactive open tactic setup_tactic_parser /-- Attempts to generate a `nontrivial α` hypothesis. The tactic first looks for an instance using `apply_instance`. If the goal is an (in)equality, the type `α` is inferred from the goal. Otherwise, the type needs to be specified in the tactic invocation, as `nontriviality α`. The `nontriviality` tactic will first look for strict inequalities amongst the hypotheses, and use these to derive the `nontrivial` instance directly. Otherwise, it will perform a case split on `subsingleton α ∨ nontrivial α`, and attempt to discharge the `subsingleton` goal using `simp [lemmas] with nontriviality`, where `[lemmas]` is a list of additional `simp` lemmas that can be passed to `nontriviality` using the syntax `nontriviality α using [lemmas]`. ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : 0 < a := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. assumption, end ``` ``` example {R : Type} [comm_ring R] {r s : R} : r * s = s * r := begin nontriviality, -- There is now a `nontrivial R` hypothesis available. apply mul_comm, end ``` ``` example {R : Type} [ordered_ring R] {a : R} (h : 0 < a) : (2 : ℕ) ∣ 4 := begin nontriviality R, -- there is now a `nontrivial R` hypothesis available. dec_trivial end ``` ``` def myeq {α : Type} (a b : α) : Prop := a = b example {α : Type} (a b : α) (h : a = b) : myeq a b := begin success_if_fail { nontriviality α }, -- Fails nontriviality α using [myeq], -- There is now a `nontrivial α` hypothesis available assumption end ``` -/ meta def nontriviality (t : parse texpr?) (lems : parse (tk "using" *> simp_arg_list <|> pure [])) : tactic unit := do α ← match t with | some α := to_expr α | none := (do t ← mk_mvar, e ← to_expr ``(@eq %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_le.le %%t _ _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@ne %%t _ _), target >>= unify e, return t) <|> (do t ← mk_mvar, e ← to_expr ``(@has_lt.lt %%t _ _ _), target >>= unify e, return t) <|> fail "The goal is not an (in)equality, so you'll need to specify the desired `nontrivial α` instance by invoking `nontriviality α`." end, nontriviality_by_assumption α <|> nontriviality_by_elim α lems add_tactic_doc { name := "nontriviality", category := doc_category.tactic, decl_names := [`tactic.interactive.nontriviality], tags := ["logic", "type class"] } end tactic.interactive namespace bool instance : nontrivial bool := ⟨⟨tt,ff, tt_eq_ff_eq_false⟩⟩ end bool
3b0b14c9f7cc232ef58ac8d795b2490af7ec0d28
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.40.lean
e8b9473e56e531101ab474394ac897e6e1a798e7
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
211
lean
/- page 91 -/ import standard open nat namespace hide -- BEGIN inductive vector (A : Type) : nat → Type := | nil {} : vector A zero | cons : Π {n}, A → vector A n → vector A (succ n) -- END end hide
e704ac24e7a46243296396c1b0cc56b687f671bb
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/src/game/world10/level3.lean
4938b12fe10ac1a87fa8795b0f06030f8a3e3352
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
2,227
lean
import game.world10.level2 -- hide namespace mynat -- hide /- # Inequality world. ## Level 3: `le_succ_of_le` We have seen how the `use` tactic makes progress on goals of the form `⊢ ∃ c, ...`. But what do we do when we have a *hypothesis* of the form `h : ∃ c, ...`? The hypothesis claims that there exists some natural number `c` with some property. How are we going to get to that natural number `c`? It turns out that the `cases` tactic can be used (just like it was used to extract information from `∧` and `∨` and `↔` hypotheses). Let me talk you through the proof of $a\le b\implies a\le\operatorname{succ}(b)$. The goal is an implication so we clearly want to start with `intro h,` . After this, if you *want*, you can do something like `rw le_iff_exists_add at h ⊢,` (get the sideways T with `\|-` then space). This changes the `≤` into its `∃` form in `h` and the goal -- but if you are happy of just *seeing* the `∃` whenever you read a `≤` then you don't need to do this line. Our hypothesis `h` is now `∃ (c : mynat), b = a + c` (or `a ≤ b` if you elected not to do the definitional rewriting) so `cases h with c hc,` gives you the natural number `c` and the hypothesis `hc : b = a + d`. Now use `use` wisely and you're home. -/ /- Lemma For all naturals $a$, $b$, if $a\leq b$ then $a\leq \operatorname{succ}(b)$. -/ theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) := begin [nat_num_game] intro h, cases h with c hc, rw hc, use c + 1, refl, end /- Did you use `succ c` or `c + 1` or `1 + c`? Those numbers are all equal, right? So it doesn't matter which one you use, right? Here's an interesting question. If you copy the proof below into the box above, and then fill in the `???` below with `succ c`, will this proof compile? (move your cursor to after the final comma to see what Lean thinks). What about if you `use 1 + c`? What about if you `use c + 1`? Can you work out what is going on? Does it help if I tell you that the *definition* of `1` is `succ 0`? ``` theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) := begin [nat_num_game] intro h, cases h with c hc, rw hc, use ???, refl, end ``` -/ end mynat -- hide
8510f7652fdbf919dc3e2f5b11890534d42e2941
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/finsupp/lattice.lean
536bb9a1da5b98c7ebb0bb82379c93bd89123d3f
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,134
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import data.finsupp.basic /-! # Lattice structure on finsupps This file provides instances of ordered structures on finsupps. -/ open_locale classical noncomputable theory variables {α : Type*} {β : Type*} [has_zero β] {μ : Type*} [canonically_ordered_add_monoid μ] variables {γ : Type*} [canonically_linear_ordered_add_monoid γ] namespace finsupp instance : order_bot (α →₀ μ) := { bot := 0, bot_le := by simp [finsupp.le_def, ← bot_eq_zero], .. finsupp.partial_order} instance [semilattice_inf β] : semilattice_inf (α →₀ β) := { inf := zip_with (⊓) inf_idem, inf_le_left := λ a b c, inf_le_left, inf_le_right := λ a b c, inf_le_right, le_inf := λ a b c h1 h2 s, le_inf (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma inf_apply [semilattice_inf β] {a : α} {f g : α →₀ β} : (f ⊓ g) a = f a ⊓ g a := rfl @[simp] lemma support_inf {f g : α →₀ γ} : (f ⊓ g).support = f.support ∩ g.support := begin ext, simp only [inf_apply, mem_support_iff, ne.def, finset.mem_union, finset.mem_filter, finset.mem_inter], rw [← decidable.not_or_iff_and_not, ← not_congr], rw inf_eq_min, unfold min, split_ifs; { try {apply or_iff_left_of_imp}, try {apply or_iff_right_of_imp}, intro con, rw con at h, revert h, simp, } end instance [semilattice_sup β] : semilattice_sup (α →₀ β) := { sup := zip_with (⊔) sup_idem, le_sup_left := λ a b c, le_sup_left, le_sup_right := λ a b c, le_sup_right, sup_le := λ a b c h1 h2 s, sup_le (h1 s) (h2 s), ..finsupp.partial_order, } @[simp] lemma sup_apply [semilattice_sup β] {a : α} {f g : α →₀ β} : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma support_sup {f g : α →₀ γ} : (f ⊔ g).support = f.support ∪ g.support := begin ext, simp only [finset.mem_union, mem_support_iff, sup_apply, ne.def, ← bot_eq_zero], rw sup_eq_bot_iff, tauto, end instance lattice [lattice β] : lattice (α →₀ β) := { .. finsupp.semilattice_inf, .. finsupp.semilattice_sup} instance semilattice_inf_bot : semilattice_inf_bot (α →₀ γ) := { ..finsupp.order_bot, ..finsupp.lattice} lemma bot_eq_zero : (⊥ : α →₀ γ) = 0 := rfl lemma disjoint_iff {x y : α →₀ γ} : disjoint x y ↔ disjoint x.support y.support := begin unfold disjoint, repeat {rw le_bot_iff}, rw [finsupp.bot_eq_zero, ← finsupp.support_eq_empty, finsupp.support_inf], refl, end variable [partial_order β] /-- The order on `finsupp`s over a partial order embeds into the order on functions -/ def order_embedding_to_fun : (α →₀ β) ↪o (α → β) := ⟨⟨λ (f : α →₀ β) (a : α), f a, λ f g h, finsupp.ext (λ a, by { dsimp at h, rw h,} )⟩, λ a b, (@le_def _ _ _ _ a b).symm⟩ @[simp] lemma order_embedding_to_fun_apply {f : α →₀ β} {a : α} : order_embedding_to_fun f a = f a := rfl lemma monotone_to_fun : monotone (finsupp.to_fun : (α →₀ β) → (α → β)) := λ f g h a, le_def.1 h a end finsupp
3ac92111f6515b152d3c99a1f1b1b34859df9785
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/list/big_operators.lean
345c581d5a53a93443ce6f99841dcfa3d00c19aa
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
26,072
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, Floris van Doorn, Sébastien Gouëzel, Alex J. Best -/ import algebra.group_power import data.list.forall2 /-! # Sums and products from lists This file provides basic results about `list.prod`, `list.sum`, which calculate the product and sum of elements of a list and `list.alternating_prod`, `list.alternating_sum`, their alternating counterparts. These are defined in [`data.list.defs`](./defs). -/ variables {ι α M N P M₀ G R : Type*} namespace list section monoid variables [monoid M] [monoid N] [monoid P] {l l₁ l₂ : list M} {a : M} @[simp, to_additive] lemma prod_nil : ([] : list M).prod = 1 := rfl @[to_additive] lemma prod_singleton : [a].prod = a := one_mul a @[simp, to_additive] lemma prod_cons : (a :: l).prod = a * l.prod := calc (a :: l).prod = foldl (*) (a * 1) l : by simp only [list.prod, foldl_cons, one_mul, mul_one] ... = _ : foldl_assoc @[simp, to_additive] lemma prod_append : (l₁ ++ l₂).prod = l₁.prod * l₂.prod := calc (l₁ ++ l₂).prod = foldl (*) (foldl (*) 1 l₁ * 1) l₂ : by simp [list.prod] ... = l₁.prod * l₂.prod : foldl_assoc @[to_additive] lemma prod_concat : (l.concat a).prod = l.prod * a := by rw [concat_eq_append, prod_append, prod_singleton] @[simp, to_additive] lemma prod_join {l : list (list M)} : l.join.prod = (l.map list.prod).prod := by induction l; [refl, simp only [*, list.join, map, prod_append, prod_cons]] @[to_additive] lemma prod_eq_foldr : l.prod = foldr (*) 1 l := list.rec_on l rfl $ λ a l ihl, by rw [prod_cons, foldr_cons, ihl] @[simp, priority 500, to_additive] theorem prod_repeat (a : M) (n : ℕ) : (repeat a n).prod = a ^ n := begin induction n with n ih, { rw pow_zero, refl }, { rw [list.repeat_succ, list.prod_cons, ih, pow_succ] } end @[to_additive sum_eq_card_nsmul] lemma prod_eq_pow_card (l : list M) (m : M) (h : ∀ (x ∈ l), x = m) : l.prod = m ^ l.length := by rw [← prod_repeat, ← list.eq_repeat.mpr ⟨rfl, h⟩] @[to_additive] lemma prod_hom_rel (l : list ι) {r : M → N → Prop} {f : ι → M} {g : ι → N} (h₁ : r 1 1) (h₂ : ∀ ⦃i a b⦄, r a b → r (f i * a) (g i * b)) : r (l.map f).prod (l.map g).prod := list.rec_on l h₁ (λ a l hl, by simp only [map_cons, prod_cons, h₂ hl]) @[to_additive] lemma prod_hom (l : list M) {F : Type*} [monoid_hom_class F M N] (f : F) : (l.map f).prod = f l.prod := by { simp only [prod, foldl_map, ← map_one f], exact l.foldl_hom _ _ _ 1 (map_mul f) } @[to_additive] lemma prod_hom₂ (l : list ι) (f : M → N → P) (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) : (l.map $ λ i, f (f₁ i) (f₂ i)).prod = f (l.map f₁).prod (l.map f₂).prod := begin simp only [prod, foldl_map], convert l.foldl_hom₂ (λ a b, f a b) _ _ _ _ _ (λ a b i, _), { exact hf'.symm }, { exact hf _ _ _ _ } end @[simp, to_additive] lemma prod_map_mul {α : Type*} [comm_monoid α] {l : list ι} {f g : ι → α} : (l.map $ λ i, f i * g i).prod = (l.map f).prod * (l.map g).prod := l.prod_hom₂ (*) mul_mul_mul_comm (mul_one _) _ _ @[simp] lemma prod_map_neg {α} [comm_monoid α] [has_distrib_neg α] (l : list α) : (l.map has_neg.neg).prod = (-1) ^ l.length * l.prod := begin convert @prod_map_mul α α _ l (λ _, -1) id, { ext, rw neg_one_mul, refl }, { convert (prod_repeat _ _).symm, rw eq_repeat, use l.length_map _, intro, rw mem_map, rintro ⟨_, _, rfl⟩, refl }, { rw l.map_id }, end @[to_additive] lemma prod_map_hom (L : list ι) (f : ι → M) {G : Type*} [monoid_hom_class G M N] (g : G) : (L.map (g ∘ f)).prod = g ((L.map f).prod) := by rw [← prod_hom, map_map] @[to_additive] lemma prod_is_unit : Π {L : list M} (u : ∀ m ∈ L, is_unit m), is_unit L.prod | [] _ := by simp | (h :: t) u := begin simp only [list.prod_cons], exact is_unit.mul (u h (mem_cons_self h t)) (prod_is_unit (λ m mt, u m (mem_cons_of_mem h mt))) end @[simp, to_additive] lemma prod_take_mul_prod_drop : ∀ (L : list M) (i : ℕ), (L.take i).prod * (L.drop i).prod = L.prod | [] i := by simp [@zero_le' ℕ] | L 0 := by simp | (h :: t) (n+1) := by { dsimp, rw [prod_cons, prod_cons, mul_assoc, prod_take_mul_prod_drop] } @[simp, to_additive] lemma prod_take_succ : ∀ (L : list M) (i : ℕ) (p), (L.take (i + 1)).prod = (L.take i).prod * L.nth_le i p | [] i p := by cases p | (h :: t) 0 _ := by simp | (h :: t) (n+1) _ := by { dsimp, rw [prod_cons, prod_cons, prod_take_succ, mul_assoc] } /-- A list with product not one must have positive length. -/ @[to_additive "A list with sum not zero must have positive length."] lemma length_pos_of_prod_ne_one (L : list M) (h : L.prod ≠ 1) : 0 < L.length := by { cases L, { contrapose h, simp }, { simp } } /-- A list with product greater than one must have positive length. -/ @[to_additive length_pos_of_sum_pos "A list with positive sum must have positive length."] lemma length_pos_of_one_lt_prod [preorder M] (L : list M) (h : 1 < L.prod) : 0 < L.length := length_pos_of_prod_ne_one L h.ne' /-- A list with product less than one must have positive length. -/ @[to_additive "A list with negative sum must have positive length."] lemma length_pos_of_prod_lt_one [preorder M] (L : list M) (h : L.prod < 1) : 0 < L.length := length_pos_of_prod_ne_one L h.ne @[to_additive] lemma prod_update_nth : ∀ (L : list M) (n : ℕ) (a : M), (L.update_nth n a).prod = (L.take n).prod * (if n < L.length then a else 1) * (L.drop (n + 1)).prod | (x :: xs) 0 a := by simp [update_nth] | (x :: xs) (i+1) a := by simp [update_nth, prod_update_nth xs i a, mul_assoc] | [] _ _ := by simp [update_nth, (nat.zero_le _).not_lt, @zero_le' ℕ] open mul_opposite /-- We'd like to state this as `L.head * L.tail.prod = L.prod`, but because `L.head` relies on an inhabited instance to return a garbage value on the empty list, this is not possible. Instead, we write the statement in terms of `(L.nth 0).get_or_else 1`. -/ @[to_additive "We'd like to state this as `L.head + L.tail.sum = L.sum`, but because `L.head` relies on an inhabited instance to return a garbage value on the empty list, this is not possible. Instead, we write the statement in terms of `(L.nth 0).get_or_else 0`."] lemma nth_zero_mul_tail_prod (l : list M) : (l.nth 0).get_or_else 1 * l.tail.prod = l.prod := by cases l; simp /-- Same as `nth_zero_mul_tail_prod`, but avoiding the `list.head` garbage complication by requiring the list to be nonempty. -/ @[to_additive "Same as `nth_zero_add_tail_sum`, but avoiding the `list.head` garbage complication by requiring the list to be nonempty."] lemma head_mul_tail_prod_of_ne_nil [inhabited M] (l : list M) (h : l ≠ []) : l.head * l.tail.prod = l.prod := by cases l; [contradiction, simp] @[to_additive] lemma _root_.commute.list_prod_right (l : list M) (y : M) (h : ∀ (x ∈ l), commute y x) : commute y l.prod := begin induction l with z l IH, { simp }, { rw list.ball_cons at h, rw list.prod_cons, exact commute.mul_right h.1 (IH h.2), } end @[to_additive] lemma _root_.commute.list_prod_left (l : list M) (y : M) (h : ∀ (x ∈ l), commute x y) : commute l.prod y := (commute.list_prod_right _ _ $ λ x hx, (h _ hx).symm).symm lemma _root_.commute.list_sum_right [non_unital_non_assoc_semiring R] (a : R) (l : list R) (h : ∀ b ∈ l, commute a b) : commute a l.sum := begin induction l with x xs ih, { exact commute.zero_right _, }, { rw sum_cons, exact (h _ $ mem_cons_self _ _).add_right (ih $ λ j hj, h _ $ mem_cons_of_mem _ hj) } end lemma _root_.commute.list_sum_left [non_unital_non_assoc_semiring R] (b : R) (l : list R) (h : ∀ a ∈ l, commute a b) : commute l.sum b := (commute.list_sum_right _ _ $ λ x hx, (h _ hx).symm).symm @[to_additive sum_le_sum] lemma forall₂.prod_le_prod' [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] {l₁ l₂ : list M} (h : forall₂ (≤) l₁ l₂) : l₁.prod ≤ l₂.prod := begin induction h with a b la lb hab ih ih', { refl }, { simpa only [prod_cons] using mul_le_mul' hab ih' } end /-- If `l₁` is a sublist of `l₂` and all elements of `l₂` are greater than or equal to one, then `l₁.prod ≤ l₂.prod`. One can prove a stronger version assuming `∀ a ∈ l₂.diff l₁, 1 ≤ a` instead of `∀ a ∈ l₂, 1 ≤ a` but this lemma is not yet in `mathlib`. -/ @[to_additive sum_le_sum "If `l₁` is a sublist of `l₂` and all elements of `l₂` are nonnegative, then `l₁.sum ≤ l₂.sum`. One can prove a stronger version assuming `∀ a ∈ l₂.diff l₁, 0 ≤ a` instead of `∀ a ∈ l₂, 0 ≤ a` but this lemma is not yet in `mathlib`."] lemma sublist.prod_le_prod' [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] {l₁ l₂ : list M} (h : l₁ <+ l₂) (h₁ : ∀ a ∈ l₂, (1 : M) ≤ a) : l₁.prod ≤ l₂.prod := begin induction h, { refl }, case cons : l₁ l₂ a ih ih' { simp only [prod_cons, forall_mem_cons] at h₁ ⊢, exact (ih' h₁.2).trans (le_mul_of_one_le_left' h₁.1) }, case cons2 : l₁ l₂ a ih ih' { simp only [prod_cons, forall_mem_cons] at h₁ ⊢, exact mul_le_mul_left' (ih' h₁.2) _ } end @[to_additive sum_le_sum] lemma sublist_forall₂.prod_le_prod' [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] {l₁ l₂ : list M} (h : sublist_forall₂ (≤) l₁ l₂) (h₁ : ∀ a ∈ l₂, (1 : M) ≤ a) : l₁.prod ≤ l₂.prod := let ⟨l, hall, hsub⟩ := sublist_forall₂_iff.1 h in hall.prod_le_prod'.trans $ hsub.prod_le_prod' h₁ @[to_additive sum_le_sum] lemma prod_le_prod' [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] {l : list ι} {f g : ι → M} (h : ∀ i ∈ l, f i ≤ g i) : (l.map f).prod ≤ (l.map g).prod := forall₂.prod_le_prod' $ by simpa @[to_additive sum_lt_sum] lemma prod_lt_prod' [preorder M] [covariant_class M M (*) (<)] [covariant_class M M (*) (≤)] [covariant_class M M (function.swap (*)) (<)] [covariant_class M M (function.swap (*)) (≤)] {l : list ι} (f g : ι → M) (h₁ : ∀ i ∈ l, f i ≤ g i) (h₂ : ∃ i ∈ l, f i < g i) : (l.map f).prod < (l.map g).prod := begin induction l with i l ihl, { rcases h₂ with ⟨_, ⟨⟩, _⟩ }, simp only [ball_cons, bex_cons, map_cons, prod_cons] at h₁ h₂ ⊢, cases h₂, exacts [mul_lt_mul_of_lt_of_le h₂ (prod_le_prod' h₁.2), mul_lt_mul_of_le_of_lt h₁.1 $ ihl h₁.2 h₂] end @[to_additive] lemma prod_lt_prod_of_ne_nil [preorder M] [covariant_class M M (*) (<)] [covariant_class M M (*) (≤)] [covariant_class M M (function.swap (*)) (<)] [covariant_class M M (function.swap (*)) (≤)] {l : list ι} (hl : l ≠ []) (f g : ι → M) (hlt : ∀ i ∈ l, f i < g i) : (l.map f).prod < (l.map g).prod := prod_lt_prod' f g (λ i hi, (hlt i hi).le) $ (exists_mem_of_ne_nil l hl).imp $ λ i hi, ⟨hi, hlt i hi⟩ @[to_additive sum_le_card_nsmul] lemma prod_le_pow_card [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] (l : list M) (n : M) (h : ∀ (x ∈ l), x ≤ n) : l.prod ≤ n ^ l.length := by simpa only [map_id'', map_const, prod_repeat] using prod_le_prod' h @[to_additive card_nsmul_le_sum] lemma pow_card_le_prod [preorder M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] (l : list M) (n : M) (h : ∀ (x ∈ l), n ≤ x) : n ^ l.length ≤ l.prod := @prod_le_pow_card Mᵒᵈ _ _ _ _ l n h @[to_additive exists_lt_of_sum_lt] lemma exists_lt_of_prod_lt' [linear_order M] [covariant_class M M (function.swap (*)) (≤)] [covariant_class M M (*) (≤)] {l : list ι} (f g : ι → M) (h : (l.map f).prod < (l.map g).prod) : ∃ i ∈ l, f i < g i := by { contrapose! h, exact prod_le_prod' h } @[to_additive exists_le_of_sum_le] lemma exists_le_of_prod_le' [linear_order M] [covariant_class M M (*) (<)] [covariant_class M M (*) (≤)] [covariant_class M M (function.swap (*)) (<)] [covariant_class M M (function.swap (*)) (≤)] {l : list ι} (hl : l ≠ []) (f g : ι → M) (h : (l.map f).prod ≤ (l.map g).prod) : ∃ x ∈ l, f x ≤ g x := by { contrapose! h, exact prod_lt_prod_of_ne_nil hl _ _ h } @[to_additive sum_nonneg] lemma one_le_prod_of_one_le [preorder M] [covariant_class M M (*) (≤)] {l : list M} (hl₁ : ∀ x ∈ l, (1 : M) ≤ x) : 1 ≤ l.prod := begin -- We don't use `pow_card_le_prod` to avoid assumption -- [covariant_class M M (function.swap (*)) (≤)] induction l with hd tl ih, { refl }, rw prod_cons, exact one_le_mul (hl₁ hd (mem_cons_self hd tl)) (ih (λ x h, hl₁ x (mem_cons_of_mem hd h))) end end monoid section monoid_with_zero variables [monoid_with_zero M₀] /-- If zero is an element of a list `L`, then `list.prod L = 0`. If the domain is a nontrivial monoid with zero with no divisors, then this implication becomes an `iff`, see `list.prod_eq_zero_iff`. -/ lemma prod_eq_zero {L : list M₀} (h : (0 : M₀) ∈ L) : L.prod = 0 := begin induction L with a L ihL, { exact absurd h (not_mem_nil _) }, { rw prod_cons, cases (mem_cons_iff _ _ _).1 h with ha hL, exacts [mul_eq_zero_of_left ha.symm _, mul_eq_zero_of_right _ (ihL hL)] } end /-- Product of elements of a list `L` equals zero if and only if `0 ∈ L`. See also `list.prod_eq_zero` for an implication that needs weaker typeclass assumptions. -/ @[simp] lemma prod_eq_zero_iff [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} : L.prod = 0 ↔ (0 : M₀) ∈ L := begin induction L with a L ihL, { simp }, { rw [prod_cons, mul_eq_zero, ihL, mem_cons_iff, eq_comm] } end lemma prod_ne_zero [nontrivial M₀] [no_zero_divisors M₀] {L : list M₀} (hL : (0 : M₀) ∉ L) : L.prod ≠ 0 := mt prod_eq_zero_iff.1 hL end monoid_with_zero section group variables [group G] /-- This is the `list.prod` version of `mul_inv_rev` -/ @[to_additive "This is the `list.sum` version of `add_neg_rev`"] lemma prod_inv_reverse : ∀ (L : list G), L.prod⁻¹ = (L.map (λ x, x⁻¹)).reverse.prod | [] := by simp | (x :: xs) := by simp [prod_inv_reverse xs] /-- A non-commutative variant of `list.prod_reverse` -/ @[to_additive "A non-commutative variant of `list.sum_reverse`"] lemma prod_reverse_noncomm : ∀ (L : list G), L.reverse.prod = (L.map (λ x, x⁻¹)).prod⁻¹ := by simp [prod_inv_reverse] /-- Counterpart to `list.prod_take_succ` when we have an inverse operation -/ @[simp, to_additive /-"Counterpart to `list.sum_take_succ` when we have an negation operation"-/] lemma prod_drop_succ : ∀ (L : list G) (i : ℕ) (p), (L.drop (i + 1)).prod = (L.nth_le i p)⁻¹ * (L.drop i).prod | [] i p := false.elim (nat.not_lt_zero _ p) | (x :: xs) 0 p := by simp | (x :: xs) (i + 1) p := prod_drop_succ xs i _ end group section comm_group variables [comm_group G] /-- This is the `list.prod` version of `mul_inv` -/ @[to_additive "This is the `list.sum` version of `add_neg`"] lemma prod_inv : ∀ (L : list G), L.prod⁻¹ = (L.map (λ x, x⁻¹)).prod | [] := by simp | (x :: xs) := by simp [mul_comm, prod_inv xs] /-- Alternative version of `list.prod_update_nth` when the list is over a group -/ @[to_additive /-"Alternative version of `list.sum_update_nth` when the list is over a group"-/] lemma prod_update_nth' (L : list G) (n : ℕ) (a : G) : (L.update_nth n a).prod = L.prod * (if hn : n < L.length then (L.nth_le n hn)⁻¹ * a else 1) := begin refine (prod_update_nth L n a).trans _, split_ifs with hn hn, { rw [mul_comm _ a, mul_assoc a, prod_drop_succ L n hn, mul_comm _ (drop n L).prod, ← mul_assoc (take n L).prod, prod_take_mul_prod_drop, mul_comm a, mul_assoc] }, { simp only [take_all_of_le (le_of_not_lt hn), prod_nil, mul_one, drop_eq_nil_of_le ((le_of_not_lt hn).trans n.le_succ)] } end end comm_group @[to_additive] lemma eq_of_prod_take_eq [left_cancel_monoid M] {L L' : list M} (h : L.length = L'.length) (h' : ∀ i ≤ L.length, (L.take i).prod = (L'.take i).prod) : L = L' := begin apply ext_le h (λ i h₁ h₂, _), have : (L.take (i + 1)).prod = (L'.take (i + 1)).prod := h' _ (nat.succ_le_of_lt h₁), rw [prod_take_succ L i h₁, prod_take_succ L' i h₂, h' i (le_of_lt h₁)] at this, convert mul_left_cancel this end @[to_additive] lemma monotone_prod_take [canonically_ordered_monoid M] (L : list M) : monotone (λ i, (L.take i).prod) := begin apply monotone_nat_of_le_succ (λ n, _), cases lt_or_le n L.length with h h, { rw prod_take_succ _ _ h, exact le_self_mul }, { simp [take_all_of_le h, take_all_of_le (le_trans h (nat.le_succ _))] } end @[to_additive sum_pos] lemma one_lt_prod_of_one_lt [ordered_comm_monoid M] : ∀ (l : list M) (hl : ∀ x ∈ l, (1 : M) < x) (hl₂ : l ≠ []), 1 < l.prod | [] _ h := (h rfl).elim | [b] h _ := by simpa using h | (a :: b :: l) hl₁ hl₂ := begin simp only [forall_eq_or_imp, list.mem_cons_iff _ a] at hl₁, rw list.prod_cons, apply one_lt_mul_of_lt_of_le' hl₁.1, apply le_of_lt ((b :: l).one_lt_prod_of_one_lt hl₁.2 (l.cons_ne_nil b)), end @[to_additive] lemma single_le_prod [ordered_comm_monoid M] {l : list M} (hl₁ : ∀ x ∈ l, (1 : M) ≤ x) : ∀ x ∈ l, x ≤ l.prod := begin induction l, { simp }, simp_rw [prod_cons, forall_mem_cons] at ⊢ hl₁, split, { exact le_mul_of_one_le_right' (one_le_prod_of_one_le hl₁.2) }, { exact λ x H, le_mul_of_one_le_of_le hl₁.1 (l_ih hl₁.right x H) }, end @[to_additive all_zero_of_le_zero_le_of_sum_eq_zero] lemma all_one_of_le_one_le_of_prod_eq_one [ordered_comm_monoid M] {l : list M} (hl₁ : ∀ x ∈ l, (1 : M) ≤ x) (hl₂ : l.prod = 1) {x : M} (hx : x ∈ l) : x = 1 := le_antisymm (hl₂ ▸ single_le_prod hl₁ _ hx) (hl₁ x hx) @[to_additive] lemma prod_eq_one_iff [canonically_ordered_monoid M] (l : list M) : l.prod = 1 ↔ ∀ x ∈ l, x = (1 : M) := ⟨all_one_of_le_one_le_of_prod_eq_one (λ _ _, one_le _), λ h, by rw [eq_repeat.2 ⟨rfl, h⟩, prod_repeat, one_pow]⟩ /-- Slightly more general version of `list.prod_eq_one_iff` for a non-ordered `monoid` -/ @[to_additive "Slightly more general version of `list.sum_eq_zero_iff` for a non-ordered `add_monoid`"] lemma prod_eq_one [monoid M] {l : list M} (hl : ∀ (x ∈ l), x = (1 : M)) : l.prod = 1 := trans (prod_eq_pow_card l 1 hl) (one_pow l.length) /-- If all elements in a list are bounded below by `1`, then the length of the list is bounded by the sum of the elements. -/ lemma length_le_sum_of_one_le (L : list ℕ) (h : ∀ i ∈ L, 1 ≤ i) : L.length ≤ L.sum := begin induction L with j L IH h, { simp }, rw [sum_cons, length, add_comm], exact add_le_add (h _ (set.mem_insert _ _)) (IH (λ i hi, h i (set.mem_union_right _ hi))) end -- TODO: develop theory of tropical rings lemma sum_le_foldr_max [add_monoid M] [add_monoid N] [linear_order N] (f : M → N) (h0 : f 0 ≤ 0) (hadd : ∀ x y, f (x + y) ≤ max (f x) (f y)) (l : list M) : f l.sum ≤ (l.map f).foldr max 0 := begin induction l with hd tl IH, { simpa using h0 }, simp only [list.sum_cons, list.foldr_map, list.foldr] at IH ⊢, exact (hadd _ _).trans (max_le_max le_rfl IH) end @[simp, to_additive] lemma prod_erase [decidable_eq M] [comm_monoid M] {a} : ∀ {l : list M}, a ∈ l → a * (l.erase a).prod = l.prod | (b :: l) h := begin obtain rfl | ⟨ne, h⟩ := decidable.list.eq_or_ne_mem_of_mem h, { simp only [list.erase, if_pos, prod_cons] }, { simp only [list.erase, if_neg (mt eq.symm ne), prod_cons, prod_erase h, mul_left_comm a b] } end @[simp, to_additive] lemma prod_map_erase [decidable_eq ι] [comm_monoid M] (f : ι → M) {a} : ∀ {l : list ι}, a ∈ l → f a * ((l.erase a).map f).prod = (l.map f).prod | (b :: l) h := begin obtain rfl | ⟨ne, h⟩ := decidable.list.eq_or_ne_mem_of_mem h, { simp only [map, erase_cons_head, prod_cons] }, { simp only [map, erase_cons_tail _ ne.symm, prod_cons, prod_map_erase h, mul_left_comm (f a) (f b)], } end lemma dvd_prod [comm_monoid M] {a} {l : list M} (ha : a ∈ l) : a ∣ l.prod := let ⟨s, t, h⟩ := mem_split ha in by { rw [h, prod_append, prod_cons, mul_left_comm], exact dvd_mul_right _ _ } @[simp] lemma sum_const_nat (m n : ℕ) : sum (list.repeat m n) = m * n := by induction n; [refl, simp only [*, repeat_succ, sum_cons, nat.mul_succ, add_comm]] lemma dvd_sum [semiring R] {a} {l : list R} (h : ∀ x ∈ l, a ∣ x) : a ∣ l.sum := begin induction l with x l ih, { exact dvd_zero _ }, { rw [list.sum_cons], exact dvd_add (h _ (mem_cons_self _ _)) (ih (λ x hx, h x (mem_cons_of_mem _ hx))) } end /-- The product of a list of positive natural numbers is positive, and likewise for any nontrivial ordered semiring. -/ lemma prod_pos [ordered_semiring R] [nontrivial R] (l : list R) (h : ∀ a ∈ l, (0 : R) < a) : 0 < l.prod := begin induction l with a l ih, { simp }, { rw prod_cons, exact mul_pos (h _ $ mem_cons_self _ _) (ih $ λ a ha, h a $ mem_cons_of_mem _ ha) } end /-! Several lemmas about sum/head/tail for `list ℕ`. These are hard to generalize well, as they rely on the fact that `default ℕ = 0`. If desired, we could add a class stating that `default = 0`. -/ /-- This relies on `default ℕ = 0`. -/ lemma head_add_tail_sum (L : list ℕ) : L.head + L.tail.sum = L.sum := by { cases L, { simp, refl }, { simp } } /-- This relies on `default ℕ = 0`. -/ lemma head_le_sum (L : list ℕ) : L.head ≤ L.sum := nat.le.intro (head_add_tail_sum L) /-- This relies on `default ℕ = 0`. -/ lemma tail_sum (L : list ℕ) : L.tail.sum = L.sum - L.head := by rw [← head_add_tail_sum L, add_comm, add_tsub_cancel_right] section alternating section variables [has_one α] [has_mul α] [has_inv α] @[simp, to_additive] lemma alternating_prod_nil : alternating_prod ([] : list α) = 1 := rfl @[simp, to_additive] lemma alternating_prod_singleton (a : α) : alternating_prod [a] = a := rfl @[to_additive] lemma alternating_prod_cons_cons' (a b : α) (l : list α) : alternating_prod (a :: b :: l) = a * b⁻¹ * alternating_prod l := rfl end @[to_additive] lemma alternating_prod_cons_cons [div_inv_monoid α] (a b : α) (l : list α) : alternating_prod (a :: b :: l) = a / b * alternating_prod l := by rw [div_eq_mul_inv, alternating_prod_cons_cons'] variables [comm_group α] @[to_additive] lemma alternating_prod_cons' : ∀ (a : α) (l : list α), alternating_prod (a :: l) = a * (alternating_prod l)⁻¹ | a [] := by rw [alternating_prod_nil, inv_one, mul_one, alternating_prod_singleton] | a (b :: l) := by rw [alternating_prod_cons_cons', alternating_prod_cons' b l, mul_inv, inv_inv, mul_assoc] @[simp, to_additive] lemma alternating_prod_cons (a : α) (l : list α) : alternating_prod (a :: l) = a / alternating_prod l := by rw [div_eq_mul_inv, alternating_prod_cons'] @[to_additive] lemma alternating_prod_append : ∀ l₁ l₂ : list α, alternating_prod (l₁ ++ l₂) = alternating_prod l₁ * alternating_prod l₂ ^ (-1 : ℤ) ^ length l₁ | [] l₂ := by simp | (a :: l₁) l₂ := by simp_rw [cons_append, alternating_prod_cons, alternating_prod_append, length_cons, pow_succ, neg_mul, one_mul, zpow_neg, ←div_eq_mul_inv, div_div] @[to_additive] lemma alternating_prod_reverse : ∀ l : list α, alternating_prod (reverse l) = alternating_prod l ^ (-1 : ℤ) ^ (length l + 1) | [] := by simp only [alternating_prod_nil, one_zpow, reverse_nil] | (a :: l) := begin simp_rw [reverse_cons, alternating_prod_append, alternating_prod_reverse, alternating_prod_singleton, alternating_prod_cons, length_reverse, length, pow_succ, neg_mul, one_mul, zpow_neg, inv_inv], rw [mul_comm, ←div_eq_mul_inv, div_zpow], end end alternating lemma sum_map_mul_left [non_unital_non_assoc_semiring R] (L : list ι) (f : ι → R) (r : R) : (L.map (λ b, r * f b)).sum = r * (L.map f).sum := sum_map_hom L f $ add_monoid_hom.mul_left r lemma sum_map_mul_right [non_unital_non_assoc_semiring R] (L : list ι) (f : ι → R) (r : R) : (L.map (λ b, f b * r)).sum = (L.map f).sum * r := sum_map_hom L f $ add_monoid_hom.mul_right r end list namespace mul_opposite open list variables [monoid M] lemma op_list_prod : ∀ (l : list M), op (l.prod) = (l.map op).reverse.prod | [] := rfl | (x :: xs) := by rw [list.prod_cons, list.map_cons, list.reverse_cons', list.prod_concat, op_mul, op_list_prod] lemma _root_.mul_opposite.unop_list_prod (l : list Mᵐᵒᵖ) : (l.prod).unop = (l.map unop).reverse.prod := by rw [← op_inj, op_unop, mul_opposite.op_list_prod, map_reverse, map_map, reverse_reverse, op_comp_unop, map_id] end mul_opposite section monoid_hom variables [monoid M] [monoid N] @[to_additive] lemma map_list_prod {F : Type*} [monoid_hom_class F M N] (f : F) (l : list M) : f l.prod = (l.map f).prod := (l.prod_hom f).symm /-- A morphism into the opposite monoid acts on the product by acting on the reversed elements. -/ lemma unop_map_list_prod {F : Type*} [monoid_hom_class F M Nᵐᵒᵖ] (f : F) (l : list M) : (f l.prod).unop = (l.map (mul_opposite.unop ∘ f)).reverse.prod := by rw [map_list_prod f l, mul_opposite.unop_list_prod, list.map_map] namespace monoid_hom /-- Deprecated, use `_root_.map_list_prod` instead. -/ @[to_additive "Deprecated, use `_root_.map_list_sum` instead."] protected lemma map_list_prod (f : M →* N) (l : list M) : f l.prod = (l.map f).prod := map_list_prod f l /-- A morphism into the opposite monoid acts on the product by acting on the reversed elements. Deprecated, use `_root_.unop_map_list_prod` instead. -/ protected lemma unop_map_list_prod (f : M →* Nᵐᵒᵖ) (l : list M) : (f l.prod).unop = (l.map (mul_opposite.unop ∘ f)).reverse.prod := unop_map_list_prod f l end monoid_hom end monoid_hom
e238429d4f4ca73aada11b3a67e1cd0b469201e3
ff5230333a701471f46c57e8c115a073ebaaa448
/leanpkg/leanpkg/lean_version.lean
8f91c205d98ddb58c82d71ecc4999fce8145b5e2
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
694
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ namespace leanpkg def lean_version_string_core := let (major, minor, patch) := lean.version in sformat!("{major}.{minor}.{patch}") def lean_version_string := if lean.is_release then lean_version_string_core else if lean.special_version_desc ≠ "" then lean.special_version_desc else "master" def ui_lean_version_string := if lean.is_release then lean_version_string_core else if lean.special_version_desc ≠ "" then lean.special_version_desc else "master (" ++ lean_version_string_core ++ ")" end leanpkg
72f3d50dd785f805e44cb0a9e9b0ba36b2f9e651
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/complex/module.lean
6c3777c3b97a42fd904e2a59f875aa8a43cc07c6
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
11,142
lean
/- Copyright (c) 2020 Alexander Bentkamp, Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Sébastien Gouëzel, Eric Wieser -/ import algebra.order.smul import data.complex.basic import data.fin.vec_notation import field_theory.tower /-! # Complex number as a vector space over `ℝ` This file contains the following instances: * Any `•`-structure (`has_scalar`, `mul_action`, `distrib_mul_action`, `module`, `algebra`) on `ℝ` imbues a corresponding structure on `ℂ`. This includes the statement that `ℂ` is an `ℝ` algebra. * any complex vector space is a real vector space; * any finite dimensional complex vector space is a finite dimensional real vector space; * the space of `ℝ`-linear maps from a real vector space to a complex vector space is a complex vector space. It also defines bundled versions of four standard maps (respectively, the real part, the imaginary part, the embedding of `ℝ` in `ℂ`, and the complex conjugate): * `complex.re_lm` (`ℝ`-linear map); * `complex.im_lm` (`ℝ`-linear map); * `complex.of_real_am` (`ℝ`-algebra (homo)morphism); * `complex.conj_ae` (`ℝ`-algebra equivalence). It also provides a universal property of the complex numbers `complex.lift`, which constructs a `ℂ →ₐ[ℝ] A` into any `ℝ`-algebra `A` given a square root of `-1`. -/ namespace complex open_locale complex_conjugate variables {R : Type*} {S : Type*} section variables [has_scalar R ℝ] /- The useless `0` multiplication in `smul` is to make sure that `restrict_scalars.module ℝ ℂ ℂ = complex.module` definitionally. -/ instance : has_scalar R ℂ := { smul := λ r x, ⟨r • x.re - 0 * x.im, r • x.im + 0 * x.re⟩ } lemma smul_re (r : R) (z : ℂ) : (r • z).re = r • z.re := by simp [(•)] lemma smul_im (r : R) (z : ℂ) : (r • z).im = r • z.im := by simp [(•)] @[simp] lemma real_smul {x : ℝ} {z : ℂ} : x • z = x * z := rfl end instance [has_scalar R ℝ] [has_scalar S ℝ] [smul_comm_class R S ℝ] : smul_comm_class R S ℂ := { smul_comm := λ r s x, by ext; simp [smul_re, smul_im, smul_comm] } instance [has_scalar R S] [has_scalar R ℝ] [has_scalar S ℝ] [is_scalar_tower R S ℝ] : is_scalar_tower R S ℂ := { smul_assoc := λ r s x, by ext; simp [smul_re, smul_im, smul_assoc] } instance [has_scalar R ℝ] [has_scalar Rᵐᵒᵖ ℝ] [is_central_scalar R ℝ] : is_central_scalar R ℂ := { op_smul_eq_smul := λ r x, by ext; simp [smul_re, smul_im, op_smul_eq_smul] } instance [monoid R] [mul_action R ℝ] : mul_action R ℂ := { one_smul := λ x, by ext; simp [smul_re, smul_im, one_smul], mul_smul := λ r s x, by ext; simp [smul_re, smul_im, mul_smul] } instance [semiring R] [distrib_mul_action R ℝ] : distrib_mul_action R ℂ := { smul_add := λ r x y, by ext; simp [smul_re, smul_im, smul_add], smul_zero := λ r, by ext; simp [smul_re, smul_im, smul_zero] } instance [semiring R] [module R ℝ] : module R ℂ := { add_smul := λ r s x, by ext; simp [smul_re, smul_im, add_smul], zero_smul := λ r, by ext; simp [smul_re, smul_im, zero_smul] } instance [comm_semiring R] [algebra R ℝ] : algebra R ℂ := { smul := (•), smul_def' := λ r x, by ext; simp [smul_re, smul_im, algebra.smul_def], commutes' := λ r ⟨xr, xi⟩, by ext; simp [smul_re, smul_im, algebra.commutes], ..complex.of_real.comp (algebra_map R ℝ) } @[simp] lemma coe_algebra_map : (algebra_map ℝ ℂ : ℝ → ℂ) = coe := rfl section variables {A : Type*} [semiring A] [algebra ℝ A] /-- We need this lemma since `complex.coe_algebra_map` diverts the simp-normal form away from `alg_hom.commutes`. -/ @[simp] lemma _root_.alg_hom.map_coe_real_complex (f : ℂ →ₐ[ℝ] A) (x : ℝ) : f x = algebra_map ℝ A x := f.commutes x /-- Two `ℝ`-algebra homomorphisms from ℂ are equal if they agree on `complex.I`. -/ @[ext] lemma alg_hom_ext ⦃f g : ℂ →ₐ[ℝ] A⦄ (h : f I = g I) : f = g := begin ext ⟨x, y⟩, simp only [mk_eq_add_mul_I, alg_hom.map_add, alg_hom.map_coe_real_complex, alg_hom.map_mul, h] end end section open_locale complex_order protected lemma ordered_smul : ordered_smul ℝ ℂ := ordered_smul.mk' $ λ a b r hab hr, ⟨by simp [hr, hab.1.le], by simp [hab.2]⟩ localized "attribute [instance] complex.ordered_smul" in complex_order end open submodule finite_dimensional /-- `ℂ` has a basis over `ℝ` given by `1` and `I`. -/ noncomputable def basis_one_I : basis (fin 2) ℝ ℂ := basis.of_equiv_fun { to_fun := λ z, ![z.re, z.im], inv_fun := λ c, c 0 + c 1 • I, left_inv := λ z, by simp, right_inv := λ c, by { ext i, fin_cases i; simp }, map_add' := λ z z', by simp, -- why does `simp` not know how to apply `smul_cons`, which is a `@[simp]` lemma, here? map_smul' := λ c z, by simp [matrix.smul_cons c z.re, matrix.smul_cons c z.im] } @[simp] lemma coe_basis_one_I_repr (z : ℂ) : ⇑(basis_one_I.repr z) = ![z.re, z.im] := rfl @[simp] lemma coe_basis_one_I : ⇑basis_one_I = ![1, I] := funext $ λ i, basis.apply_eq_iff.mpr $ finsupp.ext $ λ j, by fin_cases i; fin_cases j; simp only [coe_basis_one_I_repr, finsupp.single_eq_same, finsupp.single_eq_of_ne, matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons, nat.one_ne_zero, fin.one_eq_zero_iff, fin.zero_eq_one_iff, ne.def, not_false_iff, one_re, one_im, I_re, I_im] instance : finite_dimensional ℝ ℂ := of_fintype_basis basis_one_I @[simp] lemma finrank_real_complex : finite_dimensional.finrank ℝ ℂ = 2 := by rw [finrank_eq_card_basis basis_one_I, fintype.card_fin] @[simp] lemma dim_real_complex : module.rank ℝ ℂ = 2 := by simp [← finrank_eq_dim, finrank_real_complex] lemma {u} dim_real_complex' : cardinal.lift.{u} (module.rank ℝ ℂ) = 2 := by simp [← finrank_eq_dim, finrank_real_complex, bit0] /-- `fact` version of the dimension of `ℂ` over `ℝ`, locally useful in the definition of the circle. -/ lemma finrank_real_complex_fact : fact (finrank ℝ ℂ = 2) := ⟨finrank_real_complex⟩ end complex /- Register as an instance (with low priority) the fact that a complex vector space is also a real vector space. -/ @[priority 900] instance module.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] : module ℝ E := restrict_scalars.module ℝ ℂ E instance module.real_complex_tower (E : Type*) [add_comm_group E] [module ℂ E] : is_scalar_tower ℝ ℂ E := restrict_scalars.is_scalar_tower ℝ ℂ E @[simp, norm_cast] lemma complex.coe_smul {E : Type*} [add_comm_group E] [module ℂ E] (x : ℝ) (y : E) : (x : ℂ) • y = x • y := rfl @[priority 100] instance finite_dimensional.complex_to_real (E : Type*) [add_comm_group E] [module ℂ E] [finite_dimensional ℂ E] : finite_dimensional ℝ E := finite_dimensional.trans ℝ ℂ E lemma dim_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : module.rank ℝ E = 2 * module.rank ℂ E := cardinal.lift_inj.1 $ by { rw [← dim_mul_dim' ℝ ℂ E, complex.dim_real_complex], simp [bit0] } lemma finrank_real_of_complex (E : Type*) [add_comm_group E] [module ℂ E] : finite_dimensional.finrank ℝ E = 2 * finite_dimensional.finrank ℂ E := by rw [← finite_dimensional.finrank_mul_finrank ℝ ℂ E, complex.finrank_real_complex] namespace complex open_locale complex_conjugate /-- Linear map version of the real part function, from `ℂ` to `ℝ`. -/ def re_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.re, map_add' := add_re, map_smul' := by simp, } @[simp] lemma re_lm_coe : ⇑re_lm = re := rfl /-- Linear map version of the imaginary part function, from `ℂ` to `ℝ`. -/ def im_lm : ℂ →ₗ[ℝ] ℝ := { to_fun := λx, x.im, map_add' := add_im, map_smul' := by simp, } @[simp] lemma im_lm_coe : ⇑im_lm = im := rfl /-- `ℝ`-algebra morphism version of the canonical embedding of `ℝ` in `ℂ`. -/ def of_real_am : ℝ →ₐ[ℝ] ℂ := algebra.of_id ℝ ℂ @[simp] lemma of_real_am_coe : ⇑of_real_am = coe := rfl /-- `ℝ`-algebra isomorphism version of the complex conjugation function from `ℂ` to `ℂ` -/ def conj_ae : ℂ ≃ₐ[ℝ] ℂ := { inv_fun := conj, left_inv := star_star, right_inv := star_star, commutes' := conj_of_real, .. conj } @[simp] lemma conj_ae_coe : ⇑conj_ae = conj := rfl /-- The matrix representation of `conj_ae`. -/ @[simp] lemma to_matrix_conj_ae : linear_map.to_matrix basis_one_I basis_one_I conj_ae.to_linear_map = ![![1, 0], ![0, -1]] := begin ext i j, simp [linear_map.to_matrix_apply], fin_cases i; fin_cases j; simp end section lift variables {A : Type*} [ring A] [algebra ℝ A] /-- There is an alg_hom from `ℂ` to any `ℝ`-algebra with an element that squares to `-1`. See `complex.lift` for this as an equiv. -/ def lift_aux (I' : A) (hf : I' * I' = -1) : ℂ →ₐ[ℝ] A := alg_hom.of_linear_map ((algebra.of_id ℝ A).to_linear_map.comp re_lm + (linear_map.to_span_singleton _ _ I').comp im_lm) (show algebra_map ℝ A 1 + (0 : ℝ) • I' = 1, by rw [ring_hom.map_one, zero_smul, add_zero]) (λ ⟨x₁, y₁⟩ ⟨x₂, y₂⟩, show algebra_map ℝ A (x₁ * x₂ - y₁ * y₂) + (x₁ * y₂ + y₁ * x₂) • I' = (algebra_map ℝ A x₁ + y₁ • I') * (algebra_map ℝ A x₂ + y₂ • I'), begin rw [add_mul, mul_add, mul_add, add_comm _ (y₁ • I' * y₂ • I'), add_add_add_comm], congr' 1, -- equate "real" and "imaginary" parts { rw [smul_mul_smul, hf, smul_neg, ←algebra.algebra_map_eq_smul_one, ←sub_eq_add_neg, ←ring_hom.map_mul, ←ring_hom.map_sub], }, { rw [algebra.smul_def, algebra.smul_def, algebra.smul_def, ←algebra.right_comm _ x₂, ←mul_assoc, ←add_mul, ←ring_hom.map_mul, ←ring_hom.map_mul, ←ring_hom.map_add] } end) @[simp] lemma lift_aux_apply (I' : A) (hI') (z : ℂ) : lift_aux I' hI' z = algebra_map ℝ A z.re + z.im • I' := rfl lemma lift_aux_apply_I (I' : A) (hI') : lift_aux I' hI' I = I' := by simp /-- A universal property of the complex numbers, providing a unique `ℂ →ₐ[ℝ] A` for every element of `A` which squares to `-1`. This can be used to embed the complex numbers in the `quaternion`s. This isomorphism is named to match the very similar `zsqrtd.lift`. -/ @[simps {simp_rhs := tt}] def lift : {I' : A // I' * I' = -1} ≃ (ℂ →ₐ[ℝ] A) := { to_fun := λ I', lift_aux I' I'.prop, inv_fun := λ F, ⟨F I, by rw [←F.map_mul, I_mul_I, alg_hom.map_neg, alg_hom.map_one]⟩, left_inv := λ I', subtype.ext $ lift_aux_apply_I I' I'.prop, right_inv := λ F, alg_hom_ext $ lift_aux_apply_I _ _, } /- When applied to `complex.I` itself, `lift` is the identity. -/ @[simp] lemma lift_aux_I : lift_aux I I_mul_I = alg_hom.id ℝ ℂ := alg_hom_ext $ lift_aux_apply_I _ _ /- When applied to `-complex.I`, `lift` is conjugation, `conj`. -/ @[simp] lemma lift_aux_neg_I : lift_aux (-I) ((neg_mul_neg _ _).trans I_mul_I) = conj_ae := alg_hom_ext $ (lift_aux_apply_I _ _).trans conj_I.symm end lift end complex
ca92a6a49f5b07c0946b21cb6fa5d3fe8d23d9a6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/control/functor.lean
b9decb492e97c8417ea21db35149c9511f474f27
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
8,832
lean
/- Copyright (c) 2017 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.lint import control.basic /-! # Functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/612 > Any changes to this file require a corresponding PR to mathlib4. This module provides additional lemmas, definitions, and instances for `functor`s. ## Main definitions * `const α` is the functor that sends all types to `α`. * `add_const α` is `const α` but for when `α` has an additive structure. * `comp F G` for functors `F` and `G` is the functor composition of `F` and `G`. * `liftp` and `liftr` respectively lift predicates and relations on a type `α` to `F α`. Terms of `F α` are considered to, in some sense, contain values of type `α`. ## Tags functor, applicative -/ attribute [functor_norm] seq_assoc pure_seq_eq_map map_pure seq_map_assoc map_seq universes u v w section functor variables {F : Type u → Type v} variables {α β γ : Type u} variables [functor F] [is_lawful_functor F] lemma functor.map_id : (<$>) id = (id : F α → F α) := by apply funext; apply id_map lemma functor.map_comp_map (f : α → β) (g : β → γ) : ((<$>) g ∘ (<$>) f : F α → F γ) = (<$>) (g ∘ f) := by apply funext; intro; rw comp_map theorem functor.ext {F} : ∀ {F1 : functor F} {F2 : functor F} [@is_lawful_functor F F1] [@is_lawful_functor F F2] (H : ∀ α β (f : α → β) (x : F α), @functor.map _ F1 _ _ f x = @functor.map _ F2 _ _ f x), F1 = F2 | ⟨m, mc⟩ ⟨m', mc'⟩ H1 H2 H := begin cases show @m = @m', by funext α β f x; apply H, congr, funext α β, have E1 := @map_const_eq _ ⟨@m, @mc⟩ H1, have E2 := @map_const_eq _ ⟨@m, @mc'⟩ H2, exact E1.trans E2.symm end end functor /-- Introduce the `id` functor. Incidentally, this is `pure` for `id` as a `monad` and as an `applicative` functor. -/ def id.mk {α : Sort u} : α → id α := id namespace functor /-- `const α` is the constant functor, mapping every type to `α`. When `α` has a monoid structure, `const α` has an `applicative` instance. (If `α` has an additive monoid structure, see `functor.add_const`.) -/ @[nolint unused_arguments] def const (α : Type*) (β : Type*) := α /-- `const.mk` is the canonical map `α → const α β` (the identity), and it can be used as a pattern to extract this value. -/ @[pattern] def const.mk {α β} (x : α) : const α β := x /-- `const.mk'` is `const.mk` but specialized to map `α` to `const α punit`, where `punit` is the terminal object in `Type*`. -/ def const.mk' {α} (x : α) : const α punit := x /-- Extract the element of `α` from the `const` functor. -/ def const.run {α β} (x : const α β) : α := x namespace const protected lemma ext {α β} {x y : const α β} (h : x.run = y.run) : x = y := h /-- The map operation of the `const γ` functor. -/ @[nolint unused_arguments] protected def map {γ α β} (f : α → β) (x : const γ β) : const γ α := x instance {γ} : functor (const γ) := { map := @const.map γ } instance {γ} : is_lawful_functor (const γ) := by constructor; intros; refl instance {α β} [inhabited α] : inhabited (const α β) := ⟨(default : α)⟩ end const /-- `add_const α` is a synonym for constant functor `const α`, mapping every type to `α`. When `α` has a additive monoid structure, `add_const α` has an `applicative` instance. (If `α` has a multiplicative monoid structure, see `functor.const`.) -/ def add_const (α : Type*) := const α /-- `add_const.mk` is the canonical map `α → add_const α β`, which is the identity, where `add_const α β = const α β`. It can be used as a pattern to extract this value. -/ @[pattern] def add_const.mk {α β} (x : α) : add_const α β := x /-- Extract the element of `α` from the constant functor. -/ def add_const.run {α β} : add_const α β → α := id instance add_const.functor {γ} : functor (add_const γ) := @const.functor γ instance add_const.is_lawful_functor {γ} : is_lawful_functor (add_const γ) := @const.is_lawful_functor γ instance {α β} [inhabited α] : inhabited (add_const α β) := ⟨(default : α)⟩ /-- `functor.comp` is a wrapper around `function.comp` for types. It prevents Lean's type class resolution mechanism from trying a `functor (comp F id)` when `functor F` would do. -/ def comp (F : Type u → Type w) (G : Type v → Type u) (α : Type v) : Type w := F $ G α /-- Construct a term of `comp F G α` from a term of `F (G α)`, which is the same type. Can be used as a pattern to extract a term of `F (G α)`. -/ @[pattern] def comp.mk {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : F (G α)) : comp F G α := x /-- Extract a term of `F (G α)` from a term of `comp F G α`, which is the same type. -/ def comp.run {F : Type u → Type w} {G : Type v → Type u} {α : Type v} (x : comp F G α) : F (G α) := x namespace comp variables {F : Type u → Type w} {G : Type v → Type u} protected lemma ext {α} {x y : comp F G α} : x.run = y.run → x = y := id instance {α} [inhabited (F (G α))] : inhabited (comp F G α) := ⟨(default : F (G α))⟩ variables [functor F] [functor G] /-- The map operation for the composition `comp F G` of functors `F` and `G`. -/ protected def map {α β : Type v} (h : α → β) : comp F G α → comp F G β | (comp.mk x) := comp.mk ((<$>) h <$> x) instance : functor (comp F G) := { map := @comp.map F G _ _ } @[functor_norm] lemma map_mk {α β} (h : α → β) (x : F (G α)) : h <$> comp.mk x = comp.mk ((<$>) h <$> x) := rfl @[simp] protected lemma run_map {α β} (h : α → β) (x : comp F G α) : (h <$> x).run = (<$>) h <$> x.run := rfl variables [is_lawful_functor F] [is_lawful_functor G] variables {α β γ : Type v} protected lemma id_map : ∀ (x : comp F G α), comp.map id x = x | (comp.mk x) := by simp [comp.map, functor.map_id] protected lemma comp_map (g' : α → β) (h : β → γ) : ∀ (x : comp F G α), comp.map (h ∘ g') x = comp.map h (comp.map g' x) | (comp.mk x) := by simp [comp.map, functor.map_comp_map g' h] with functor_norm instance : is_lawful_functor (comp F G) := { id_map := @comp.id_map F G _ _ _ _, comp_map := @comp.comp_map F G _ _ _ _ } theorem functor_comp_id {F} [AF : functor F] [is_lawful_functor F] : @comp.functor F id _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor F id _ _ _ _) _ (λ α β f x, rfl) theorem functor_id_comp {F} [AF : functor F] [is_lawful_functor F] : @comp.functor id F _ _ = AF := @functor.ext F _ AF (@comp.is_lawful_functor id F _ _ _ _) _ (λ α β f x, rfl) end comp namespace comp open function (hiding comp) open functor variables {F : Type u → Type w} {G : Type v → Type u} variables [applicative F] [applicative G] /-- The `<*>` operation for the composition of applicative functors. -/ protected def seq {α β : Type v} : comp F G (α → β) → comp F G α → comp F G β | (comp.mk f) (comp.mk x) := comp.mk $ (<*>) <$> f <*> x instance : has_pure (comp F G) := ⟨λ _ x, comp.mk $ pure $ pure x⟩ instance : has_seq (comp F G) := ⟨λ _ _ f x, comp.seq f x⟩ @[simp] protected lemma run_pure {α : Type v} : ∀ x : α, (pure x : comp F G α).run = pure (pure x) | _ := rfl @[simp] protected lemma run_seq {α β : Type v} (f : comp F G (α → β)) (x : comp F G α) : (f <*> x).run = (<*>) <$> f.run <*> x.run := rfl instance : applicative (comp F G) := { map := @comp.map F G _ _, seq := @comp.seq F G _ _, ..comp.has_pure } end comp variables {F : Type u → Type u} [functor F] /-- If we consider `x : F α` to, in some sense, contain values of type `α`, predicate `liftp p x` holds iff every value contained by `x` satisfies `p`. -/ def liftp {α : Type u} (p : α → Prop) (x : F α) : Prop := ∃ u : F (subtype p), subtype.val <$> u = x /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `liftr r x y` relates `x` and `y` iff (1) `x` and `y` have the same shape and (2) we can pair values `a` from `x` and `b` from `y` so that `r a b` holds. -/ def liftr {α : Type u} (r : α → α → Prop) (x y : F α) : Prop := ∃ u : F {p : α × α // r p.fst p.snd}, (λ t : {p : α × α // r p.fst p.snd}, t.val.fst) <$> u = x ∧ (λ t : {p : α × α // r p.fst p.snd}, t.val.snd) <$> u = y /-- If we consider `x : F α` to, in some sense, contain values of type `α`, then `supp x` is the set of values of type `α` that `x` contains. -/ def supp {α : Type u} (x : F α) : set α := { y : α | ∀ ⦃p⦄, liftp p x → p y } theorem of_mem_supp {α : Type u} {x : F α} {p : α → Prop} (h : liftp p x) : ∀ y ∈ supp x, p y := λ y hy, hy h end functor
e01562b55fe8534ba25c71b05e99f4207d38d259
8f67b34bba98f894155dedf263bc8d61c31e89cd
/2ltt/pullbacks.lean
206874536ca3b57352016034ee4202616cc8af9b
[]
no_license
5HT/two-level
3b1523db242cba819681b862fbc8f490d9571a66
370f5a91311db3b463b10a31891370721e2476e2
refs/heads/master
1,648,254,367,420
1,576,269,550,000
1,576,269,550,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,653
lean
import .fibrant .limit data.equiv algebra.category .facts open function section pullback universe variable u variables {A B C : Type.{u}} (f : A → C) (g : B → C) {isfib : is_fibration f} structure Pullback (f : A → C) (g : B → C):= (pA : A) (pB : B) (pC : C) (p_law : (f pA = pC) × (g pB = pC)) definition Pullback' : Type := Σ (b : B), fibreₛ f (g b) open sigma.ops -- ref:lem:fib-closure:pb -- Lemma 3.9 (i) definition Pullback'_is_fibrant : is_fibration (λ (pb : Pullback' f g), pb.1) := λ b, @equiv_is_fibrant _ _ (equiv.symm (fibre_projection b)) (isfib (g b)) -- Inspired by the implementation from HoTT Lean library inductive pb_cat_ob : Type := | obA : pb_cat_ob | obB : pb_cat_ob | obC : pb_cat_ob open pb_cat_ob inductive pb_cat_hom : pb_cat_ob → pb_cat_ob → Type := | f1 : pb_cat_hom obA obC | f2 : pb_cat_hom obB obC open sum definition no_comp_pullback_hom {a b c : pb_cat_ob} : pb_cat_hom a b → pb_cat_hom b c → false := begin intros f g, cases g: cases f end -- Pullback as a category with three objects obA obB and obC -- and arrows f1 : obA → obC and f2: obB → obC definition pullback_category : category pb_cat_ob := ⦃ category, hom := λ a b, pb_cat_hom a b + (a = b), comp := λ a b c f g, begin cases f with [f₁, f₂]: cases g with [g₁, g₂], { apply inl, exfalso, apply no_comp_pullback_hom g₁ f₁}, { apply inl, rewrite g₂, assumption}, { apply inl, rewrite -f₂, assumption}, { apply inr, rewrite -f₂, assumption} end, ID := λ a, inr rfl , assoc := λ a b c d h g f, begin induction h with rh ph: induction g with rg pg: induction f with rf pf: try cases pg: try cases pf: esimp: exfalso: apply no_comp_pullback_hom; assumption; assumption end, id_left := λ a b f, begin cases f with [fl, fr], esimp, cases fr, esimp end, id_right := λ a b f, begin cases f with [fl, fr], esimp, cases fr, esimp end ⦄ open category definition PullbackCat := Mk pullback_category definition pullback_diagram (f : A → C) (g : B → C) : PullbackCat ⇒ Type_category.{u} := ⦃ functor, object := λ c, match c with | obA := A | obB := B | obC := C end, morphism := λ a b h, begin cases h with [pb_hom, p], cases pb_hom, apply f, apply g, cases p, apply id end, respect_id := λ a, begin reflexivity end, respect_comp := begin intros a b c pf pg, cases pf with [pb_hom_f, id_f]: cases pg with [pb_hom_g, id_g]: try (cases pb_hom_f: cases pb_hom_g: esimp): try cases id_g: esimp: try cases id_f: esimp end ⦄ open poly_unit open equiv definition const_funct_unit [reducible] [unfold_full] := const_funct_obj PullbackCat Type_category poly_unit definition nat_unit_Pullback_equiv : const_funct_unit ⟹ pullback_diagram f g ≃ₛ Pullback f g:= begin esimp, refine (equiv.mk _ _ _ _), { intro N, cases N with [η, NatSq], unfold pullback_diagram at *, esimp at *, refine Pullback.mk _ _ _ _, apply (η obA star), apply (η obB star), apply (η obC star), esimp, refine (_,_), have H : f ∘ η obA = η obC ∘ id, from NatSq (inl pb_cat_hom.f1), apply happly H, have H : g ∘ η obB = η obC ∘ id, from NatSq (inl pb_cat_hom.f2), apply happly H }, { intro PB, cases PB, cases p_law with [f_eq, g_eq], refine natural_transformation.mk _ _, intros a, unfold pullback_diagram, esimp, intro uu, cases a: esimp: assumption, intros a b pb, unfold pullback_diagram, cases pb with [pb_hom, p_id], cases pb_hom: esimp, { apply funext, intros, apply f_eq}, { apply funext, intros, apply g_eq}, { cases p_id, esimp}}, { unfold function.left_inverse, intros x, cases x, esimp at *, congruence, apply funext, intros, apply funext, intro uu, esimp, cases x: esimp: cases uu: reflexivity }, { unfold function.right_inverse, unfold function.left_inverse, intros x, cases x, cases p_law with [f_eq, g_eq], esimp } end definition Pullback'_Pullback_equiv : Pullback' f g ≃ₛ Pullback f g:= equiv.mk (λ x, begin cases x with [p₁, p₂], cases p₂ with [pp₁, pp₂], apply Pullback.mk pp₁ p₁ (g p₁) (pp₂, rfl) end) (λ x, begin cases x, cases p_law with [p₁, p₂], refine ⟨ pB, #eq.ops ⟨pA, p₁ ⬝ p₂⁻¹⟩⟩end) (λ x, begin cases x with [p₁, p₂], cases p₂ with [pp₁, pp₂], esimp end) (λ x, begin cases x, cases p_law with [p₁, p₂], esimp, cases p₂, esimp end) end pullback
307253e9e2e0f5a212fd9c84829e11c7e243db02
63abd62053d479eae5abf4951554e1064a4c45b4
/src/group_theory/subgroup.lean
8962ac03507a661e9503fc3f3167d52c3dcdbd84
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
46,293
lean
/- Copyright (c) 2020 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import group_theory.submonoid import algebra.group.conj /-! # Subgroups This file defines multiplicative and additive subgroups as an extension of submonoids, in a bundled form (unbundled subgroups are in `deprecated/subgroups.lean`). We prove subgroups of a group form a complete lattice, and results about images and preimages of subgroups under group homomorphisms. The bundled subgroups use bundled monoid homomorphisms. There are also theorems about the subgroups generated by an element or a subset of a group, defined both inductively and as the infimum of the set of subgroups containing a given element/subset. Special thanks goes to Amelia Livingston and Yury Kudryashov for their help and inspiration. ## Main definitions Notation used here: - `G N` are `group`s - `A` is an `add_group` - `H K` are `subgroup`s of `G` or `add_subgroup`s of `A` - `x` is an element of type `G` or type `A` - `f g : N →* G` are group homomorphisms - `s k` are sets of elements of type `G` Definitions in the file: * `subgroup G` : the type of subgroups of a group `G` * `add_subgroup A` : the type of subgroups of an additive group `A` * `complete_lattice (subgroup G)` : the subgroups of `G` form a complete lattice * `subgroup.closure k` : the minimal subgroup that includes the set `k` * `subgroup.subtype` : the natural group homomorphism from a subgroup of group `G` to `G` * `subgroup.gi` : `closure` forms a Galois insertion with the coercion to set * `subgroup.comap H f` : the preimage of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.map f H` : the image of a subgroup `H` along the group homomorphism `f` is also a subgroup * `subgroup.prod H K` : the product of subgroups `H`, `K` of groups `G`, `N` respectively, `H × K` is a subgroup of `G × N` * `monoid_hom.range f` : the range of the group homomorphism `f` is a subgroup * `monoid_hom.ker f` : the kernel of a group homomorphism `f` is the subgroup of elements `x : G` such that `f x = 1` * `monoid_hom.eq_locus f g` : given group homomorphisms `f`, `g`, the elements of `G` such that `f x = g x` form a subgroup of `G` ## Implementation notes Subgroup inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a subgroup's underlying set. ## Tags subgroup, subgroups -/ open_locale big_operators variables {G : Type*} [group G] variables {A : Type*} [add_group A] set_option old_structure_cmd true /-- A subgroup of a group `G` is a subset containing 1, closed under multiplication and closed under multiplicative inverse. -/ structure subgroup (G : Type*) [group G] extends submonoid G := (inv_mem' {x} : x ∈ carrier → x⁻¹ ∈ carrier) /-- An additive subgroup of an additive group `G` is a subset containing 0, closed under addition and additive inverse. -/ structure add_subgroup (G : Type*) [add_group G] extends add_submonoid G:= (neg_mem' {x} : x ∈ carrier → -x ∈ carrier) attribute [to_additive] subgroup attribute [to_additive add_subgroup.to_add_submonoid] subgroup.to_submonoid /-- Reinterpret a `subgroup` as a `submonoid`. -/ add_decl_doc subgroup.to_submonoid /-- Reinterpret an `add_subgroup` as an `add_submonoid`. -/ add_decl_doc add_subgroup.to_add_submonoid /-- Map from subgroups of group `G` to `add_subgroup`s of `additive G`. -/ def subgroup.to_add_subgroup {G : Type*} [group G] (H : subgroup G) : add_subgroup (additive G) := { neg_mem' := H.inv_mem', .. submonoid.to_add_submonoid H.to_submonoid} /-- Map from `add_subgroup`s of `additive G` to subgroups of `G`. -/ def subgroup.of_add_subgroup {G : Type*} [group G] (H : add_subgroup (additive G)) : subgroup G := { inv_mem' := H.neg_mem', .. submonoid.of_add_submonoid H.to_add_submonoid} /-- Map from `add_subgroup`s of `add_group G` to subgroups of `multiplicative G`. -/ def add_subgroup.to_subgroup {G : Type*} [add_group G] (H : add_subgroup G) : subgroup (multiplicative G) := { inv_mem' := H.neg_mem', .. add_submonoid.to_submonoid H.to_add_submonoid} /-- Map from subgroups of `multiplicative G` to `add_subgroup`s of `add_group G`. -/ def add_subgroup.of_subgroup {G : Type*} [add_group G] (H : subgroup (multiplicative G)) : add_subgroup G := { neg_mem' := H.inv_mem', .. add_submonoid.of_submonoid H.to_submonoid } /-- Subgroups of group `G` are isomorphic to additive subgroups of `additive G`. -/ def subgroup.add_subgroup_equiv (G : Type*) [group G] : subgroup G ≃ add_subgroup (additive G) := { to_fun := subgroup.to_add_subgroup, inv_fun := subgroup.of_add_subgroup, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl } namespace subgroup @[to_additive] instance : has_coe (subgroup G) (set G) := { coe := subgroup.carrier } @[simp, to_additive] lemma coe_to_submonoid (K : subgroup G) : (K.to_submonoid : set G) = K := rfl @[to_additive] instance : has_mem G (subgroup G) := ⟨λ m K, m ∈ (K : set G)⟩ @[to_additive] instance : has_coe_to_sort (subgroup G) := ⟨_, λ G, (G : Type*)⟩ @[simp, norm_cast, to_additive] lemma mem_coe {K : subgroup G} {g : G} : g ∈ (K : set G) ↔ g ∈ K := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (K : subgroup G) : ↥(K : set G) = K := rfl -- note that `to_additive` transfers the `simp` attribute over but not the `norm_cast` attribute attribute [norm_cast] add_subgroup.mem_coe attribute [norm_cast] add_subgroup.coe_coe end subgroup @[to_additive] protected lemma subgroup.exists {K : subgroup G} {p : K → Prop} : (∃ x : K, p x) ↔ ∃ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.exists @[to_additive] protected lemma subgroup.forall {K : subgroup G} {p : K → Prop} : (∀ x : K, p x) ↔ ∀ x ∈ K, p ⟨x, ‹x ∈ K›⟩ := set_coe.forall namespace subgroup variables (H K : subgroup G) /-- Copy of a subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ @[to_additive "Copy of an additive subgroup with a new `carrier` equal to the old one. Useful to fix definitional equalities"] protected def copy (K : subgroup G) (s : set G) (hs : s = K) : subgroup G := { carrier := s, one_mem' := hs.symm ▸ K.one_mem', mul_mem' := hs.symm ▸ K.mul_mem', inv_mem' := hs.symm ▸ K.inv_mem' } /- Two subgroups are equal if the underlying set are the same. -/ @[to_additive "Two `add_group`s are equal if the underlying subsets are equal."] theorem ext' {H K : subgroup G} (h : (H : set G) = K) : H = K := by { cases H, cases K, congr, exact h } /- Two subgroups are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_subgroup`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {H K : subgroup G} : H = K ↔ (H : set G) = K := ⟨λ h, h ▸ rfl, ext'⟩ /-- Two subgroups are equal if they have the same elements. -/ @[ext, to_additive "Two `add_subgroup`s are equal if they have the same elements."] theorem ext {H K : subgroup G} (h : ∀ x, x ∈ H ↔ x ∈ K) : H = K := ext' $ set.ext h attribute [ext] add_subgroup.ext /-- A subgroup contains the group's 1. -/ @[to_additive "An `add_subgroup` contains the group's 0."] theorem one_mem : (1 : G) ∈ H := H.one_mem' /-- A subgroup is closed under multiplication. -/ @[to_additive "An `add_subgroup` is closed under addition."] theorem mul_mem {x y : G} : x ∈ H → y ∈ H → x * y ∈ H := λ hx hy, H.mul_mem' hx hy /-- A subgroup is closed under inverse. -/ @[to_additive "An `add_subgroup` is closed under inverse."] theorem inv_mem {x : G} : x ∈ H → x⁻¹ ∈ H := λ hx, H.inv_mem' hx @[simp, to_additive] theorem inv_mem_iff {x : G} : x⁻¹ ∈ H ↔ x ∈ H := ⟨λ h, inv_inv x ▸ H.inv_mem h, H.inv_mem⟩ @[to_additive] lemma mul_mem_cancel_right {x y : G} (h : x ∈ H) : y * x ∈ H ↔ y ∈ H := ⟨λ hba, by simpa using H.mul_mem hba (H.inv_mem h), λ hb, H.mul_mem hb h⟩ @[to_additive] lemma mul_mem_cancel_left {x y : G} (h : x ∈ H) : x * y ∈ H ↔ y ∈ H := ⟨λ hab, by simpa using H.mul_mem (H.inv_mem h) hab, H.mul_mem h⟩ /-- Product of a list of elements in a subgroup is in the subgroup. -/ @[to_additive "Sum of a list of elements in an `add_subgroup` is in the `add_subgroup`."] lemma list_prod_mem {l : list G} : (∀ x ∈ l, x ∈ K) → l.prod ∈ K := K.to_submonoid.list_prod_mem /-- Product of a multiset of elements in a subgroup of a `comm_group` is in the subgroup. -/ @[to_additive "Sum of a multiset of elements in an `add_subgroup` of an `add_comm_group` is in the `add_subgroup`."] lemma multiset_prod_mem {G} [comm_group G] (K : subgroup G) (g : multiset G) : (∀ a ∈ g, a ∈ K) → g.prod ∈ K := K.to_submonoid.multiset_prod_mem g /-- Product of elements of a subgroup of a `comm_group` indexed by a `finset` is in the subgroup. -/ @[to_additive "Sum of elements in an `add_subgroup` of an `add_comm_group` indexed by a `finset` is in the `add_subgroup`."] lemma prod_mem {G : Type*} [comm_group G] (K : subgroup G) {ι : Type*} {t : finset ι} {f : ι → G} (h : ∀ c ∈ t, f c ∈ K) : ∏ c in t, f c ∈ K := K.to_submonoid.prod_mem h lemma pow_mem {x : G} (hx : x ∈ K) : ∀ n : ℕ, x ^ n ∈ K := K.to_submonoid.pow_mem hx lemma gpow_mem {x : G} (hx : x ∈ K) : ∀ n : ℤ, x ^ n ∈ K | (int.of_nat n) := pow_mem _ hx n | -[1+ n] := K.inv_mem $ K.pow_mem hx n.succ /-- Construct a subgroup from a nonempty set that is closed under division. -/ @[to_additive "Construct a subgroup from a nonempty set that is closed under subtraction"] def of_div (s : set G) (hsn : s.nonempty) (hs : ∀ x y ∈ s, x * y⁻¹ ∈ s) : subgroup G := have one_mem : (1 : G) ∈ s, from let ⟨x, hx⟩ := hsn in by simpa using hs x x hx hx, have inv_mem : ∀ x, x ∈ s → x⁻¹ ∈ s, from λ x hx, by simpa using hs 1 x one_mem hx, { carrier := s, one_mem' := one_mem, inv_mem' := inv_mem, mul_mem' := λ x y hx hy, by simpa using hs x y⁻¹ hx (inv_mem y hy) } /-- A subgroup of a group inherits a multiplication. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an addition."] instance has_mul : has_mul H := H.to_submonoid.has_mul /-- A subgroup of a group inherits a 1. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits a zero."] instance has_one : has_one H := H.to_submonoid.has_one /-- A subgroup of a group inherits an inverse. -/ @[to_additive "A `add_subgroup` of a `add_group` inherits an inverse."] instance has_inv : has_inv H := ⟨λ a, ⟨a⁻¹, H.inv_mem a.2⟩⟩ @[simp, norm_cast, to_additive] lemma coe_mul (x y : H) : (↑(x * y) : G) = ↑x * ↑y := rfl @[simp, norm_cast, to_additive] lemma coe_one : ((1 : H) : G) = 1 := rfl @[simp, norm_cast, to_additive] lemma coe_inv (x : H) : ↑(x⁻¹ : H) = (x⁻¹ : G) := rfl @[simp, norm_cast, to_additive] lemma coe_mk (x : G) (hx : x ∈ H) : ((⟨x, hx⟩ : H) : G) = x := rfl attribute [norm_cast] add_subgroup.coe_add add_subgroup.coe_zero add_subgroup.coe_neg add_subgroup.coe_mk /-- A subgroup of a group inherits a group structure. -/ @[to_additive "An `add_subgroup` of an `add_group` inherits an `add_group` structure."] instance to_group {G : Type*} [group G] (H : subgroup G) : group H := { inv := has_inv.inv, mul_left_inv := λ x, subtype.eq $ mul_left_inv x, .. H.to_submonoid.to_monoid } /-- A subgroup of a `comm_group` is a `comm_group`. -/ @[to_additive "An `add_subgroup` of an `add_comm_group` is an `add_comm_group`."] instance to_comm_group {G : Type*} [comm_group G] (H : subgroup G) : comm_group H := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, .. H.to_group} /-- The natural group hom from a subgroup of group `G` to `G`. -/ @[to_additive "The natural group hom from an `add_subgroup` of `add_group` `G` to `G`."] def subtype : H →* G := ⟨coe, rfl, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : ⇑H.subtype = coe := rfl @[simp, norm_cast] lemma coe_pow (x : H) (n : ℕ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_pow _ _ _ @[simp, norm_cast] lemma coe_gpow (x : H) (n : ℤ) : ((x ^ n : H) : G) = x ^ n := coe_subtype H ▸ monoid_hom.map_gpow _ _ _ @[to_additive] instance : has_le (subgroup G) := ⟨λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K⟩ @[to_additive] lemma le_def {H K : subgroup G} : H ≤ K ↔ ∀ ⦃x : G⦄, x ∈ H → x ∈ K := iff.rfl @[simp, to_additive] lemma coe_subset_coe {H K : subgroup G} : (H : set G) ⊆ K ↔ H ≤ K := iff.rfl @[to_additive] instance : partial_order (subgroup G) := { le := (≤), .. partial_order.lift (coe : subgroup G → set G) (λ a b, ext') } /-- The subgroup `G` of the group `G`. -/ @[to_additive "The `add_subgroup G` of the `add_group G`."] instance : has_top (subgroup G) := ⟨{ inv_mem' := λ _ _, set.mem_univ _ , .. (⊤ : submonoid G) }⟩ /-- The trivial subgroup `{1}` of an group `G`. -/ @[to_additive "The trivial `add_subgroup` `{0}` of an `add_group` `G`."] instance : has_bot (subgroup G) := ⟨{ inv_mem' := λ _, by simp *, .. (⊥ : submonoid G) }⟩ @[to_additive] instance : inhabited (subgroup G) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : G} : x ∈ (⊥ : subgroup G) ↔ x = 1 := iff.rfl @[simp, to_additive] lemma mem_top (x : G) : x ∈ (⊤ : subgroup G) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : subgroup G) : set G) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : subgroup G) : set G) = {1} := rfl @[to_additive] lemma eq_bot_iff_forall : H = ⊥ ↔ ∀ x ∈ H, x = (1 : G) := begin split, { intros h x x_in, rwa [h, mem_bot] at x_in }, { intros h, ext x, rw mem_bot, exact ⟨h x, by { rintros rfl, exact H.one_mem }⟩ }, end @[to_additive] lemma nontrivial_iff_exists_ne_one (H : subgroup G) : nontrivial H ↔ ∃ x ∈ H, x ≠ (1:G) := begin split, { introI h, rcases exists_ne (1 : H) with ⟨⟨h, h_in⟩, h_ne⟩, use [h, h_in], intro hyp, apply h_ne, simpa [hyp] }, { rintros ⟨x, x_in, hx⟩, apply nontrivial_of_ne (⟨x, x_in⟩ : H) 1, intro hyp, apply hx, simpa [has_one.one] using hyp }, end /-- A subgroup is either the trivial subgroup or nontrivial. -/ @[to_additive] lemma bot_or_nontrivial (H : subgroup G) : H = ⊥ ∨ nontrivial H := begin classical, by_cases h : ∀ x ∈ H, x = (1 : G), { left, exact H.eq_bot_iff_forall.mpr h }, { right, push_neg at h, simpa [nontrivial_iff_exists_ne_one] using h }, end /-- A subgroup is either the trivial subgroup or contains a nonzero element. -/ @[to_additive] lemma bot_or_exists_ne_one (H : subgroup G) : H = ⊥ ∨ ∃ x ∈ H, x ≠ (1:G) := begin convert H.bot_or_nontrivial, rw nontrivial_iff_exists_ne_one end /-- The inf of two subgroups is their intersection. -/ @[to_additive "The inf of two `add_subgroups`s is their intersection."] instance : has_inf (subgroup G) := ⟨λ H₁ H₂, { inv_mem' := λ _ ⟨hx, hx'⟩, ⟨H₁.inv_mem hx, H₂.inv_mem hx'⟩, .. H₁.to_submonoid ⊓ H₂.to_submonoid }⟩ @[simp, to_additive] lemma coe_inf (p p' : subgroup G) : ((p ⊓ p' : subgroup G) : set G) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : subgroup G} {x : G} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (subgroup G) := ⟨λ s, { inv_mem' := λ x hx, set.mem_bInter $ λ i h, i.inv_mem (by apply set.mem_bInter_iff.1 hx i h), .. (⨅ S ∈ s, subgroup.to_submonoid S).copy (⋂ S ∈ s, ↑S) (by simp) }⟩ @[simp, to_additive] lemma coe_Inf (H : set (subgroup G)) : ((Inf H : subgroup G) : set G) = ⋂ s ∈ H, ↑s := rfl attribute [norm_cast] coe_Inf add_subgroup.coe_Inf @[simp, to_additive] lemma mem_Inf {S : set (subgroup G)} {x : G} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → subgroup G} {x : G} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → subgroup G} : (↑(⨅ i, S i) : set G) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_infi add_subgroup.coe_infi /-- Subgroups of a group form a complete lattice. -/ @[to_additive "The `add_subgroup`s of an `add_group` form a complete lattice."] instance : complete_lattice (subgroup G) := { bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (subgroup G) $ λ s, is_glb.of_image (λ H K, show (H : set G) ≤ K ↔ H ≤ K, from coe_subset_coe) is_glb_binfi } @[to_additive] lemma mem_sup_left {S T : subgroup G} : ∀ {x : G}, x ∈ S → x ∈ S ⊔ T := show S ≤ S ⊔ T, from le_sup_left @[to_additive] lemma mem_sup_right {S T : subgroup G} : ∀ {x : G}, x ∈ T → x ∈ S ⊔ T := show T ≤ S ⊔ T, from le_sup_right @[to_additive] lemma mem_supr_of_mem {ι : Type*} {S : ι → subgroup G} (i : ι) : ∀ {x : G}, x ∈ S i → x ∈ supr S := show S i ≤ supr S, from le_supr _ _ @[to_additive] lemma mem_Sup_of_mem {S : set (subgroup G)} {s : subgroup G} (hs : s ∈ S) : ∀ {x : G}, x ∈ s → x ∈ Sup S := show s ≤ Sup S, from le_Sup hs /-- The `subgroup` generated by a set. -/ @[to_additive "The `add_subgroup` generated by a set"] def closure (k : set G) : subgroup G := Inf {K | k ⊆ K} variable {k : set G} @[to_additive] lemma mem_closure {x : G} : x ∈ closure k ↔ ∀ K : subgroup G, k ⊆ K → x ∈ K := mem_Inf /-- The subgroup generated by a set includes the set. -/ @[simp, to_additive "The `add_subgroup` generated by a set includes the set."] lemma subset_closure : k ⊆ closure k := λ x hx, mem_closure.2 $ λ K hK, hK hx open set /-- A subgroup `K` includes `closure k` if and only if it includes `k`. -/ @[simp, to_additive "An additive subgroup `K` includes `closure k` if and only if it includes `k`"] lemma closure_le : closure k ≤ K ↔ k ⊆ K := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ @[to_additive] lemma closure_eq_of_le (h₁ : k ⊆ K) (h₂ : K ≤ closure k) : closure k = K := le_antisymm ((closure_le $ K).2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `k`, and is preserved under multiplication and inverse, then `p` holds for all elements of the closure of `k`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `k`, and is preserved under addition and isvers, then `p` holds for all elements of the additive closure of `k`."] lemma closure_induction {p : G → Prop} {x} (h : x ∈ closure k) (Hk : ∀ x ∈ k, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) (Hinv : ∀ x, p x → p x⁻¹) : p x := (@closure_le _ _ ⟨p, H1, Hmul, Hinv⟩ _).2 Hk h attribute [elab_as_eliminator] subgroup.closure_induction add_subgroup.closure_induction variable (G) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure G _) coe := { choice := λ s _, closure s, gc := λ s t, @closure_le _ _ t s, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {G} /-- Subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`. -/ @[to_additive "Additive subgroup closure of a set is monotone in its argument: if `h ⊆ k`, then `closure h ≤ closure k`"] lemma closure_mono ⦃h k : set G⦄ (h' : h ⊆ k) : closure h ≤ closure k := (subgroup.gi G).gc.monotone_l h' /-- Closure of a subgroup `K` equals `K`. -/ @[simp, to_additive "Additive closure of an additive subgroup `K` equals `K`"] lemma closure_eq : closure (K : set G) = K := (subgroup.gi G).l_u_eq K @[simp, to_additive] lemma closure_empty : closure (∅ : set G) = ⊥ := (subgroup.gi G).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set G) = ⊤ := @coe_top G _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set G) : closure (s ∪ t) = closure s ⊔ closure t := (subgroup.gi G).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set G) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subgroup.gi G).gc.l_supr /-- The subgroup generated by an element of a group equals the set of integer number powers of the element. -/ lemma mem_closure_singleton {x y : G} : y ∈ closure ({x} : set G) ↔ ∃ n : ℤ, x ^ n = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gpow_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, gpow_one x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, gpow_add x n m⟩ }, rintros _ ⟨n, rfl⟩, exact ⟨-n, gpow_neg x n⟩ end lemma closure_singleton_one : closure ({1} : set G) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] @[to_additive] lemma mem_supr_of_directed {ι} [hι : nonempty ι] {K : ι → subgroup G} (hK : directed (≤) K) {x : G} : x ∈ (supr K : subgroup G) ↔ ∃ i, x ∈ K i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr K i) hi⟩, suffices : x ∈ closure (⋃ i, (K i : set G)) → ∃ i, x ∈ K i, by simpa only [closure_Union, closure_eq (K _)] using this, refine (λ hx, closure_induction hx (λ _, mem_Union.1) _ _ _), { exact hι.elim (λ i, ⟨i, (K i).one_mem⟩) }, { rintros x y ⟨i, hi⟩ ⟨j, hj⟩, rcases hK i j with ⟨k, hki, hkj⟩, exact ⟨k, (K k).mul_mem (hki hi) (hkj hj)⟩ }, rintros _ ⟨i, hi⟩, exact ⟨i, inv_mem (K i) hi⟩ end @[to_additive] lemma coe_supr_of_directed {ι} [nonempty ι] {S : ι → subgroup G} (hS : directed (≤) S) : ((⨆ i, S i : subgroup G) : set G) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] @[to_additive] lemma mem_Sup_of_directed_on {K : set (subgroup G)} (Kne : K.nonempty) (hK : directed_on (≤) K) {x : G} : x ∈ Sup K ↔ ∃ s ∈ K, x ∈ s := begin haveI : nonempty K := Kne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hK.directed_coe, set_coe.exists, subtype.coe_mk] end variables {N : Type*} [group N] {P : Type*} [group P] /-- The preimage of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The preimage of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def comap {N : Type*} [group N] (f : G →* N) (H : subgroup N) : subgroup G := { carrier := (f ⁻¹' H), inv_mem' := λ a ha, show f a⁻¹ ∈ H, by rw f.map_inv; exact H.inv_mem ha, .. H.to_submonoid.comap f } @[simp, to_additive] lemma coe_comap (K : subgroup N) (f : G →* N) : (K.comap f : set G) = f ⁻¹' K := rfl @[simp, to_additive] lemma mem_comap {K : subgroup N} {f : G →* N} {x : G} : x ∈ K.comap f ↔ f x ∈ K := iff.rfl @[to_additive] lemma comap_comap (K : subgroup P) (g : N →* P) (f : G →* N) : (K.comap g).comap f = K.comap (g.comp f) := rfl /-- The image of a subgroup along a monoid homomorphism is a subgroup. -/ @[to_additive "The image of an `add_subgroup` along an `add_monoid` homomorphism is an `add_subgroup`."] def map (f : G →* N) (H : subgroup G) : subgroup N := { carrier := (f '' H), inv_mem' := by { rintros _ ⟨x, hx, rfl⟩, exact ⟨x⁻¹, H.inv_mem hx, f.map_inv x⟩ }, .. H.to_submonoid.map f } @[simp, to_additive] lemma coe_map (f : G →* N) (K : subgroup G) : (K.map f : set N) = f '' K := rfl @[simp, to_additive] lemma mem_map {f : G →* N} {K : subgroup G} {y : N} : y ∈ K.map f ↔ ∃ x ∈ K, f x = y := mem_image_iff_bex @[to_additive] lemma map_map (g : N →* P) (f : G →* N) : (K.map f).map g = K.map (g.comp f) := ext' $ image_image _ _ _ @[to_additive] lemma map_le_iff_le_comap {f : G →* N} {K : subgroup G} {H : subgroup N} : K.map f ≤ H ↔ K ≤ H.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : G →* N) : galois_connection (map f) (comap f) := λ _ _, map_le_iff_le_comap @[to_additive] lemma map_sup (H K : subgroup G) (f : G →* N) : (H ⊔ K).map f = H.map f ⊔ K.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : G →* N) (s : ι → subgroup G) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (H K : subgroup N) (f : G →* N) : (H ⊓ K).comap f = H.comap f ⊓ K.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : G →* N) (s : ι → subgroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : G →* N) : (⊥ : subgroup G).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : G →* N) : (⊤ : subgroup N).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subgroup`s `H`, `K` of groups `G`, `N` respectively, `H × K` as a subgroup of `G × N`. -/ @[to_additive prod "Given `add_subgroup`s `H`, `K` of `add_group`s `A`, `B` respectively, `H × K` as an `add_subgroup` of `A × B`."] def prod (H : subgroup G) (K : subgroup N) : subgroup (G × N) := { inv_mem' := λ _ hx, ⟨H.inv_mem' hx.1, K.inv_mem' hx.2⟩, .. submonoid.prod H.to_submonoid K.to_submonoid} @[to_additive coe_prod] lemma coe_prod (H : subgroup G) (K : subgroup N) : (H.prod K : set (G × N)) = (H : set G).prod (K : set N) := rfl @[to_additive mem_prod] lemma mem_prod {H : subgroup G} {K : subgroup N} {p : G × N} : p ∈ H.prod K ↔ p.1 ∈ H ∧ p.2 ∈ K := iff.rfl @[to_additive prod_mono] lemma prod_mono : ((≤) ⇒ (≤) ⇒ (≤)) (@prod G _ N _) (@prod G _ N _) := λ s s' hs t t' ht, set.prod_mono hs ht @[to_additive prod_mono_right] lemma prod_mono_right (K : subgroup G) : monotone (λ t : subgroup N, K.prod t) := prod_mono (le_refl K) @[to_additive prod_mono_left] lemma prod_mono_left (H : subgroup N) : monotone (λ K : subgroup G, K.prod H) := λ s₁ s₂ hs, prod_mono hs (le_refl H) @[to_additive prod_top] lemma prod_top (K : subgroup G) : K.prod (⊤ : subgroup N) = K.comap (monoid_hom.fst G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] @[to_additive top_prod] lemma top_prod (H : subgroup N) : (⊤ : subgroup G).prod H = H.comap (monoid_hom.snd G N) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subgroup G).prod (⊤ : subgroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subgroup G).prod (⊥ : subgroup N) = ⊥ := ext' $ by simp [coe_prod, prod.one_eq_mk] /-- Product of subgroups is isomorphic to their product as groups. -/ @[to_additive prod_equiv "Product of additive subgroups is isomorphic to their product as additive groups"] def prod_equiv (H : subgroup G) (K : subgroup N) : H.prod K ≃* H × K := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑H ↑K } /-- A subgroup is normal if whenever `n ∈ H`, then `g * n * g⁻¹ ∈ H` for every `g : G` -/ structure normal : Prop := (conj_mem : ∀ n, n ∈ H → ∀ g : G, g * n * g⁻¹ ∈ H) attribute [class] normal end subgroup namespace add_subgroup /-- An add_subgroup is normal if whenever `n ∈ H`, then `g + n - g ∈ H` for every `g : G` -/ structure normal (H : add_subgroup A) : Prop := (conj_mem [] : ∀ n, n ∈ H → ∀ g : A, g + n - g ∈ H) attribute [to_additive add_subgroup.normal] subgroup.normal attribute [class] normal end add_subgroup namespace subgroup variables {H K : subgroup G} @[priority 100, to_additive] instance normal_of_comm {G : Type*} [comm_group G] (H : subgroup G) : H.normal := ⟨by simp [mul_comm, mul_left_comm]⟩ namespace normal variable (nH : H.normal) @[to_additive] lemma mem_comm {a b : G} (h : a * b ∈ H) : b * a ∈ H := have a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ H, from nH.conj_mem (a * b) h a⁻¹, by simpa @[to_additive] lemma mem_comm_iff {a b : G} : a * b ∈ H ↔ b * a ∈ H := ⟨nH.mem_comm, nH.mem_comm⟩ end normal @[priority 100, to_additive] instance bot_normal : normal (⊥ : subgroup G) := ⟨by simp⟩ variable (G) /-- The center of a group `G` is the set of elements that commute with everything in `G` -/ @[to_additive "The center of a group `G` is the set of elements that commute with everything in `G`"] def center : subgroup G := { carrier := {z | ∀ g, g * z = z * g}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ g, g * a = a * g) (hb : ∀ g, g * b = b * g) g, by assoc_rw [ha, hb g], inv_mem' := λ a (ha : ∀ g, g * a = a * g) g, by rw [← inv_inj, mul_inv_rev, inv_inv, ← ha, mul_inv_rev, inv_inv] } variable {G} @[to_additive] lemma mem_center_iff {z : G} : z ∈ center G ↔ ∀ g, g * z = z * g := iff.rfl @[priority 100, to_additive] instance center_normal : (center G).normal := ⟨begin assume n hn g h, assoc_rw [hn (h * g), hn g], simp end⟩ variables {G} (H) /-- The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal. -/ @[to_additive "The `normalizer` of `H` is the smallest subgroup of `G` inside which `H` is normal."] def normalizer : subgroup G := { carrier := {g : G | ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) (hb : ∀ n, n ∈ H ↔ b * n * b⁻¹ ∈ H) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ H ↔ a * n * a⁻¹ ∈ H) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } -- variant for sets. -- TODO should this replace `normalizer`? /-- The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g*S*g⁻¹=S` -/ @[to_additive "The `set_normalizer` of `S` is the subgroup of `G` whose elements satisfy `g+S-g=S`."] def set_normalizer (S : set G) : subgroup G := { carrier := {g : G | ∀ n, n ∈ S ↔ g * n * g⁻¹ ∈ S}, one_mem' := by simp, mul_mem' := λ a b (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) (hb : ∀ n, n ∈ S ↔ b * n * b⁻¹ ∈ S) n, by { rw [hb, ha], simp [mul_assoc] }, inv_mem' := λ a (ha : ∀ n, n ∈ S ↔ a * n * a⁻¹ ∈ S) n, by { rw [ha (a⁻¹ * n * a⁻¹⁻¹)], simp [mul_assoc] } } variable {H} @[to_additive] lemma mem_normalizer_iff {g : G} : g ∈ normalizer H ↔ ∀ n, n ∈ H ↔ g * n * g⁻¹ ∈ H := iff.rfl @[to_additive] lemma le_normalizer : H ≤ normalizer H := λ x xH n, by rw [H.mul_mem_cancel_right (H.inv_mem xH), H.mul_mem_cancel_left xH] @[priority 100, to_additive] instance normal_in_normalizer : (H.comap H.normalizer.subtype).normal := ⟨λ x xH g, by simpa using (g.2 x).1 xH⟩ open_locale classical @[to_additive] lemma le_normalizer_of_normal [hK : (H.comap K.subtype).normal] (HK : H ≤ K) : K ≤ H.normalizer := λ x hx y, ⟨λ yH, hK.conj_mem ⟨y, HK yH⟩ yH ⟨x, hx⟩, λ yH, by simpa [mem_comap, mul_assoc] using hK.conj_mem ⟨x * y * x⁻¹, HK yH⟩ yH ⟨x⁻¹, K.inv_mem hx⟩⟩ end subgroup namespace group variables {s : set G} /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates (a : G) : set G := {b | is_conj a b} lemma mem_conjugates_self {a : G} : a ∈ conjugates a := is_conj_refl _ /-- Given a set `s`, `conjugates_of_set s` is the set of all conjugates of the elements of `s`. -/ def conjugates_of_set (s : set G) : set G := ⋃ a ∈ s, conjugates a lemma mem_conjugates_of_set_iff {x : G} : x ∈ conjugates_of_set s ↔ ∃ a ∈ s, is_conj a x := set.mem_bUnion_iff theorem subset_conjugates_of_set : s ⊆ conjugates_of_set s := λ (x : G) (h : x ∈ s), mem_conjugates_of_set_iff.2 ⟨x, h, is_conj_refl _⟩ theorem conjugates_of_set_mono {s t : set G} (h : s ⊆ t) : conjugates_of_set s ⊆ conjugates_of_set t := set.bUnion_subset_bUnion_left h lemma conjugates_subset_normal {N : subgroup G} [tn : N.normal] {a : G} (h : a ∈ N) : conjugates a ⊆ N := by { rintros a ⟨c, rfl⟩, exact tn.conj_mem a h c } theorem conjugates_of_set_subset {s : set G} {N : subgroup G} [N.normal] (h : s ⊆ N) : conjugates_of_set s ⊆ N := set.bUnion_subset (λ x H, conjugates_subset_normal (h H)) /-- The set of conjugates of `s` is closed under conjugation. -/ lemma conj_mem_conjugates_of_set {x c : G} : x ∈ conjugates_of_set s → (c * x * c⁻¹ ∈ conjugates_of_set s) := λ H, begin rcases (mem_conjugates_of_set_iff.1 H) with ⟨a,h₁,h₂⟩, exact mem_conjugates_of_set_iff.2 ⟨a, h₁, is_conj_trans h₂ ⟨c,rfl⟩⟩, end end group namespace subgroup open group variable {s : set G} /-- The normal closure of a set `s` is the subgroup closure of all the conjugates of elements of `s`. It is the smallest normal subgroup containing `s`. -/ def normal_closure (s : set G) : subgroup G := closure (conjugates_of_set s) theorem conjugates_of_set_subset_normal_closure : conjugates_of_set s ⊆ normal_closure s := subset_closure theorem subset_normal_closure : s ⊆ normal_closure s := set.subset.trans subset_conjugates_of_set conjugates_of_set_subset_normal_closure /-- The normal closure of `s` is a normal subgroup. -/ instance normal_closure_normal : (normal_closure s).normal := ⟨λ n h g, begin refine subgroup.closure_induction h (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset_normal_closure (conj_mem_conjugates_of_set hx)) }, { simpa using (normal_closure s).one_mem }, { rw ← conj_mul, exact mul_mem _ ihx ihy }, { rw ← conj_inv, exact inv_mem _ ihx } end⟩ /-- The normal closure of `s` is the smallest normal subgroup containing `s`. -/ theorem normal_closure_le_normal {N : subgroup G} [N.normal] (h : s ⊆ N) : normal_closure s ≤ N := begin assume a w, refine closure_induction w (λ x hx, _) _ (λ x y ihx ihy, _) (λ x ihx, _), { exact (conjugates_of_set_subset h hx) }, { exact subgroup.one_mem _ }, { exact subgroup.mul_mem _ ihx ihy }, { exact subgroup.inv_mem _ ihx } end lemma normal_closure_subset_iff {N : subgroup G} [N.normal] : s ⊆ N ↔ normal_closure s ≤ N := ⟨normal_closure_le_normal, set.subset.trans (subset_normal_closure)⟩ theorem normal_closure_mono {s t : set G} (h : s ⊆ t) : normal_closure s ≤ normal_closure t := normal_closure_le_normal (set.subset.trans h subset_normal_closure) theorem normal_closure_eq_infi : normal_closure s = ⨅ (N : subgroup G) [normal N] (hs : s ⊆ N), N := le_antisymm (le_infi (λ N, le_infi (λ hN, by exactI le_infi (normal_closure_le_normal)))) (infi_le_of_le (normal_closure s) (infi_le_of_le (by apply_instance) (infi_le_of_le subset_normal_closure (le_refl _)))) end subgroup namespace add_subgroup open set lemma gsmul_mem (H : add_subgroup A) {x : A} (hx : x ∈ H) : ∀ n : ℤ, gsmul n x ∈ H | (int.of_nat n) := add_submonoid.nsmul_mem H.to_add_submonoid hx n | -[1+ n] := H.neg_mem' $ H.add_mem hx $ add_submonoid.nsmul_mem H.to_add_submonoid hx n lemma sub_mem (H : add_subgroup A) {x y : A} (hx : x ∈ H) (hy : y ∈ H) : x - y ∈ H := H.add_mem hx (H.neg_mem hy) /-- The `add_subgroup` generated by an element of an `add_group` equals the set of natural number multiples of the element. -/ lemma mem_closure_singleton {x y : A} : y ∈ closure ({x} : set A) ↔ ∃ n : ℤ, gsmul n x = y := begin refine ⟨λ hy, closure_induction hy _ _ _ _, λ ⟨n, hn⟩, hn ▸ gsmul_mem _ (subset_closure $ mem_singleton x) n⟩, { intros y hy, rw [eq_of_mem_singleton hy], exact ⟨1, one_gsmul x⟩ }, { exact ⟨0, rfl⟩ }, { rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩, exact ⟨n + m, add_gsmul x n m⟩ }, { rintros _ ⟨n, rfl⟩, refine ⟨-n, neg_gsmul x n⟩ } end lemma closure_singleton_zero : closure ({0} : set A) = ⊥ := by simp [eq_bot_iff_forall, mem_closure_singleton] variable (H : add_subgroup A) @[simp] lemma coe_smul (x : H) (n : ℕ) : ((nsmul n x : H) : A) = nsmul n x := coe_subtype H ▸ add_monoid_hom.map_nsmul _ _ _ @[simp] lemma coe_gsmul (x : H) (n : ℤ) : ((n •ℤ x : H) : A) = n •ℤ x := coe_subtype H ▸ add_monoid_hom.map_gsmul _ _ _ attribute [to_additive add_subgroup.coe_smul] subgroup.coe_pow attribute [to_additive add_subgroup.coe_gsmul] subgroup.coe_gpow end add_subgroup namespace monoid_hom variables {N : Type*} {P : Type*} [group N] [group P] (K : subgroup G) open subgroup /-- The range of a monoid homomorphism from a group is a subgroup. -/ @[to_additive "The range of an `add_monoid_hom` from an `add_group` is an `add_subgroup`."] def range (f : G →* N) : subgroup N := subgroup.copy ((⊤ : subgroup G).map f) (set.range f) (by simp [set.ext_iff]) @[simp, to_additive] lemma coe_range (f : G →* N) : (f.range : set N) = set.range f := rfl @[simp, to_additive] lemma mem_range {f : G →* N} {y : N} : y ∈ f.range ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma range_eq_map (f : G →* N) : f.range = (⊤ : subgroup G).map f := by ext; simp /-- The canonical surjective group homomorphism `G →* f(G)` induced by a group homomorphism `G →* N`. -/ @[to_additive "The canonical surjective `add_group` homomorphism `G →+ f(G)` induced by a group homomorphism `G →+ N`."] def to_range (f : G →* N) : G →* f.range := monoid_hom.mk' (λ g, ⟨f g, ⟨g, rfl⟩⟩) $ λ a b, by {ext, exact f.map_mul' _ _} @[to_additive] lemma map_range (g : N →* P) (f : G →* N) : f.range.map g = (g.comp f).range := by rw [range_eq_map, range_eq_map]; exact (⊤ : subgroup G).map_map g f @[to_additive] lemma range_top_iff_surjective {N} [group N] {f : G →* N} : f.range = (⊤ : subgroup N) ↔ function.surjective f := subgroup.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective monoid homomorphism is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_monoid` homomorphism is the whole of the codomain."] lemma range_top_of_surjective {N} [group N] (f : G →* N) (hf : function.surjective f) : f.range = (⊤ : subgroup N) := range_top_iff_surjective.2 hf /-- Restriction of a group hom to a subgroup of the codomain. -/ @[to_additive "Restriction of an `add_group` hom to an `add_subgroup` of the codomain."] def cod_restrict (f : G →* N) (S : subgroup N) (h : ∀ x, f x ∈ S) : G →* S := { to_fun := λ n, ⟨f n, h n⟩, map_one' := subtype.eq f.map_one, map_mul' := λ x y, subtype.eq (f.map_mul x y) } /-- The multiplicative kernel of a monoid homomorphism is the subgroup of elements `x : G` such that `f x = 1` -/ @[to_additive "The additive kernel of an `add_monoid` homomorphism is the `add_subgroup` of elements such that `f x = 0`"] def ker (f : G →* N) := (⊥ : subgroup N).comap f @[to_additive] lemma mem_ker (f : G →* N) {x : G} : x ∈ f.ker ↔ f x = 1 := iff.rfl @[to_additive] lemma comap_ker (g : N →* P) (f : G →* N) : g.ker.comap f = (g.comp f).ker := rfl @[to_additive] lemma to_range_ker (f : G →* N) : ker (to_range f) = ker f := begin ext, change (⟨f x, _⟩ : range f) = ⟨1, _⟩ ↔ f x = 1, simp only [], end /-- The subgroup of elements `x : G` such that `f x = g x` -/ @[to_additive "The additive subgroup of elements `x : G` such that `f x = g x`"] def eq_locus (f g : G →* N) : subgroup G := { inv_mem' := λ x (hx : f x = g x), show f x⁻¹ = g x⁻¹, by rw [f.map_inv, g.map_inv, hx], .. eq_mlocus f g} /-- If two monoid homomorphisms are equal on a set, then they are equal on its subgroup closure. -/ @[to_additive] lemma eq_on_closure {f g : G →* N} {s : set G} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from (closure_le _).2 h @[to_additive] lemma eq_of_eq_on_top {f g : G →* N} (h : set.eq_on f g (⊤ : subgroup G)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_dense {s : set G} (hs : closure s = ⊤) {f g : G →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_top $ hs ▸ eq_on_closure h @[to_additive] lemma gclosure_preimage_le (f : G →* N) (s : set N) : closure (f ⁻¹' s) ≤ (closure s).comap f := (closure_le _).2 $ λ x hx, by rw [mem_coe, mem_comap]; exact subset_closure hx /-- The image under a monoid homomorphism of the subgroup generated by a set equals the subgroup generated by the image of the set. -/ @[to_additive "The image under an `add_monoid` hom of the `add_subgroup` generated by a set equals the `add_subgroup` generated by the image of the set."] lemma map_closure (f : G →* N) (s : set G) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image f s) (gclosure_preimage_le _ _)) ((closure_le _).2 $ set.image_subset _ subset_closure) end monoid_hom namespace monoid_hom variables {G₁ G₂ G₃ : Type*} [group G₁] [group G₂] [group G₃] variables (f : G₁ →* G₂) /-- `lift_of_surjective f hf g hg` is the unique group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \ f | \ g | \ v \⌟ G₂----> G₃ ∃!φ ``` -/ @[to_additive "`lift_of_surjective f hf g hg` is the unique additive group homomorphism `φ` * such that `φ.comp f = g` (`lift_of_surjective_comp`), * where `f : G₁ →+* G₂` is surjective (`hf`), * and `g : G₂ →+* G₃` satisfies `hg : f.ker ≤ g.ker`. See `lift_of_surjective_eq` for the uniqueness lemma. ``` G₁. | \\ f | \\ g | \\ v \\⌟ G₂----> G₃ ∃!φ ```"] noncomputable def lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : G₂ →* G₃ := { to_fun := λ b, g (classical.some (hf b)), map_one' := hg (classical.some_spec (hf 1)), map_mul' := begin intros x y, rw [← g.map_mul, ← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one, f.map_mul], simp only [classical.some_spec (hf _)], end } @[simp, to_additive] lemma lift_of_surjective_comp_apply (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (x : G₁) : (f.lift_of_surjective hf g hg) (f x) = g x := begin dsimp [lift_of_surjective], rw [← mul_inv_eq_one, ← g.map_inv, ← g.map_mul, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_mul, f.map_inv, mul_inv_eq_one], simp only [classical.some_spec (hf _)], end @[simp, to_additive] lemma lift_of_surjective_comp (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) : (f.lift_of_surjective hf g hg).comp f = g := by { ext, simp only [comp_apply, lift_of_surjective_comp_apply] } @[to_additive] lemma eq_lift_of_surjective (hf : function.surjective f) (g : G₁ →* G₃) (hg : f.ker ≤ g.ker) (h : G₂ →* G₃) (hh : h.comp f = g) : h = (f.lift_of_surjective hf g hg) := begin ext b, rcases hf b with ⟨a, rfl⟩, simp only [← comp_apply, hh, f.lift_of_surjective_comp], end end monoid_hom variables {N : Type*} [group N] -- Here `H.normal` is an explicit argument so we can use dot notation with `comap`. @[to_additive] lemma subgroup.normal.comap {H : subgroup N} (hH : H.normal) (f : G →* N) : (H.comap f).normal := ⟨λ _, by simp [subgroup.mem_comap, hH.conj_mem] {contextual := tt}⟩ @[priority 100, to_additive] instance subgroup.normal_comap {H : subgroup N} [nH : H.normal] (f : G →* N) : (H.comap f).normal := nH.comap _ @[priority 100, to_additive] instance monoid_hom.normal_ker (f : G →* N) : f.ker.normal := by rw [monoid_hom.ker]; apply_instance namespace subgroup /-- The subgroup generated by an element. -/ def gpowers (g : G) : subgroup G := subgroup.copy (gpowers_hom G g).range (set.range ((^) g : ℤ → G)) rfl @[simp] lemma mem_gpowers (g : G) : g ∈ gpowers g := ⟨1, gpow_one _⟩ lemma gpowers_eq_closure (g : G) : gpowers g = closure {g} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gpowers_hom (g : G) : (gpowers_hom G g).range = gpowers g := rfl lemma gpowers_subset {a : G} {K : subgroup G} (h : a ∈ K) : gpowers a ≤ K := λ x hx, match x, hx with _, ⟨i, rfl⟩ := K.gpow_mem h i end end subgroup namespace add_subgroup /-- The subgroup generated by an element. -/ def gmultiples (a : A) : add_subgroup A := add_subgroup.copy (gmultiples_hom A a).range (set.range ((•ℤ a) : ℤ → A)) rfl @[simp] lemma mem_gmultiples (a : A) : a ∈ gmultiples a := ⟨1, one_gsmul _⟩ lemma gmultiples_eq_closure (a : A) : gmultiples a = closure {a} := by { ext, exact mem_closure_singleton.symm } @[simp] lemma range_gmultiples_hom (a : A) : (gmultiples_hom A a).range = gmultiples a := rfl lemma gmultiples_subset {a : A} {B : add_subgroup A} (h : a ∈ B) : gmultiples a ≤ B := @subgroup.gpowers_subset (multiplicative A) _ _ (B.to_subgroup) h attribute [to_additive add_subgroup.gmultiples] subgroup.gpowers attribute [to_additive add_subgroup.mem_gmultiples] subgroup.mem_gpowers attribute [to_additive add_subgroup.gmultiples_eq_closure] subgroup.gpowers_eq_closure attribute [to_additive add_subgroup.range_gmultiples_hom] subgroup.range_gpowers_hom attribute [to_additive add_subgroup.gmultiples_subset] subgroup.gpowers_subset end add_subgroup namespace mul_equiv variables {H K : subgroup G} /-- Makes the identity isomorphism from a proof two subgroups of a multiplicative group are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subgroups of an additive group are equal."] def subgroup_congr (h : H = K) : H ≃* K := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ subgroup.ext'_iff.1 h } end mul_equiv -- TODO : ↥(⊤ : subgroup H) ≃* H ?
0ea9c4b15f1e0935ee5a2c8024a80e3f0fc5f9fe
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/liouville/liouville_with.lean
9ebc0dcefe9eec41eea2d408994feb1ba854ff36
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,953
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.special_functions.pow import number_theory.liouville.basic import topology.instances.irrational /-! # Liouville numbers with a given exponent We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent, see `forall_liouville_with_iff`. * If `p ≤ 1`, then this condition is trivial. * If `1 < p ≤ 2`, then this condition is equivalent to `irrational x`. The forward implication does not require `p ≤ 2` and is formalized as `liouville_with.irrational`; the other implication follows from approximations by continued fractions and is not formalized yet. * If `p > 2`, then this is a non-trivial condition on irrational numbers. In particular, [Thue–Siegel–Roth theorem](https://en.wikipedia.org/wiki/Roth's_theorem) states that such numbers must be transcendental. In this file we define the predicate `liouville_with` and prove some basic facts about this predicate. ## Tags Liouville number, irrational, irrationality exponent -/ open filter metric real set open_locale filter topological_space /-- We say that a real number `x` is a Liouville number with exponent `p : ℝ` if there exists a real number `C` such that for infinitely many denominators `n` there exists a numerator `m` such that `x ≠ m / n` and `|x - m / n| < C / n ^ p`. A number is a Liouville number in the sense of `liouville` if it is `liouville_with` any real exponent. -/ def liouville_with (p x : ℝ) : Prop := ∃ C, ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p /-- For `p = 1` (hence, for any `p ≤ 1`), the condition `liouville_with p x` is trivial. -/ lemma liouville_with_one (x : ℝ) : liouville_with 1 x := begin use 2, refine ((eventually_gt_at_top 0).mono $ λ n hn, _).frequently, have hn' : (0 : ℝ) < n, by simpa, have : x < ↑(⌊x * ↑n⌋ + 1) / ↑n, { rw [lt_div_iff hn', int.cast_add, int.cast_one], exact int.lt_floor_add_one _ }, refine ⟨⌊x * n⌋ + 1, this.ne, _⟩, rw [abs_sub_comm, abs_of_pos (sub_pos.2 this), rpow_one, sub_lt_iff_lt_add', add_div_eq_mul_add_div _ _ hn'.ne', div_lt_div_right hn'], simpa [bit0, ← add_assoc] using (int.floor_le (x * n)).trans_lt (lt_add_one _) end namespace liouville_with variables {p q x y : ℝ} {r : ℚ} {m : ℤ} {n : ℕ} /-- The constant `C` provided by the definition of `liouville_with` can be made positive. We also add `1 ≤ n` to the list of assumptions about the denominator. While it is equivalent to the original statement, the case `n = 0` breaks many arguments. -/ lemma exists_pos (h : liouville_with p x) : ∃ (C : ℝ) (h₀ : 0 < C), ∃ᶠ n : ℕ in at_top, 1 ≤ n ∧ ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < C / n ^ p := begin rcases h with ⟨C, hC⟩, refine ⟨max C 1, zero_lt_one.trans_le $ le_max_right _ _, _⟩, refine ((eventually_ge_at_top 1).and_frequently hC).mono _, rintro n ⟨hle, m, hne, hlt⟩, refine ⟨hle, m, hne, hlt.trans_le _⟩, exact div_le_div_of_le (rpow_nonneg_of_nonneg n.cast_nonneg _) (le_max_left _ _) end /-- If a number is Liouville with exponent `p`, then it is Liouville with any smaller exponent. -/ lemma mono (h : liouville_with p x) (hle : q ≤ p) : liouville_with q x := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨hn, m, hne, hlt⟩, refine ⟨m, hne, hlt.trans_le $ div_le_div_of_le_left hC₀.le _ _⟩, exacts [rpow_pos_of_pos (nat.cast_pos.2 hn) _, rpow_le_rpow_of_exponent_le (nat.one_le_cast.2 hn) hle] end /-- If `x` satisfies Liouville condition with exponent `p` and `q < p`, then `x` satisfies Liouville condition with exponent `q` and constant `1`. -/ lemma frequently_lt_rpow_neg (h : liouville_with p x) (hlt : q < p) : ∃ᶠ n : ℕ in at_top, ∃ m : ℤ, x ≠ m / n ∧ |x - m / n| < n ^ (-q) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, have : ∀ᶠ n : ℕ in at_top, C < n ^ (p - q), by simpa only [(∘), neg_sub, one_div] using ((tendsto_rpow_at_top (sub_pos.2 hlt)).comp tendsto_coe_nat_at_top_at_top).eventually (eventually_gt_at_top C), refine (this.and_frequently hC).mono _, rintro n ⟨hnC, hn, m, hne, hlt⟩, replace hn : (0 : ℝ) < n := nat.cast_pos.2 hn, refine ⟨m, hne, hlt.trans $ (div_lt_iff $ rpow_pos_of_pos hn _).2 _⟩, rwa [mul_comm, ← rpow_add hn, ← sub_eq_add_neg] end /-- The product of a Liouville number and a nonzero rational number is again a Liouville number. -/ lemma mul_rat (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (x * r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * (|r| * C), (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have A : (↑(r.num * m) : ℝ) / ↑(r.denom • id n) = (m / n) * r, by simp [← div_mul_div_comm, ← r.cast_def, mul_comm], refine ⟨r.num * m, _, _⟩, { rw A, simp [hne, hr] }, { rw [A, ← sub_mul, abs_mul], simp only [smul_eq_mul, id.def, nat.cast_mul], refine (mul_lt_mul_of_pos_right hlt $ abs_pos.2 $ rat.cast_ne_zero.2 hr).trans_le _, rw [mul_rpow, mul_div_mul_left, mul_comm, mul_div_assoc], exacts [(rpow_pos_of_pos (nat.cast_pos.2 r.pos) _).ne', nat.cast_nonneg _, nat.cast_nonneg _] } end /-- The product `x * r`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma mul_rat_iff (hr : r ≠ 0) : liouville_with p (x * r) ↔ liouville_with p x := ⟨λ h, by simpa only [mul_assoc, ← rat.cast_mul, mul_inv_cancel hr, rat.cast_one, mul_one] using h.mul_rat (inv_ne_zero hr), λ h, h.mul_rat hr⟩ /-- The product `r * x`, `r : ℚ`, `r ≠ 0`, is a Liouville number with exponent `p` if and only if `x` satisfies the same condition. -/ lemma rat_mul_iff (hr : r ≠ 0) : liouville_with p (r * x) ↔ liouville_with p x := by rw [mul_comm, mul_rat_iff hr] lemma rat_mul (h : liouville_with p x) (hr : r ≠ 0) : liouville_with p (r * x) := (rat_mul_iff hr).2 h lemma mul_int_iff (hm : m ≠ 0) : liouville_with p (x * m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, mul_rat_iff (int.cast_ne_zero.2 hm)] lemma mul_int (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (x * m) := (mul_int_iff hm).2 h lemma int_mul_iff (hm : m ≠ 0) : liouville_with p (m * x) ↔ liouville_with p x := by rw [mul_comm, mul_int_iff hm] lemma int_mul (h : liouville_with p x) (hm : m ≠ 0) : liouville_with p (m * x) := (int_mul_iff hm).2 h lemma mul_nat_iff (hn : n ≠ 0) : liouville_with p (x * n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, mul_rat_iff (nat.cast_ne_zero.2 hn)] lemma mul_nat (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (x * n) := (mul_nat_iff hn).2 h lemma nat_mul_iff (hn : n ≠ 0) : liouville_with p (n * x) ↔ liouville_with p x:= by rw [mul_comm, mul_nat_iff hn] lemma nat_mul (h : liouville_with p x) (hn : n ≠ 0) : liouville_with p (n * x) := by { rw mul_comm, exact h.mul_nat hn } lemma add_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x + r) := begin rcases h.exists_pos with ⟨C, hC₀, hC⟩, refine ⟨r.denom ^ p * C, (tendsto_id.nsmul_at_top r.pos).frequently (hC.mono _)⟩, rintro n ⟨hn, m, hne, hlt⟩, have hr : (0 : ℝ) < r.denom, from nat.cast_pos.2 r.pos, have hn' : (n : ℝ) ≠ 0, from nat.cast_ne_zero.2 (zero_lt_one.trans_le hn).ne', have : (↑(r.denom * m + r.num * n : ℤ) / ↑(r.denom • id n) : ℝ) = m / n + r, by simp [add_div, hr.ne', mul_div_mul_left, mul_div_mul_right, hn', ← rat.cast_def], refine ⟨r.denom * m + r.num * n, _⟩, rw [this, add_sub_add_right_eq_sub], refine ⟨by simpa, hlt.trans_le (le_of_eq _)⟩, have : (r.denom ^ p : ℝ) ≠ 0, from (rpow_pos_of_pos hr _).ne', simp [mul_rpow, nat.cast_nonneg, mul_div_mul_left, this] end @[simp] lemma add_rat_iff : liouville_with p (x + r) ↔ liouville_with p x := ⟨λ h, by simpa using h.add_rat (-r), λ h, h.add_rat r⟩ @[simp] lemma rat_add_iff : liouville_with p (r + x) ↔ liouville_with p x := by rw [add_comm, add_rat_iff] lemma rat_add (h : liouville_with p x) (r : ℚ) : liouville_with p (r + x) := add_comm x r ▸ h.add_rat r @[simp] lemma add_int_iff : liouville_with p (x + m) ↔ liouville_with p x := by rw [← rat.cast_coe_int m, add_rat_iff] @[simp] lemma int_add_iff : liouville_with p (m + x) ↔ liouville_with p x := by rw [add_comm, add_int_iff] @[simp] lemma add_nat_iff : liouville_with p (x + n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat n, add_rat_iff] @[simp] lemma nat_add_iff : liouville_with p (n + x) ↔ liouville_with p x := by rw [add_comm, add_nat_iff] lemma add_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x + m) := add_int_iff.2 h lemma int_add (h : liouville_with p x) (m : ℤ) : liouville_with p (m + x) := int_add_iff.2 h lemma add_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x + n) := h.add_int n lemma nat_add (h : liouville_with p x) (n : ℕ) : liouville_with p (n + x) := h.int_add n protected lemma neg (h : liouville_with p x) : liouville_with p (-x) := begin rcases h with ⟨C, hC⟩, refine ⟨C, hC.mono _⟩, rintro n ⟨m, hne, hlt⟩, use (-m), simp [neg_div, abs_sub_comm _ x, *] end @[simp] lemma neg_iff : liouville_with p (-x) ↔ liouville_with p x := ⟨λ h, neg_neg x ▸ h.neg, liouville_with.neg⟩ @[simp] lemma sub_rat_iff : liouville_with p (x - r) ↔ liouville_with p x := by rw [sub_eq_add_neg, ← rat.cast_neg, add_rat_iff] lemma sub_rat (h : liouville_with p x) (r : ℚ) : liouville_with p (x - r) := sub_rat_iff.2 h @[simp] lemma sub_int_iff : liouville_with p (x - m) ↔ liouville_with p x := by rw [← rat.cast_coe_int, sub_rat_iff] lemma sub_int (h : liouville_with p x) (m : ℤ) : liouville_with p (x - m) := sub_int_iff.2 h @[simp] lemma sub_nat_iff : liouville_with p (x - n) ↔ liouville_with p x := by rw [← rat.cast_coe_nat, sub_rat_iff] lemma sub_nat (h : liouville_with p x) (n : ℕ) : liouville_with p (x - n) := sub_nat_iff.2 h @[simp] lemma rat_sub_iff : liouville_with p (r - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma rat_sub (h : liouville_with p x) (r : ℚ) : liouville_with p (r - x) := rat_sub_iff.2 h @[simp] lemma int_sub_iff : liouville_with p (m - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma int_sub (h : liouville_with p x) (m : ℤ) : liouville_with p (m - x) := int_sub_iff.2 h @[simp] lemma nat_sub_iff : liouville_with p (n - x) ↔ liouville_with p x := by simp [sub_eq_add_neg] lemma nat_sub (h : liouville_with p x) (n : ℕ) : liouville_with p (n - x) := nat_sub_iff.2 h lemma ne_cast_int (h : liouville_with p x) (hp : 1 < p) (m : ℤ) : x ≠ m := begin rintro rfl, rename m M, rcases ((eventually_gt_at_top 0).and_frequently (h.frequently_lt_rpow_neg hp)).exists with ⟨n : ℕ, hn : 0 < n, m : ℤ, hne : (M : ℝ) ≠ m / n, hlt : |(M - m / n : ℝ)| < n ^ (-1 : ℝ)⟩, refine hlt.not_le _, have hn' : (0 : ℝ) < n, by simpa, rw [rpow_neg_one, ← one_div, sub_div' _ _ _ hn'.ne', abs_div, nat.abs_cast, div_le_div_right hn'], norm_cast, rw [← zero_add (1 : ℤ), int.add_one_le_iff, abs_pos, sub_ne_zero], rw [ne.def, eq_div_iff hn'.ne'] at hne, exact_mod_cast hne end /-- A number satisfying the Liouville condition with exponent `p > 1` is an irrational number. -/ protected lemma irrational (h : liouville_with p x) (hp : 1 < p) : irrational x := begin rintro ⟨r, rfl⟩, rcases eq_or_ne r 0 with (rfl|h0), { refine h.ne_cast_int hp 0 _, rw [rat.cast_zero, int.cast_zero] }, { refine (h.mul_rat (inv_ne_zero h0)).ne_cast_int hp 1 _, simp [rat.cast_ne_zero.2 h0] } end end liouville_with namespace liouville variables {x : ℝ} /-- If `x` is a Liouville number, then for any `n`, for infinitely many denominators `b` there exists a numerator `a` such that `x ≠ a / b` and `|x - a / b| < 1 / b ^ n`. -/ lemma frequently_exists_num (hx : liouville x) (n : ℕ) : ∃ᶠ b : ℕ in at_top, ∃ a : ℤ, x ≠ a / b ∧ |x - a / b| < 1 / b ^ n := begin refine not_not.1 (λ H, _), simp only [liouville, not_forall, not_exists, not_frequently, not_and, not_lt, eventually_at_top] at H, rcases H with ⟨N, hN⟩, have : ∀ b > (1 : ℕ), ∀ᶠ m : ℕ in at_top, ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, { intros b hb, have hb0' : (b : ℚ) ≠ 0 := (zero_lt_one.trans (nat.one_lt_cast.2 hb)).ne', replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have hb0 : (0 : ℝ) < b := zero_lt_one.trans hb, have H : tendsto (λ m, 1 / b ^ m : ℕ → ℝ) at_top (𝓝 0), { simp only [one_div], exact tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt hb) }, refine (H.eventually (hx.irrational.eventually_forall_le_dist_cast_div b)).mono _, exact λ m hm a, hm a }, have : ∀ᶠ m : ℕ in at_top, ∀ b < N, 1 < b → ∀ a : ℤ, (1 / b ^ m : ℝ) ≤ |x - a / b|, from (finite_lt_nat N).eventually_all.2 (λ b hb, eventually_imp_distrib_left.2 (this b)), rcases (this.and (eventually_ge_at_top n)).exists with ⟨m, hm, hnm⟩, rcases hx m with ⟨a, b, hb, hne, hlt⟩, lift b to ℕ using zero_le_one.trans hb.le, norm_cast at hb, push_cast at hne hlt, cases le_or_lt N b, { refine (hN b h a hne).not_lt (hlt.trans_le _), replace hb : (1 : ℝ) < b := nat.one_lt_cast.2 hb, have hb0 : (0 : ℝ) < b := zero_lt_one.trans hb, exact one_div_le_one_div_of_le (pow_pos hb0 _) (pow_le_pow hb.le hnm) }, { exact (hm b h hb _).not_lt hlt } end /-- A Liouville number is a Liouville number with any real exponent. -/ protected lemma liouville_with (hx : liouville x) (p : ℝ) : liouville_with p x := begin suffices : liouville_with ⌈p⌉₊ x, from this.mono (nat.le_ceil p), refine ⟨1, ((eventually_gt_at_top 1).and_frequently (hx.frequently_exists_num ⌈p⌉₊)).mono _⟩, rintro b ⟨hb, a, hne, hlt⟩, refine ⟨a, hne, _⟩, rwa rpow_nat_cast end end liouville /-- A number satisfies the Liouville condition with any exponent if and only if it is a Liouville number. -/ lemma forall_liouville_with_iff {x : ℝ} : (∀ p, liouville_with p x) ↔ liouville x := begin refine ⟨λ H n, _, liouville.liouville_with⟩, rcases ((eventually_gt_at_top 1).and_frequently ((H (n + 1)).frequently_lt_rpow_neg (lt_add_one n))).exists with ⟨b, hb, a, hne, hlt⟩, exact ⟨a, b, by exact_mod_cast hb, hne, by simpa [rpow_neg] using hlt⟩, end
cb1fa65932fac63f0ce4419a2a0965f2fcdf7410
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/category_theory/concrete_category/basic.lean
6fc6ce47d28b6a5cdbd31202768a00d88ef0c185
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
3,967
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Johannes Hölzl, Reid Barton, Sean Leather, Yury Kudryashov -/ import category_theory.types category_theory.full_subcategory /-! # Concrete categories A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type*`. We define concrete categories using `class concrete_category`. In particular, we impose no restrictions on the carrier type `C`, so `Type` is a concrete category with the identity forgetful functor. Each concrete category `C` comes with a canonical faithful functor `forget C : C ⥤ Type*`. We say that a concrete category `C` admits a *forgetful functor* to a concrete category `D`, if it has a functor `forget₂ C D : C ⥤ D` such that `(forget₂ C D) ⋙ (forget D) = forget C`, see `class has_forget₂`. Due to `faithful.div_comp`, it suffices to verify that `forget₂.obj` and `forget₂.map` agree with the equality above; then `forget₂` will satisfy the functor laws automatically, see `has_forget₂.mk'`. Two classes helping construct concrete categories in the two most common cases are provided in the files `bundled_hom` and `unbundled_hom`, see their documentation for details. ## References See [Ahrens and Lumsdaine, *Displayed Categories*][ahrens2017] for related work. -/ universe u namespace category_theory /-- A concrete category is a category `C` with a fixed faithful functor `forget : C ⥤ Type`. -/ class concrete_category (C : Type (u+1)) extends category.{u} C := (forget : C ⥤ Type u) [forget_faithful : faithful forget] /-- The forgetful functor from a concrete category to `Type u`. -/ @[reducible] def forget (C : Type (u+1)) [concrete_category C] : C ⥤ Type u := concrete_category.forget C attribute [instance] concrete_category.forget_faithful instance concrete_category.types : concrete_category (Type u) := { forget := 𝟭 _ } /-- `has_forget₂ C D`, where `C` and `D` are both concrete categories, provides a functor `forget₂ C D : C ⥤ C` and a proof that `forget₂ ⋙ (forget D) = forget C`. -/ class has_forget₂ (C D : Type (u+1)) [concrete_category C] [concrete_category D] := (forget₂ : C ⥤ D) (forget_comp : forget₂ ⋙ (forget D) = forget C) /-- The forgetful functor `C ⥤ D` between concrete categories for which we have an instance `has_forget₂ C `. -/ @[reducible] def forget₂ (C D : Type (u+1)) [concrete_category C] [concrete_category D] [has_forget₂ C D] : C ⥤ D := has_forget₂.forget₂ C D instance forget_faithful (C D : Type (u+1)) [concrete_category C] [concrete_category D] [has_forget₂ C D] : faithful (forget₂ C D) := (has_forget₂.forget_comp C D).faithful_of_comp instance induced_category.concrete_category {C D : Type (u+1)} [concrete_category D] (f : C → D) : concrete_category (induced_category f) := { forget := induced_functor f ⋙ forget D } instance induced_category.has_forget₂ {C D : Type (u+1)} [concrete_category D] (f : C → D) : has_forget₂ (induced_category f) D := { forget₂ := induced_functor f, forget_comp := rfl } /-- In order to construct a “partially forgetting” functor, we do not need to verify functor laws; it suffices to ensure that compositions agree with `forget₂ C D ⋙ forget D = forget C`. -/ def has_forget₂.mk' {C D : Type (u+1)} [concrete_category C] [concrete_category D] (obj : C → D) (h_obj : ∀ X, (forget D).obj (obj X) = (forget C).obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, (forget D).map (map f) == (forget C).map f) : has_forget₂ C D := { forget₂ := faithful.div _ _ _ @h_obj _ @h_map, forget_comp := by apply faithful.div_comp } instance has_forget_to_Type (C : Type (u+1)) [concrete_category C] : has_forget₂ C (Type u) := { forget₂ := forget C, forget_comp := functor.comp_id _ } end category_theory
777a273e87f1ba3eb62b3d4c7dcf790c24d572fb
28be2ab6091504b6ba250b367205fb94d50ab284
/src/game/world10/level18a.lean
20e8b9ede9113172f7e31b529f3aeb3add538f4f
[ "Apache-2.0" ]
permissive
postmasters/natural_number_game
87304ac22e5e1c5ac2382d6e523d6914dd67a92d
38a7adcdfdb18c49c87b37831736c8f15300d821
refs/heads/master
1,649,856,819,031
1,586,444,676,000
1,586,444,676,000
255,006,061
0
0
Apache-2.0
1,586,664,599,000
1,586,664,598,000
null
UTF-8
Lean
false
false
6,024
lean
import game.world10.level17 -- hide namespace mynat -- hide -- todo INTRODUCE CONGR lemma lt_irrefl (a : mynat) : ¬ (a < a) := begin [nat_num_game] intro h, cases h with h1 h2, apply h2, exact h1, end lemma ne_of_lt (a b : mynat) : a < b → a ≠ b := begin [nat_num_game] intro h, intro h1, cases h with h2 h3, apply h3, rw h1, refl, end -- I had -- theorem ne_zero_of_pos (a : mynat) : 0 < a → a ≠ 0 := -- do we really need this?? theorem not_lt_zero (a : mynat) : ¬(a < 0) := begin [nat_num_game] intro h, cases h with ha hna, apply hna, exact zero_le a, end theorem lt_of_lt_of_le (a b c : mynat) : a < b → b ≤ c → a < c := begin intro hab, intro hbc, rw lt_iff_succ_le at hab ⊢, cases hbc with x hx, cases hab with y hy, rw hx, rw hy, use y + x, ring, end theorem lt_of_le_of_lt (a b c : mynat) : a ≤ b → b < c → a < c := begin [nat_num_game] intro hab, intro hbc, rw lt_iff_succ_le at hbc ⊢, cases hbc with x hx, cases hab with y hy, rw hx, rw hy, use y + x, rw succ_add, rw succ_add, rw add_assoc, refl, end theorem lt_trans (a b c : mynat) : a < b → b < c → a < c := begin [nat_num_game] intro hab, intro hbc, rw lt_iff_succ_le at hab hbc ⊢, cases hbc with x hx, cases hab with y hy, rw hx, rw hy, use y + x + 1, repeat {rw succ_add}, repeat {rw succ_eq_add_one}, simp, end theorem lt_iff_le_and_ne (a b : mynat) : a < b ↔ a ≤ b ∧ a ≠ b := begin [nat_num_game] split, intro h, cases h with h1 h2, split, assumption, intro h, apply h2, rw h, refl, intro h, cases h with h1 h2, split, exact h1, intro h, apply h2, exact le_antisymm _ _ h1 h end theorem lt_succ_self (n : mynat) : n < succ n := begin [nat_num_game] rw lt_iff_le_and_ne, split, use 1, apply succ_eq_add_one, intro h, exact ne_succ_self n h end lemma succ_le_succ_iff (m n : mynat) : succ m ≤ succ n ↔ m ≤ n := begin [nat_num_game] split, intro h, cases h with c hc, use c, apply succ_inj, rw hc, rw succ_add, refl, intro h, cases h with c hc, use c, rw hc, rw succ_add, refl, end -- remind user about succ_le_succ_iff lemma lt_succ_iff_le (m n : mynat) : m < succ n ↔ m ≤ n := begin [nat_num_game] rw lt_iff_succ_le, exact succ_le_succ_iff m n end -- note: needs add_left_cancel but otherwise is easy. lemma le_of_add_le_add_left (a b c : mynat) : a + b ≤ a + c → b ≤ c := begin [nat_num_game] intro h, cases h with d hd, use d, apply add_left_cancel a, rw hd, ring, end lemma lt_of_add_lt_add_left (a b c : mynat) : a + b < a + c → b < c := begin [nat_num_game] rw lt_iff_succ_le, rw lt_iff_succ_le, intro h, apply le_of_add_le_add_left a, rw add_succ, exact h, end -- I SHOULD TEACH CONGR lemma add_lt_add_right (a b : mynat) : a < b → ∀ c : mynat, a + c < b + c := begin [nat_num_game] intro h, intro c, rw lt_iff_succ_le at h ⊢, cases h with d hd, use d, rw hd, repeat {rw succ_add}, rw add_right_comm, refl, end def bot := 0 -- hide def bot_le := zero_le -- hide instance : canonically_ordered_monoid mynat := by structure_helper instance : ordered_comm_monoid mynat := by structure_helper instance : ordered_cancel_comm_monoid mynat := by structure_helper def succ_lt_succ_iff (a b : mynat) : succ a < succ b ↔ a < b := begin [nat_num_game] rw lt_iff_succ_le, rw lt_iff_succ_le, exact succ_le_succ_iff _ _, end -- multiplication theorem mul_le_mul_of_nonneg_left (a b c : mynat) : a ≤ b → 0 ≤ c → c * a ≤ c * b := begin [nat_num_game] intro hab, intro h0, cases hab with d hd, rw hd, rw mul_add, use c * d, refl end theorem mul_le_mul_of_nonneg_right (a b c : mynat) : a ≤ b → 0 ≤ c → a * c ≤ b * c := begin [nat_num_game] intro hab, intro h0, rw mul_comm, rw mul_comm b, apply mul_le_mul_of_nonneg_left, assumption, assumption end theorem mul_lt_mul_of_pos_left (a b c : mynat) : a < b → 0 < c → c * a < c * b := begin [nat_num_game] intro hab, intro hc, cases c with d, exfalso, exact lt_irrefl 0 hc, clear hc, induction d with e he, rw [succ_mul,zero_mul, zero_add, succ_mul, zero_mul, zero_add], exact hab, rw succ_mul, rw succ_mul (succ e), have h : succ e * a + a < succ e * b + a, exact add_lt_add_right _ _ he _, apply lt_trans _ _ _ h, rw add_comm, rw add_comm _ b, apply add_lt_add_right, assumption end theorem mul_lt_mul_of_pos_right (a b c : mynat) : a < b → 0 < c → a * c < b * c := begin [nat_num_game] intros ha h0, rw mul_comm, rw mul_comm b, apply mul_lt_mul_of_pos_left, assumption, assumption end instance : ordered_semiring mynat := by structure_helper lemma le_mul (a b c d : mynat) : a ≤ b → c ≤ d → a * c ≤ b * d := begin [nat_num_game] intros hab hcd, cases a with t Ht, rw [zero_mul], apply zero_le, have cz : 0 ≤ c, apply zero_le, have bz : 0 ≤ b, apply zero_le, apply mul_le_mul hab hcd cz bz, end lemma pow_le (m n a : mynat) : m ≤ n → m ^ a ≤ n ^ a := begin [nat_num_game] intro h, induction a with t Ht, rw [pow_zero, pow_zero], refl, rw [pow_succ, pow_succ], apply le_mul, assumption, assumption, end lemma strong_induction_aux (P : mynat → Prop) (IH : ∀ m : mynat, (∀ b : mynat, b < m → P b) → P m) (n : mynat) : ∀ c < n, P c := begin [nat_num_game] induction n with d hd, intro c, intro hc, exfalso, revert hc, exact not_lt_zero c, intros e he, rw lt_succ_iff_le at he, apply IH, intros b hb, apply hd, exact lt_of_lt_of_le _ _ _ hb he end -- is elab_as_eliminator right? @[elab_as_eliminator] theorem strong_induction (P : mynat → Prop) (IH : ∀ m : mynat, (∀ d : mynat, d < m → P d) → P m) : ∀ n, P n := begin [nat_num_game] intro n, apply strong_induction_aux P IH (succ n), exact lt_succ_self n end end mynat -- hide
6846b40c831905079b2c67bd9b739cb5cc2e904a
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/bug1.lean
a25db34d03ea29e944eb5671e1ef03796021e5d1
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
654
lean
definition bool [inline] : Type.{1} := Type.{0} definition and [inline] (p q : bool) : bool := ∀ c : bool, (p → q → c) → c infixl `∧`:25 := and variable a : bool -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : a := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ p := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Error theorem and_intro (p q : bool) (H1 : p) (H2 : q) : q ∧ p := fun (c : bool) (H : p -> q -> c), H H1 H2 -- Correct theorem and_intro (p q : bool) (H1 : p) (H2 : q) : p ∧ q := fun (c : bool) (H : p -> q -> c), H H1 H2 check and_intro
9c13b8f26d055a17e2b64c906c80f62e529b996e
3f48345ac9bbaa421714efc9872a0409379bb4ae
/src/set_category/limits/Pullback.lean
bb4fe098785b47451c59899454691e86402be989
[]
no_license
QaisHamarneh/Coalgebra-in-Lean
b4318ee6d83780e5c734eb78fed98b1fe8016f7e
bd0452df98bc64b608e5dfd7babc42c301bb6a46
refs/heads/master
1,663,371,200,241
1,661,004,695,000
1,661,004,695,000
209,798,828
0
0
null
null
null
null
UTF-8
Lean
false
false
5,504
lean
import tactic.tidy import set_category.diagram_lemmas import set_category.category_set import help_functions import set_category.limits.Equalizer import set_category.limits.Product import category_theory.types namespace Pullback open set diagram_lemmas classical function help_functions Equalizer Product category_theory category_set universes v u local notation f ` ⊚ `:80 g:80 := category_struct.comp g f def is_pullback {X : Type v} [category X] {A₁ A₂ B : X} (f : A₁ ⟶ B) (g : A₂ ⟶ B) {P : X} (p₁ : P ⟶ A₁) (p₂ : P ⟶ A₂): Prop := f ⊚ p₁ = g ⊚ p₂ ∧ Π {Q : X} (q₁ : Q ⟶ A₁) (q₂ : Q ⟶ A₂), f ⊚ q₁ = g ⊚ q₂ → ∃! h : Q ⟶ P, q₁ = p₁ ⊚ h ∧ q₂ = p₂ ⊚ h lemma equalizer_product_is_pullback_cat {X : Type u} [category X] {A₁ A₂ B P E : X} (f : A₁ ⟶ B) (g : A₂ ⟶ B) (π₁ : P ⟶ A₁) (π₂ : P ⟶ A₂) (pr : is_product A₁ A₂ π₁ π₂) (e : E ⟶ P) (eqauliz : is_equalizer (f ⊚ π₁) (g ⊚ π₂) e) : is_pullback f g (π₁ ⊚ e) (π₂ ⊚ e) := ⟨ begin tidy end , begin intros Q q₁ q₂ fq₁_gq₂, let p : Q ⟶ P := some (pr Q q₁ q₂), have spec_p : q₁ = π₁ ⊚ p ∧ q₂ = π₂ ⊚ p := (some_spec (pr Q q₁ q₂)).1, have eq_comp : f ⊚ π₁ ⊚ p = g ⊚ π₂ ⊚ p := calc f ⊚ π₁ ⊚ p = f ⊚ (π₁ ⊚ p) : by tidy ... = f ⊚ q₁ : by rw ← spec_p.1 ... = g ⊚ q₂ : fq₁_gq₂ ... = g ⊚ (π₂ ⊚ p) : by rw spec_p.2 ... = g ⊚ π₂ ⊚ p : by tidy, let h : Q ⟶ E := some (eqauliz.2 p eq_comp), have spec_h : p = e ⊚ h := (some_spec (eqauliz.2 p eq_comp)).1, use h, have h0 : q₁ = π₁ ⊚ e ⊚ h ∧ q₂ = π₂ ⊚ e ⊚ h := ⟨ by simp [spec_h , spec_p.1] , by simp [spec_h , spec_p.2] ⟩ , split, exact h0, assume (y : Q ⟶ E) (spec_y : q₁ = π₁ ⊚ e ⊚ y ∧ q₂ = π₂ ⊚ e ⊚ y), have s0 : π₁ ⊚ (e ⊚ h) = π₁ ⊚ (e ⊚ y) := calc π₁ ⊚ (e ⊚ h) = π₁ ⊚ e ⊚ h : by tidy ... = q₁ : eq.symm h0.1 ... = π₁ ⊚ e ⊚ y : spec_y.1 ... = π₁ ⊚ (e ⊚ y) : by tidy, have s1 : π₂ ⊚ (e ⊚ h) = π₂ ⊚ (e ⊚ y) := calc π₂ ⊚ (e ⊚ h) = π₂ ⊚ e ⊚ h : by tidy ... = q₂ : eq.symm h0.2 ... = π₂ ⊚ e ⊚ y : spec_y.2 ... = π₂ ⊚ (e ⊚ y) : by tidy, have eh_ey : e ⊚ h = e ⊚ y := jointly_mono A₁ A₂ P π₁ π₂ pr s0 s1, haveI m_e : mono e := equalizer_is_mono (f ⊚ π₁) (g ⊚ π₂) e eqauliz, exact left_cancel e (eq.symm eh_ey) end ⟩ variables {A₁ A₂ B : Type u} variables (f : A₁ ⟶ B) (g : A₂ ⟶ B) lemma equalizer_product_is_pullback : let P := A₁ × A₂ in let π₁ : P → A₁ := λ ab, ab.1 in let π₂ : P → A₂ := λ ab, ab.2 in let E := equalizer_set (f ∘ π₁) (g ∘ π₂) in let e := E ↪ P in is_pullback f g (π₁ ∘ e) (π₂ ∘ e) := let P := A₁ × A₂ in let π₁ : P → A₁ := λ ab, ab.1 in let π₂ : P → A₂ := λ ab, ab.2 in let E := equalizer_set (f ∘ π₁) (g ∘ π₂) in let e : E → P := E ↪ P in ⟨ begin tidy end , begin intros Q q₁ q₂ fq₁_gq₂, have eq := eqaulizer_set_is_equalizer (f ∘ π₁) (g ∘ π₂), have pr := cartesian_product_is_product A₁ A₂ Q q₁ q₂, let p : Q → P := some pr, have spec_p : q₁ = π₁ ∘ p ∧ q₂ = π₂ ∘ p := (some_spec pr).1, have eq_comp : f ∘ π₁ ∘ p = g ∘ π₂ ∘ p := spec_p.2 ▸ (spec_p.1 ▸ fq₁_gq₂), let h : Q → E := some (eq.2 p eq_comp), have spec_h : p = e ∘ h := (some_spec (eq.2 p eq_comp)).1, use h, split, have h0 : q₁ = π₁ ∘ e ∘ h ∧ q₂ = π₂ ∘ e ∘ h := ⟨ by simp [spec_h , spec_p.1] , by simp [spec_h , spec_p.2] ⟩ , exact h0, assume (y : Q → E) (hy : q₁ = π₁ ∘ e ∘ y ∧ q₂ = π₂ ∘ e ∘ y), have s0 : π₁ ∘ e ∘ h = π₁ ∘ e ∘ y := spec_h ▸ (spec_p.1 ▸ hy.1), have s1 : π₂ ∘ e ∘ h = π₂ ∘ e ∘ y := spec_h ▸ (spec_p.2 ▸ hy.2), have eh_ey : e ∘ h = e ∘ y := jointly_mono A₁ A₂ (A₁ × A₂) prod.fst prod.snd (cartesian_product_is_product A₁ A₂) s0 s1, have elements : ∀ q, y q = h q := assume q, have e0 : (e ∘ y) q = (e ∘ h) q := by rw eh_ey, (inj_inclusion P E) e0, exact funext elements end ⟩ end Pullback
894555fab8097826c418199f6d65c5edc5e91b41
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/MutualDef.lean
12e401d21317df7b8e81f75e037c2f676859f3a4
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
33,362
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Parser.Term import Lean.Meta.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition import Lean.Elab.DeclarationRange namespace Lean.Elab open Lean.Parser.Term /- DefView after elaborating the header. -/ structure DefViewElabHeader where ref : Syntax modifiers : Modifiers kind : DefKind shortDeclName : Name declName : Name levelNames : List Name binderIds : Array Syntax numParams : Nat type : Expr -- including the parameters valueStx : Syntax deriving Inhabited namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | Exception.error ref msg => throw (Exception.error ref m!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" /-- Return `some [b, c]` if the given `views` are representing a declaration of the form ``` constant a b c : Nat ``` -/ private def isMultiConstant? (views : Array DefView) : Option (List Name) := if views.size == 1 && views[0].kind == DefKind.opaque && views[0].binders.getArgs.size > 0 && views[0].binders.getArgs.all (·.getKind == ``Parser.Term.simpleBinder) then some <| (views[0].binders.getArgs.toList.map (fun stx => stx[0].getArgs.toList.map (·.getId))).join else none private def getPendindMVarErrorMessage (views : Array DefView) : String := match isMultiConstant? views with | some ids => let idsStr := ", ".intercalate <| ids.map fun id => s!"`{id}`" let paramsStr := ", ".intercalate <| ids.map fun id => s!"`({id} : _)`" s!"\nrecall that you cannot declare multiple constants in a single declaration. The identifier(s) {idsStr} are being interpreted as parameters {paramsStr}" | none => "\nwhen the resulting type of a declaration is explicitly provided, all holes (e.g., `_`) in the header are resolved before the declaration body is processed" private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let mut headers := #[] for view in views do let newHeader ← withRef view.ref do let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers addDeclarationRanges declName view.ref applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration withDeclName declName <| withAutoBoundImplicit <| withLevelNames levelNames <| elabBindersEx view.binders.getArgs fun xs => do let refForElabFunType := view.value let type ← match view.type? with | some typeStx => let type ← elabType typeStx registerFailedToInferDefTypeInfo type typeStx pure type | none => let hole := mkHole refForElabFunType let type ← elabType hole registerFailedToInferDefTypeInfo type refForElabFunType pure type Term.synthesizeSyntheticMVarsNoPostponing let (binderIds, xs) := xs.unzip let type ← mkForallFVars xs type let type ← mkForallFVars (← read).autoBoundImplicits.toArray type let type ← instantiateMVars type let xs ← addAutoBoundImplicits xs let levelNames ← getLevelNames if view.type?.isSome then let pendingMVarIds ← getMVars type discard <| logUnassignedUsingErrorInfos pendingMVarIds <| getPendindMVarErrorMessage views let newHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, binderIds := binderIds, numParams := xs.size, type := type, valueStx := view.value : DefViewElabHeader } check headers newHeader pure newHeader headers := headers.push newHeader pure headers private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ if header.modifiers.isNonrec then loop (i+1) fvars else withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] private def expandWhereStructInst : Macro | `(Parser.Command.whereStructInst|where $[$decls:letDecl$[;]?]*) => do let letIdDecls ← decls.mapM fun stx => match stx with | `(letDecl|$decl:letPatDecl) => Macro.throwErrorAt stx "patterns are not allowed here" | `(letDecl|$decl:letEqnsDecl) => expandLetEqnsDecl decl | `(letDecl|$decl:letIdDecl) => pure decl | _ => Macro.throwUnsupported let structInstFields ← letIdDecls.mapM fun | stx@`(letIdDecl|$id:ident $[$binders]* $[: $ty?]? := $val) => withRef stx do let mut val := val if let some ty := ty? then val ← `(($val : $ty)) val ← if binders.size > 0 then `(fun $[$binders]* => $val:term) else val `(structInstField|$id:ident := $val) | _ => Macro.throwUnsupported `({ $[$structInstFields,]* }) | _ => Macro.throwUnsupported /- Recall that ``` def declValSimple := leading_parser " :=\n" >> termParser >> optional Term.whereDecls def declValEqns := leading_parser Term.matchAltsWhereDecls def declVal := declValSimple <|> declValEqns <|> Term.whereDecls ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := withRef declVal do if declVal.isOfKind ``Lean.Parser.Command.declValSimple then expandWhereDeclsOpt declVal[2] declVal[1] else if declVal.isOfKind ``Lean.Parser.Command.declValEqns then expandMatchAltsWhereDecls declVal[0] else if declVal.isOfKind ``Lean.Parser.Command.whereStructInst then expandWhereStructInst declVal else if declVal.isMissing then Macro.throwErrorAt declVal "declaration body is missing" else Macro.throwErrorAt declVal "unexpected declaration body" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do let valStx ← liftMacroM $ declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do -- Add new info nodes for new fvars. The server will detect all fvars of a binder by the binder's source location. for i in [0:header.binderIds.size] do -- skip auto-bound prefix in `xs` addTermInfo (isBinder := true) header.binderIds[i] xs[header.numParams - header.binderIds.size + i] let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State MetaM Unit := do headers.forM fun header => collectUsedFVars header.type values.forM collectUsedFVars toLift.forM fun letRecToLift => do collectUsedFVars letRecToLift.type collectUsedFVars letRecToLift.val private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts $ k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← findLocalDecl? fvarId) with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := FVarIdMap FVarIdSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := Id.run <| do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set pure usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State where usedFVarsMap : UsedFVarsMap := {} modified : Bool := false abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : FVarIdSet) : M FVarIdSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then pure s₁ else markModified pure $ s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := FVarIdMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := Id.run <| do let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds pure freeVarMap structure ClosureState where newLocalDecls : Array LocalDecl := #[] localDecls : Array LocalDecl := #[] newLetDecls : Array LocalDecl := #[] exprArgs : Array Expr := #[] private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl arbitrary fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) } pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => trace[Elab.definition.mkClosure] "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => let toProcess ← pushLocalDecl toProcess fvarId userName type bi mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl arbitrary fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls } pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure where ref : Syntax localDecls : Array LocalDecl closed : Expr -- expression used to replace occurrences of the let-rec FVarId toLift : LetRecToLift private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId! let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs assignExprMVar toLift.mvarId c return { ref := toLift.ref localDecls := s.newLocalDecls closed := c toLift := { toLift with val := val, type := type } } private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := FVarIdMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert mainFVars[i].fvarId! (mkAppN (Lean.mkConst mainHeaders[i].declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i] let val ← mkLambdaFVars sectionVars mainVals[i] let type ← mkForallFVars sectionVars header.type return preDefs.push { ref := getDeclarationSelectionRef header.ref kind := header.kind declName := header.declName levelParams := [], -- we set it later modifiers := header.modifiers type := type value := val } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (init := preDefs) fun preDefs c => let type := Closure.mkForall c.localDecls c.toLift.type let val := Closure.mkLambda c.localDecls c.toLift.val preDefs.push { ref := c.ref kind := kind declName := c.toLift.declName levelParams := [] -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs } type := type value := val } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable recKind := if mainHeaders.any fun h => h.modifiers.isPartial then RecKind.partial else RecKind.default isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mctx ← getMCtx let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM (instantiateMVars ·) let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] /-- Eagerly convert universe metavariables occurring in theorem headers to universe parameters. -/ private def levelMVarToParamHeaders (views : Array DefView) (headers : Array DefViewElabHeader) : TermElabM (Array DefViewElabHeader) := do let rec process : StateRefT Nat TermElabM (Array DefViewElabHeader) := do let mut newHeaders := #[] for view in views, header in headers do if view.kind.isTheorem then newHeaders := newHeaders.push { header with type := (← levelMVarToParam' header.type) } else newHeaders := newHeaders.push header return newHeaders let newHeaders ← process.run' 1 newHeaders.mapM fun header => return { header with type := (← instantiateMVars header.type) } /-- Result for `mkInst?` -/ structure MkInstResult where instVal : Expr instType : Expr outParams : Array Expr := #[] /-- Construct an instance for `className out₁ ... outₙ type`. The method support classes with a prefix of `outParam`s (e.g. `MonadReader`). -/ private partial def mkInst? (className : Name) (type : Expr) : MetaM (Option MkInstResult) := do let rec go? (instType instTypeType : Expr) (outParams : Array Expr) : MetaM (Option MkInstResult) := do let instTypeType ← whnfD instTypeType unless instTypeType.isForall do return none let d := instTypeType.bindingDomain! if isOutParam d then let mvar ← mkFreshExprMVar d go? (mkApp instType mvar) (instTypeType.bindingBody!.instantiate1 mvar) (outParams.push mvar) else unless (← isDefEqGuarded (← inferType type) d) do return none let instType ← instantiateMVars (mkApp instType type) let instVal ← synthInstance instType return some { instVal, instType, outParams } let instType ← mkConstWithFreshMVarLevels className go? instType (← inferType instType) #[] def processDefDeriving (className : Name) (declName : Name) : TermElabM Bool := do try let ConstantInfo.defnInfo info ← getConstInfo declName | return false let some result ← mkInst? className info.value | return false let instTypeNew := mkApp result.instType.appFn! (Lean.mkConst declName (info.levelParams.map mkLevelParam)) Meta.check instTypeNew let instName ← liftMacroM <| mkUnusedBaseName (declName.appendBefore "inst" |>.appendAfter className.getString!) addAndCompile <| Declaration.defnDecl { name := instName levelParams := info.levelParams type := (← instantiateMVars instTypeNew) value := (← instantiateMVars result.instVal) hints := info.hints safety := info.safety } addInstance instName AttributeKind.global (eval_prio default) return true catch ex => return false def elabMutualDef (vars : Array Expr) (views : Array DefView) (hints : TerminationHints) : TermElabM Unit := if isExample views then withoutModifyingEnv go else go where go := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let headers ← levelMVarToParamHeaders views headers let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing let values ← values.mapM (instantiateMVars ·) let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift for preDef in preDefs do trace[Elab.definition] "{preDef.declName} : {preDef.type} :=\n{preDef.value}" let preDefs ← levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames addPreDefinitions preDefs hints processDeriving headers processDeriving (headers : Array DefViewElabHeader) := do for header in headers, view in views do if let some classNamesStx := view.deriving? then for classNameStx in classNamesStx do let className ← resolveGlobalConstNoOverload classNameStx withRef classNameStx do unless (← processDefDeriving className header.declName) do throwError "failed to synthesize instance '{className}' for '{header.declName}'" end Term namespace Command def elabMutualDef (ds : Array Syntax) (hints : TerminationHints) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] if ds.size > 1 && modifiers.isNonrec then throwErrorAt d "invalid use of 'nonrec' modifier in 'mutual' block" mkDefView modifiers d[1] runTermElabM none fun vars => Term.elabMutualDef vars views hints end Command end Lean.Elab
36f0c8cc29175b80f578578252e609cd112f476d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/diamond9.lean
b7cb4b912f505dcfdda566aa6ed85917543504b8
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
395
lean
class Zero (A : Type u) where zero : A instance {A} [Zero A] : OfNat A (nat_lit 0) := ⟨Zero.zero⟩ class AddGroup (A : Type u) extends Zero A where gsmul : Int → A → A gsmul_zero' : ∀ a, gsmul 0 a = 0 class Ring (R : Type u) extends Zero R, AddGroup R #print Ring.mk #check { zero := 0 gsmul := fun x n => x.toNat * n gsmul_zero' := fun a => Nat.zero_mul _ : Ring Nat }
9030ebd7f725ccfd9b714f8ac8be73ea541e8468
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/category/Group/colimits.lean
362f9ade3e506a3a056083874f0b11fadf7de8b3
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,661
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Group.preadditive import group_theory.quotient_group import category_theory.limits.shapes.kernels import category_theory.concrete_category.elementwise /-! # The category of additive commutative groups has all colimits. This file uses a "pre-automated" approach, just as for `Mon/colimits.lean`. It is a very uniform approach, that conceivably could be synthesised directly by a tactic that analyses the shape of `add_comm_group` and `monoid_hom`. TODO: In fact, in `AddCommGroup` there is a much nicer model of colimits as quotients of finitely supported functions, and we really should implement this as well (or instead). -/ universes u v open category_theory open category_theory.limits -- [ROBOT VOICE]: -- You should pretend for now that this file was automatically generated. -- It follows the same template as colimits in Mon. namespace AddCommGroup.colimits /-! We build the colimit of a diagram in `AddCommGroup` by constructing the free group on the disjoint union of all the abelian groups in the diagram, then taking the quotient by the abelian group laws within each abelian group, and the identifications given by the morphisms in the diagram. -/ variables {J : Type v} [small_category J] (F : J ⥤ AddCommGroup.{v}) /-- An inductive type representing all group expressions (without relations) on a collection of types indexed by the objects of `J`. -/ inductive prequotient -- There's always `of` | of : Π (j : J) (x : F.obj j), prequotient -- Then one generator for each operation | zero : prequotient | neg : prequotient → prequotient | add : prequotient → prequotient → prequotient instance : inhabited (prequotient F) := ⟨prequotient.zero⟩ open prequotient /-- The relation on `prequotient` saying when two expressions are equal because of the abelian group laws, or because one element is mapped to another by a morphism in the diagram. -/ inductive relation : prequotient F → prequotient F → Prop -- Make it an equivalence relation: | refl : Π (x), relation x x | symm : Π (x y) (h : relation x y), relation y x | trans : Π (x y z) (h : relation x y) (k : relation y z), relation x z -- There's always a `map` relation | map : Π (j j' : J) (f : j ⟶ j') (x : F.obj j), relation (of j' (F.map f x)) (of j x) -- Then one relation per operation, describing the interaction with `of` | zero : Π (j), relation (of j 0) zero | neg : Π (j) (x : F.obj j), relation (of j (-x)) (neg (of j x)) | add : Π (j) (x y : F.obj j), relation (of j (x + y)) (add (of j x) (of j y)) -- Then one relation per argument of each operation | neg_1 : Π (x x') (r : relation x x'), relation (neg x) (neg x') | add_1 : Π (x x' y) (r : relation x x'), relation (add x y) (add x' y) | add_2 : Π (x y y') (r : relation y y'), relation (add x y) (add x y') -- And one relation per axiom | zero_add : Π (x), relation (add zero x) x | add_zero : Π (x), relation (add x zero) x | add_left_neg : Π (x), relation (add (neg x) x) zero | add_comm : Π (x y), relation (add x y) (add y x) | add_assoc : Π (x y z), relation (add (add x y) z) (add x (add y z)) /-- The setoid corresponding to group expressions modulo abelian group relations and identifications. -/ def colimit_setoid : setoid (prequotient F) := { r := relation F, iseqv := ⟨relation.refl, relation.symm, relation.trans⟩ } attribute [instance] colimit_setoid /-- The underlying type of the colimit of a diagram in `AddCommGroup`. -/ @[derive inhabited] def colimit_type : Type v := quotient (colimit_setoid F) instance : add_comm_group (colimit_type F) := { zero := begin exact quot.mk _ zero end, neg := begin fapply @quot.lift, { intro x, exact quot.mk _ (neg x) }, { intros x x' r, apply quot.sound, exact relation.neg_1 _ _ r }, end, add := begin fapply @quot.lift _ _ ((colimit_type F) → (colimit_type F)), { intro x, fapply @quot.lift, { intro y, exact quot.mk _ (add x y) }, { intros y y' r, apply quot.sound, exact relation.add_2 _ _ _ r } }, { intros x x' r, funext y, induction y, dsimp, apply quot.sound, { exact relation.add_1 _ _ _ r }, { refl } }, end, zero_add := λ x, begin induction x, dsimp, apply quot.sound, apply relation.zero_add, refl, end, add_zero := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_zero, refl, end, add_left_neg := λ x, begin induction x, dsimp, apply quot.sound, apply relation.add_left_neg, refl, end, add_comm := λ x y, begin induction x, induction y, dsimp, apply quot.sound, apply relation.add_comm, refl, refl, end, add_assoc := λ x y z, begin induction x, induction y, induction z, dsimp, apply quot.sound, apply relation.add_assoc, refl, refl, refl, end, } @[simp] lemma quot_zero : quot.mk setoid.r zero = (0 : colimit_type F) := rfl @[simp] lemma quot_neg (x) : quot.mk setoid.r (neg x) = (-(quot.mk setoid.r x) : colimit_type F) := rfl @[simp] lemma quot_add (x y) : quot.mk setoid.r (add x y) = ((quot.mk setoid.r x) + (quot.mk setoid.r y) : colimit_type F) := rfl /-- The bundled abelian group giving the colimit of a diagram. -/ def colimit : AddCommGroup := AddCommGroup.of (colimit_type F) /-- The function from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_fun (j : J) (x : F.obj j) : colimit_type F := quot.mk _ (of j x) /-- The group homomorphism from a given abelian group in the diagram to the colimit abelian group. -/ def cocone_morphism (j : J) : F.obj j ⟶ colimit F := { to_fun := cocone_fun F j, map_zero' := by apply quot.sound; apply relation.zero, map_add' := by intros; apply quot.sound; apply relation.add } @[simp] lemma cocone_naturality {j j' : J} (f : j ⟶ j') : F.map f ≫ (cocone_morphism F j') = cocone_morphism F j := begin ext, apply quot.sound, apply relation.map, end @[simp] lemma cocone_naturality_components (j j' : J) (f : j ⟶ j') (x : F.obj j): (cocone_morphism F j') (F.map f x) = (cocone_morphism F j) x := by { rw ←cocone_naturality F f, refl } /-- The cocone over the proposed colimit abelian group. -/ def colimit_cocone : cocone F := { X := colimit F, ι := { app := cocone_morphism F } }. /-- The function from the free abelian group on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift (s : cocone F) : prequotient F → s.X | (of j x) := (s.ι.app j) x | zero := 0 | (neg x) := -(desc_fun_lift x) | (add x y) := desc_fun_lift x + desc_fun_lift y /-- The function from the colimit abelian group to the cone point of any other cocone. -/ def desc_fun (s : cocone F) : colimit_type F → s.X := begin fapply quot.lift, { exact desc_fun_lift F s }, { intros x y r, induction r; try { dsimp }, -- refl { refl }, -- symm { exact r_ih.symm }, -- trans { exact eq.trans r_ih_h r_ih_k }, -- map { simp, }, -- zero { simp, }, -- neg { simp, }, -- add { simp, }, -- neg_1 { rw r_ih, }, -- add_1 { rw r_ih, }, -- add_2 { rw r_ih, }, -- zero_add { rw zero_add, }, -- add_zero { rw add_zero, }, -- add_left_neg { rw add_left_neg, }, -- add_comm { rw add_comm, }, -- add_assoc { rw add_assoc, } } end /-- The group homomorphism from the colimit abelian group to the cone point of any other cocone. -/ def desc_morphism (s : cocone F) : colimit F ⟶ s.X := { to_fun := desc_fun F s, map_zero' := rfl, map_add' := λ x y, by { induction x; induction y; refl }, } /-- Evidence that the proposed colimit is the colimit. -/ def colimit_cocone_is_colimit : is_colimit (colimit_cocone F) := { desc := λ s, desc_morphism F s, uniq' := λ s m w, begin ext, induction x, induction x, { have w' := congr_fun (congr_arg (λ f : F.obj x_j ⟶ s.X, (f : F.obj x_j → s.X)) (w x_j)) x_x, erw w', refl, }, { simp *, }, { simp *, }, { simp *, }, refl end }. instance has_colimits_AddCommGroup : has_colimits AddCommGroup := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, has_colimit.mk { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } end AddCommGroup.colimits namespace AddCommGroup open quotient_add_group /-- The categorical cokernel of a morphism in `AddCommGroup` agrees with the usual group-theoretical quotient. -/ noncomputable def cokernel_iso_quotient {G H : AddCommGroup.{u}} (f : G ⟶ H) : cokernel f ≅ AddCommGroup.of (H ⧸ (add_monoid_hom.range f)) := { hom := cokernel.desc f (mk' _) (by { ext, apply quotient.sound, apply left_rel_apply.mpr, fsplit, exact -x, simp only [add_zero, add_monoid_hom.map_neg], }), inv := quotient_add_group.lift _ (cokernel.π f) (by { intros x H_1, cases H_1, induction H_1_h, simp only [cokernel.condition_apply, zero_apply]}), -- obviously can take care of the next goals, but it is really slow hom_inv_id' := begin ext1, simp only [coequalizer_as_cokernel, category.comp_id, cokernel.π_desc_assoc], ext1, refl, end, inv_hom_id' := begin ext x : 2, simp only [add_monoid_hom.coe_comp, function.comp_app, comp_apply, lift_mk, cokernel.π_desc_apply, mk'_apply, id_apply], end, } end AddCommGroup
796ee27b88e21490f52b2cdc72b97651c7579f21
d6124c8dbe5661dcc5b8c9da0a56fbf1f0480ad6
/Papyrus/IR/BasicBlockRef.lean
41217ac55850b3b08467c6a810b21eef3fb20531
[ "Apache-2.0" ]
permissive
xubaiw/lean4-papyrus
c3fbbf8ba162eb5f210155ae4e20feb2d32c8182
02e82973a5badda26fc0f9fd15b3d37e2eb309e0
refs/heads/master
1,691,425,756,824
1,632,122,825,000
1,632,123,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,214
lean
import Papyrus.Context import Papyrus.IR.ValueRef import Papyrus.IR.InstructionRef namespace Papyrus /-- A reference to an external LLVM [BasicBlock](https://llvm.org/doxygen/classllvm_1_1BasicBlock.html). -/ structure BasicBlockRef extends ValueRef where is_basic_block : toValueRef.valueKind = ValueKind.basicBlock instance : Coe BasicBlockRef ValueRef := ⟨(·.toValueRef)⟩ namespace BasicBlockRef /-- Cast a general `ValueRef` to a `BasicBlockRef` given proof it is one. -/ def cast (val : ValueRef) (h : val.valueKind = ValueKind.basicBlock) : BasicBlockRef := {toValueRef := val, is_basic_block := h} /-- Create a new unlinked basic block with given label/name (or none if empty). -/ @[extern "papyrus_basic_block_create"] constant create (name : @& String := "") : LlvmM BasicBlockRef /-- Get the array of references to the instructions of this basic block. -/ @[extern "papyrus_basic_block_get_instructions"] constant getInstructions (self : @& BasicBlockRef) : IO (Array InstructionRef) /-- Add an instruction to the end of the basic block. -/ @[extern "papyrus_basic_block_append_instruction"] constant appendInstruction (inst : @& InstructionRef) (self : @& BasicBlockRef) : IO PUnit
865a19cb2cc3afc43d7ba16801d6cfe9a4226419
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/ring/basic.lean
7d531e6a5b95388869e8f3be4e0af57836679d81
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,005
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, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ /-- A semiring is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero` instead of `monoid` and `mul_zero_class`. -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } /-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/ def even (a : α) : Prop := ∃ k, a = 2*k lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : (mul_right r : R → R) a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`. The `simp`-normal form is `(f : R →* S)`. -/ add_decl_doc ring_hom.to_monoid_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`. The `simp`-normal form is `(f : R →+ S)`. -/ add_decl_doc ring_hom.to_add_monoid_hom namespace ring_hom section coe variables {rα : semiring α} {rβ : semiring β} include rα rβ instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl @[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ := rfl instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl @[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ := rfl end coe variables [rα : semiring α] [rβ : semiring β] section include rα rβ variables (f : α →+* β) {x y : α} {rα rβ} theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →+* β, h x) h theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, ext (λ x, add_monoid_hom.congr_fun h x) theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, ext (λ x, monoid_hom.congr_fun h x) /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- Ring homomorphisms preserve `bit0`. -/ @[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _ /-- Ring homomorphisms preserve `bit1`. -/ @[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) := by simp [bit1] /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map (f.to_monoid_hom) end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα instance : inhabited (α →+* α) := ⟨id α⟩ @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom /-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). -/ @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} @[priority 100] -- see Note [lower instance priority] instance comm_semiring.comm_monoid_with_zero : comm_monoid_with_zero α := { .. (‹_› : comm_semiring α) } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [add_mul, mul_add, mul_comm, add_assoc] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ /-- A ring is a type with the following structures: additive commutative group (`add_comm_group`), multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a `semiring` with a negation operation making it an additive group. -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ @[priority 200] instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp [sub_eq_add_neg] alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp [sub_eq_add_neg] alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom /-- A commutative ring is a `ring` with commutative multiplication. -/ @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α @[priority 100] -- see Note [lower instance priority] instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self, mul_one] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by { convert h, simp }))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] @[priority 100] -- see Note [lower instance priority] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ /-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative multiplication. -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} @[priority 100] -- see Note [lower instance priority] instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } end integral_domain namespace ring variables [ring R] open_locale classical /-- Introduce a function `inverse` on a ring `R`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : R → R := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units R) : R) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ @[simp] lemma inverse_unit (a : units R) : inverse (a : R) = (a⁻¹ : units R) := begin simp [is_unit_unit, inverse], exact units.inv_unique (classical.some_spec (is_unit_unit a)), end /-- By definition, if `x` is not invertible then `inverse x = 0`. -/ @[simp] lemma inverse_non_unit (x : R) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
0869c382dc767295b83610433f226f8a98d1be2e
e39f04f6ff425fe3b3f5e26a8998b817d1dba80f
/meta/rb_map.lean
e09a59b1760d3e2f01e8efb13d261e2745fef492
[ "Apache-2.0" ]
permissive
kristychoi/mathlib
c504b5e8f84e272ea1d8966693c42de7523bf0ec
257fd84fe98927ff4a5ffe044f68c4e9d235cc75
refs/heads/master
1,586,520,722,896
1,544,030,145,000
1,544,031,933,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,105
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis Additional operations on native rb_maps and rb_sets. -/ import data.option namespace native namespace rb_set meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) end rb_set namespace rb_map meta def find_def {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)] (x : β) (m : rb_map α β) (k : α) := (m.find k).get_or_else x meta def insert_cons {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)] (k : α) (x : β) (m : rb_map α (list β)) : rb_map α (list β) := m.insert k (x :: m.find_def [] k) meta def ifind {α β} [inhabited β] (m : rb_map α β) (a : α) : β := (m.find a).iget meta def zfind {α β} [has_zero β] (m : rb_map α β) (a : α) : β := (m.find a).get_or_else 0 meta def add {α β} [has_add β] [has_zero β] [decidable_eq β] (m1 m2 : rb_map α β) : rb_map α β := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) meta def scale {α β} [has_lt α] [decidable_rel ((<) : α → α → Prop)] [has_mul β] (b : β) (m : rb_map α β) : rb_map α β := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map end native
7434343892967531faa1cd455d04577289ffe4ec
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/mynat/hcf.lean
9c670ca1b528ffa22ba9c860e5b991beaaa0ff6a
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
8,264
lean
import ..myset.basic import .prime import ..myint.dvd import ..logic /- Noncomputable HCF In this file we make no attempt to remain computable or minimise the axioms used. We construct the HCF of a and b as the smallest positive integer h for which there exist integers x and y such that a * x + b * y = h, and then go on to prove some properties of this. -/ namespace hidden open myint namespace mynat /-- Non-zero linear combinations of naturals -/ def lin_combs (a b : mynat) : myset mynat := λ c, c ≠ 0 ∧ ∃ x y : myint, ↑a * x + ↑b * y = ↑c theorem lin_combs_comm (a b : mynat) : lin_combs a b = lin_combs b a := begin apply funext, intro c, apply propext, split, all_goals { assume h, unfold lin_combs at *, split, from h.left, cases h.right with x hx, cases hx with y hxy, existsi y, existsi x, rwa myint.add_comm, }, end theorem lin_combs_nemp {a b : mynat} : a ≠ 0 ∨ b ≠ 0 → ¬myset.empty (lin_combs a b) := begin assume hab, rw ←myset.exists_iff_nempty, cases hab with ha hb, { existsi a, split, assumption, existsi (1 : myint), existsi (0 : myint), rw [myint.mul_one, myint.mul_zero, myint.add_zero], }, { existsi b, split, assumption, existsi (0 : myint), existsi (1 : myint), rw [myint.mul_one, myint.mul_zero, myint.zero_add], }, end -- 0 if both 0, sadly this makes it an if :( -- Inherits noncomputablility from `min` /-- Given two integers, (noncomputably) get their hcf, and if both are zero, return zero. -/ noncomputable def hcf (a b : mynat) : mynat := if h : a ≠ 0 ∨ b ≠ 0 then min (lin_combs a b) (lin_combs_nemp h) else 0 variables m n k : mynat theorem hcf_comm : hcf m n = hcf n m := begin by_cases m ≠ 0 ∨ n ≠ 0, unfold hcf, rw [dif_pos h, dif_pos (or.symm h)], apply min_rw, from lin_combs_comm m n, unfold hcf, have : ¬(n ≠ 0 ∨ m ≠ 0), assume hnm, from h (or.symm hnm), rw [dif_neg h, dif_neg this], end private lemma common_factor_dvd_lin_comb (k m n a : mynat): k ∣ m → k ∣ n → a ∈ lin_combs m n → k ∣ a := begin assume hkm hkn h, cases h with ha h, cases h with x hx, cases hx with y hxy, have : ↑k ∣ ↑m * x + ↑n * y, apply myint.dvd_sum, apply myint.dvd_mul, apply myint.coe_coe_dvd.mp, assumption, apply myint.dvd_mul, apply myint.coe_coe_dvd.mp, assumption, apply myint.coe_coe_dvd.mpr, rwa ←hxy, end theorem hcf_is_lin_comb {m n : mynat} (h : m ≠ 0 ∨ n ≠ 0): hcf m n ∈ lin_combs m n := begin unfold hcf, rw dif_pos h, from min_property _, end theorem hcf_min_if_one_nzero {m n : mynat} (h : m ≠ 0 ∨ n ≠ 0) : hcf m n = min (lin_combs m n) (lin_combs_nemp h) := begin unfold hcf, rw dif_pos h, end theorem common_factor_dvd_hcf {k m n : mynat} : k ∣ m → k ∣ n → k ∣ hcf m n := begin by_cases m ≠ 0 ∨ n ≠ 0; assume hkm hkn, apply common_factor_dvd_lin_comb k m n (hcf m n), any_goals { assumption, }, from hcf_is_lin_comb h, have : hcf m n = 0, unfold hcf, rw dif_neg h, rw this, from dvd_zero, end theorem hcf_zero_iff_both_zero : hcf m n = 0 ↔ ¬(m ≠ 0 ∨ n ≠ 0) := begin split; assume h, { assume hmn0, unfold hcf at h, rw dif_pos hmn0 at h, have := min_property (lin_combs_nemp hmn0), rw myset.mem_def at this, cases this with h0 hright, contradiction, }, { unfold hcf, rw dif_neg h, }, end -- NOTE: This example breaks if you open classical. Why? -- (see below) example {m n : mynat} (h : m ≠ 0 ∨ n ≠ 0) : hcf m n = min (lin_combs m n) (lin_combs_nemp h) := begin unfold hcf, rw dif_pos h, end -- Let's open classical and make all propositions decidable open classical -- Proving dvd decidable almost certainly requires well-founded recursion local attribute [instance] prop_decidable -- Brok example {m n : mynat} (h : m ≠ 0 ∨ n ≠ 0) : hcf m n = min (lin_combs m n) (lin_combs_nemp h) := begin unfold hcf, -- rw dif_pos h, sorry, end -- A ridiculous proof, at this point might as well just be constructive -- We need dvd decidable -- TODO: Move somewhere, I guess /-- Off-brand division algorithm -/ theorem exists_remainder {k n : mynat} : k ≠ 0 → ¬k ∣ n → ∃ m r, 0 ≠ r ∧ r < k ∧ k ∣ m ∧ n = m + r := begin assume hk, induction n with n hn, assume h, have : k ∣ zero, rw zz, from dvd_zero, contradiction, assume hsucc, by_cases hkn: k ∣ n, { existsi n, existsi (1 : mynat), split, apply mynat.no_confusion, split, assume hk1, cases le_one hk1, contradiction, have : k ∣ (succ n), rw h, from one_dvd, contradiction, split, assumption, refl, }, { cases hn hkn with m hm, cases hm with r hmr, cases hmr with h0r hmr, cases hmr with hrk hmr, cases hmr with hkm hnmr, existsi m, existsi (succ r), split, apply mynat.no_confusion, split, rw [lt_iff_succ_le, le_iff_lt_or_eq] at hrk, cases hrk, assumption, have := congr_arg succ hnmr, cases hkm with a ha, rw [←add_succ, hrk, ha] at this, conv at this { to_rhs, congr, skip, rw ←mynat.one_mul k, skip, }, rw ←add_mul at this, have hcontra : k ∣ (succ n), existsi (a + 1), assumption, contradiction, split, assumption, rwa [add_succ, hnmr], }, end theorem hcf_dvd_left (h : m ≠ 0 ∨ n ≠ 0): hcf m n ∣ m := begin by_contradiction hdvd, have hprop := min_property (lin_combs_nemp h), rw ←hcf_min_if_one_nzero h at hprop, cases hprop with h0 hprop, cases hprop with x hx, cases hx with y hxy, -- Again, unfold enormous string of ∧. -- Mathlib has `rcases` tactic which makes this pleasant. cases exists_remainder h0 hdvd with a ha, cases ha with r har, cases har with h0r har, cases har with hrhcf har, cases har with hhcfdvd hmxr, cases hhcfdvd with q hq, have hmul := congr_arg (λ x, ↑q * x) hxy, dsimp only [] at hmul, rw [coe_coe_mul, ←hq] at hmul, have hcoe := congr_arg (λ x, (↑x : myint)) hmxr, dsimp only [] at hcoe, rw [←coe_coe_add, ←myint.add_cancel (-↑r), myint.add_assoc, self_neg_add, myint.add_zero] at hcoe, rw [←hcoe, ←myint.add_cancel (↑r), myint.add_assoc, neg_self_add, myint.add_zero, myint.add_comm, ←myint.add_cancel (-(↑q * (↑m * x + ↑n * y))), myint.add_assoc, self_neg_add, myint.add_zero, ←mul_neg_with, myint.mul_add, ←myint.mul_one (↑m)] at hmul, have : ↑m * 1 + (-↑q * (↑m * 1 * x) + -↑q * (↑n * y)) = ↑m * 1 + ↑m * (1 * -↑q * x) + ↑n * (-↑q * y), ac_refl, rw [this, ←myint.mul_add] at hmul, clear this, suffices : r ∈ lin_combs m n, have hle := min_le (lin_combs_nemp h) this, rw ←hcf_min_if_one_nzero h at hle, contradiction, split, from h0r.symm, existsi (1 + 1 * -↑q * x), existsi (-↑q * y), symmetry, assumption, end theorem hcf_dvd_right (h : m ≠ 0 ∨ n ≠ 0): hcf m n ∣ n := by rw hcf_comm; from hcf_dvd_left n m (or.symm h) theorem bezouts_lemma {m n k : mynat} (h : m ≠ 0 ∨ n ≠ 0) : (∃ x y : myint, ↑m * x + ↑n * y = k) ↔ hcf m n ∣ k := begin split; assume h₁, { cases h₁ with x hx, cases hx with y hxy, cases hcf_dvd_left _ _ h with a ha, cases hcf_dvd_right _ _ h with b hb, apply myint.coe_coe_dvd.mpr, existsi (↑a * x + ↑b * y), rw [myint.mul_comm, myint.mul_add, ←myint.mul_assoc, ←myint.mul_assoc, coe_coe_mul, coe_coe_mul, mul_comm, mul_comm _ b, ←ha, ←hb], symmetry, assumption, }, { have hprop := min_property (lin_combs_nemp h), rw ←hcf_min_if_one_nzero h at hprop, cases hprop with h0 hprop, cases hprop with x hx, cases hx with y hxy, cases h₁ with a ha, have := congr_arg (λ x, ↑a * x) hxy, dsimp only [] at this, rw [myint.mul_add, coe_coe_mul, ←ha] at this, existsi (↑a * x), existsi (↑a * y), rw ←this, ac_refl, }, end end mynat end hidden
aa7d9e8f4cf1968b32d661ba09dac0a069b81a57
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/meta/interaction_monad.lean
e2f53e8e39233603f1ba51b3b1394758dc838866
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,313
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import init.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.to_string init.data.string.basic universes u v meta inductive interaction_monad.result (state : Type) (α : Type u) | success : α → state → interaction_monad.result | exception {} : option (unit → format) → option pos → state → interaction_monad.result open interaction_monad.result section variables {state : Type} {α : Type u} variables [has_to_string α] meta def interaction_monad.result_to_string : result state α → string | (success a s) := to_string a | (exception (some t) ref s) := "Exception: " ++ to_string (t ()) | (exception none ref s) := "[silent exception]" meta instance interaction_monad.result_has_string : has_to_string (result state α) := ⟨interaction_monad.result_to_string⟩ end @[reducible] meta def interaction_monad (state : Type) (α : Type u) := state → result state α section parameter {state : Type} variables {α : Type u} {β : Type v} local notation `m` := interaction_monad state @[inline] meta def interaction_monad_fmap (f : α → β) (t : m α) : m β := λ s, interaction_monad.result.cases_on (t s) (λ a s', success (f a) s') (λ e s', exception e s') @[inline] meta def interaction_monad_bind (t₁ : m α) (t₂ : α → m β) : m β := λ s, interaction_monad.result.cases_on (t₁ s) (λ a s', t₂ a s') (λ e s', exception e s') @[inline] meta def interaction_monad_return (a : α) : m α := λ s, success a s meta def interaction_monad_orelse {α : Type u} (t₁ t₂ : m α) : m α := λ s, interaction_monad.result.cases_on (t₁ s) success (λ e₁ ref₁ s', interaction_monad.result.cases_on (t₂ s) success exception) @[inline] meta def interaction_monad_seq (t₁ : m α) (t₂ : m β) : m β := interaction_monad_bind t₁ (λ a, t₂) meta instance interaction_monad.monad : monad m := {map := @interaction_monad_fmap, ret := @interaction_monad_return, bind := @interaction_monad_bind} meta def interaction_monad.mk_exception {α : Type u} {β : Type v} [has_to_format β] (msg : β) (ref : option expr) (s : state) : result state α := exception (some (λ _, to_fmt msg)) none s meta def interaction_monad.fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : m α := λ s, interaction_monad.mk_exception msg none s meta def interaction_monad.silent_fail {α : Type u} : m α := λ s, exception none none s meta def interaction_monad.failed {α : Type u} : m α := interaction_monad.fail "failed" meta instance interaction_monad.monad_fail : monad_fail m := { interaction_monad.monad with fail := λ α s, interaction_monad.fail (to_fmt s) } -- TODO: unify `parser` and `tactic` behavior? -- meta instance interaction_monad.alternative : alternative m := -- ⟨@interaction_monad_fmap, (λ α a s, success a s), (@fapp _ _), @interaction_monad.failed, @interaction_monad_orelse⟩ end
6584aa93e60cb00d62f57c5a502d2be3bd5a7ff4
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.7.lean
125d60211d1d06cf247888e243a7b906bbcb16b3
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
666
lean
import standard namespace hide inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A definition Prop.is_inhabited [instance] : inhabited Prop := inhabited.mk true definition bool.is_inhabited [instance] : inhabited bool := inhabited.mk bool.tt definition nat.is_inhabited [instance] : inhabited nat := inhabited.mk nat.zero definition unit.is_inhabited [instance] : inhabited unit := inhabited.mk unit.star definition default (A : Type) [H : inhabited A] : A := inhabited.rec (λ a, a) H -- BEGIN eval default Prop -- true eval default nat -- nat.zero eval default bool -- bool.tt eval default unit -- unit.star -- END end hide
bfd887cae69b47b8a9c736e048cf08af462fc812
e151e9053bfd6d71740066474fc500a087837323
/src/hott/types/sum.lean
3315008c75757bc834e8d261a3fba2154e640339
[ "Apache-2.0" ]
permissive
daniel-carranza/hott3
15bac2d90589dbb952ef15e74b2837722491963d
913811e8a1371d3a5751d7d32ff9dec8aa6815d9
refs/heads/master
1,610,091,349,670
1,596,222,336,000
1,596,222,336,000
241,957,822
0
0
Apache-2.0
1,582,222,839,000
1,582,222,838,000
null
UTF-8
Lean
false
false
19,954
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer Theorems about sums/coproducts/disjoint unions -/ import .pi .equiv hott.cubical.square open /-hott.lift-/ hott hott.eq hott.is_equiv hott.equiv hott.prod /-prod.ops-/ hott.is_trunc hott.sigma hott.bool hott_theory namespace sum universe variables u v u' v' variables {A : Type.{u}} {B : Type.{v}} (z z' : A ⊎ B) {P : A → Type.{u'}} {Q : A → Type.{v'}} @[hott] protected def eta : @sum.rec A B (λ z, A ⊎ B) inl inr z = z := by hinduction z; reflexivity @[hott] protected def code : A ⊎ B → A ⊎ B → Type (max u v) := begin intros x y, induction x with a b; induction y with a' b', exact ulift.{(max u v) u} (a = a'), exact ulift empty, exact ulift empty, exact @ulift.{(max u v) v} (b = b'), end @[hott] protected def decode : Π (z z' : A ⊎ B), sum.code z z' → z = z' := begin intros z z', induction z with a b; induction z' with a' b', exact λ c, ap inl (ulift.down c), exact λ c, empty.elim (ulift.down c), exact λ c, empty.elim (ulift.down c), exact λ c, ap inr (ulift.down c) end @[hott] protected def mem_cases : (Σ a, z = inl a) ⊎ (Σ b, z = inr b) := begin induction z with a b, exact inl ⟨a, idp⟩, exact inr ⟨b, idp⟩ end @[hott] protected def eqrec {A B : Type _} {C : A ⊎ B → Type _} (x : A ⊎ B) (cl : Π a, x = inl a → C (inl a)) (cr : Π b, x = inr b → C (inr b)) : C x := begin induction x with a b, exact cl a idp, exact cr b idp end variables {z z'} @[hott] protected def encode (p : z = z') : sum.code z z' := by induction p; induction z; exact ulift.up idp variables (z z') @[hott] def sum_eq_equiv : (z = z') ≃ sum.code z z' := begin fapply equiv.MK, apply sum.encode, apply sum.decode, { induction z with a b; induction z' with a' b'; intro b; induction b with b; induction b; reflexivity }, { intro p, induction p, induction z; refl } end section variables {a a' : A} {b b' : B} @[hott] def eq_of_inl_eq_inl (p : inl a = (inl a' : A ⊎ B)) : a = a' := ulift.down (sum.encode p) @[hott] def eq_of_inr_eq_inr (p : inr b = (inr b' : A ⊎ B)) : b = b' := ulift.down (sum.encode p) @[hott] def empty_of_inl_eq_inr (p : inl a = inr b) : empty := ulift.down (sum.encode p) @[hott] def empty_of_inr_eq_inl (p : inr b = inl a) : empty := ulift.down (sum.encode p) /- Transport -/ @[hott] def sum_transport (p : a = a') (z : P a ⊎ Q a) : p ▸ z = sum.rec (λa, inl (p ▸ a)) (λb, inr (p ▸ b)) z := by induction p; induction z; reflexivity /- Pathovers -/ @[hott] def etao (p : a = a') (z : P a ⊎ Q a) : z =[p; λ a, P a ⊎ Q a] sum.rec (λa, inl (p ▸ a)) (λb, inr (p ▸ b)) z := by induction p; induction z; constructor @[hott] protected def codeo (p : a = a') : P a ⊎ Q a → P a' ⊎ Q a' → Type (max u' v') := begin intros z z', induction z with x y; induction z' with x' y', exact ulift (x =[p; P] x'), exact ulift empty, exact ulift empty, exact ulift.{u' v'} (y =[p; Q] y') end @[hott] protected def decodeo (p : a = a') : Π(z : P a ⊎ Q a) (z' : P a' ⊎ Q a'), sum.codeo p z z' → z =[p; λ a, P a ⊎ Q a] z' := begin intros z z', induction z with x y; induction z' with x' y'; intro c, induction p, apply pathover_idp_of_eq, exact ap inl (eq_of_pathover_idp (ulift.down c)), apply empty.elim (ulift.down c), apply empty.elim (ulift.down c), induction p, apply pathover_idp_of_eq, exact ap inr (eq_of_pathover_idp (ulift.down c)), end variables {z z'} @[hott] protected def encodeo {p : a = a'} {z : P a ⊎ Q a} {z' : P a' ⊎ Q a'} (q : z =[p; λ a, P a ⊎ Q a] z') : sum.codeo p z z' := by induction q; induction z; exact ulift.up idpo variables (z z') @[hott] def sum_pathover_equiv (p : a = a') (z : P a ⊎ Q a) (z' : P a' ⊎ Q a') : (z =[p; λ a, P a ⊎ Q a] z') ≃ sum.codeo p z z' := equiv.MK sum.encodeo (sum.decodeo _ _ _) (by { intro c, induction z with a b; induction z' with a' b'; dsimp at *; induction c with c; induction c; -- c either has type empty or a pathover refl }) begin intro q, induction q, induction z; refl end end /- Functorial action -/ universes u'' v'' variables {A' : Type u''} {B' : Type v''} @[hott] def sum_functor (f : A → A') (g : B → B') : A ⊎ B → A' ⊎ B' := begin intro z, induction z with a b, exact inl (f a), exact inr (g b) end infix ` +→ `:62 := sum_functor /- Equivalences -/ @[hott, instance] def is_equiv_sum_functor (f : A → A') (g : B → B') [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (sum_functor f g) := begin fapply adjointify, refine sum_functor f⁻¹ᶠ g⁻¹ᶠ, { intro z, induction z, apply ap inl, apply right_inv, apply ap inr, apply right_inv }, { intro z, induction z, apply ap inl, apply left_inv, apply ap inr, apply left_inv } end @[hott] def sum_equiv_sum_of_is_equiv (f : A → A') (g : B → B') [Hf : is_equiv f] [Hg : is_equiv g] : A ⊎ B ≃ A' ⊎ B' := equiv.mk _ (is_equiv_sum_functor f g) @[hott] def sum_equiv_sum (f : A ≃ A') (g : B ≃ B') : A ⊎ B ≃ A' ⊎ B' := equiv.mk _ (is_equiv_sum_functor f g) infix ` +≃ `:62 := sum_equiv_sum @[hott] def sum_equiv_sum_left (g : B ≃ B') : A ⊎ B ≃ A ⊎ B' := sum_equiv_sum equiv.rfl g @[hott] def sum_equiv_sum_right (f : A ≃ A') : A ⊎ B ≃ A' ⊎ B := sum_equiv_sum f equiv.rfl @[hott] def flip : A ⊎ B → B ⊎ A := begin intro z, induction z with a b, exact inr a, exact inl b end @[hott] def flip_flip (x : A ⊎ B) : flip (flip x) = x := begin induction x; reflexivity end @[hott] def sum_comm_equiv (A B : Type _) : A ⊎ B ≃ B ⊎ A := equiv.MK flip flip flip_flip flip_flip @[hott] def sum_assoc_equiv (A B C : Type _) : A ⊎ (B ⊎ C) ≃ (A ⊎ B) ⊎ C := begin fapply equiv.MK, { intro z, induction z with u v, exact inl (inl u), induction v, exact inl (inr v), exact inr v }, { intro z, induction z with u v, induction u, exact (inl u), exact inr (inl u), exact inr (inr v) }, { intro z, induction z with u v, induction u, refl, refl, refl }, { intro z, induction z with u v, refl, induction v, refl, refl } end @[hott] def sum_empty_equiv (A : Type _) : A ⊎ empty ≃ A := begin fapply equiv.MK, { intro z, induction z, assumption, apply empty.elim z }, { exact inl}, { intro a, reflexivity}, { intro z, induction z, reflexivity, apply empty.elim z} end @[hott] def empty_sum_equiv (A : Type _) : empty ⊎ A ≃ A := sum_comm_equiv _ _ ⬝e sum_empty_equiv _ @[hott] def bool_equiv_unit_sum_unit : bool ≃ unit ⊎ unit := begin fapply equiv.MK, { intro b, cases b, exact inl unit.star, exact inr unit.star }, { intro s, cases s, exact bool.ff, exact bool.tt }, { intro s, cases s, repeat { cases s; refl } }, { intro b, cases b, refl, refl }, end @[hott] def sum_prod_right_distrib (A B C : Type _) : (A ⊎ B) × C ≃ (A × C) ⊎ (B × C) := begin fapply equiv.MK, { intro x, cases x with ab c, cases ab with a b, exact inl (a, c), exact inr (b, c) }, { intro x, cases x with ac bc, cases ac with a c, exact (inl a, c), cases bc with b c, exact (inr b, c) }, { intro x, cases x with ac bc, cases ac with a c, refl, cases bc, refl }, { intro x, cases x with ab c, cases ab with a b, refl, refl } end @[hott] def sum_prod_left_distrib (A B C : Type _) : A × (B ⊎ C) ≃ (A × B) ⊎ (A × C) := calc A × (B ⊎ C) ≃ (B ⊎ C) × A : prod_comm_equiv _ _ ... ≃ (B × A) ⊎ (C × A) : sum_prod_right_distrib _ _ _ ... ≃ (A × B) ⊎ (C × A) : sum_equiv_sum_right (prod_comm_equiv _ _) ... ≃ (A × B) ⊎ (A × C) : sum_equiv_sum_left (prod_comm_equiv _ _) section variables (H : unit ⊎ A ≃ unit ⊎ B) include H --open unit /-sigma.ops-/ @[hott] def unit_sum_equiv_cancel_map : A → B := begin intro a, cases sum.mem_cases (H (inr a)) with u b, cases u with u Hu, cases sum.mem_cases (H (inl unit.star)) with u' b, cases u' with u' Hu', apply empty.elim, apply empty_of_inl_eq_inr, calc inl () = H⁻¹ᶠ (H (inl ())) : (to_left_inv H (inl ()))⁻¹ ... = H⁻¹ᶠ (inl u') : ap _ Hu' ... = H⁻¹ᶠ (inl u) : ap _ (is_prop.elim u' u) ... = H⁻¹ᶠ (H (inr a)) : ap _ Hu⁻¹ ... = inr a : to_left_inv H (inr a), exact b.1, exact b.1 end @[hott] def unit_sum_equiv_cancel_inv (b : B) : unit_sum_equiv_cancel_map H (unit_sum_equiv_cancel_map H⁻¹ᵉ b) = b := /-begin dsimp[unit_sum_equiv_cancel_map], apply sum.rec, { intro x, cases x with u Hu, dsimp, apply sum.rec, { intro x, exfalso, cases x with u' Hu', apply empty_of_inl_eq_inr, calc inl () = H⁻¹ (H (inl ())) : (to_left_inv H (inl ()))⁻¹ ... = H⁻¹ (inl u') : ap H⁻¹ Hu' ... = H⁻¹ (inl u) : ap _ (is_prop.elim _ _) ... = H⁻¹ (H (inr _)) : ap _ Hu⁻¹ ... = inr _ : to_left_inv H }, { intro x, cases x with b' Hb', dsimp, cases sum.mem_cases (H⁻¹ (inr b)) with x x, { cases x with u' Hu', cases u', apply eq_of_inr_eq_inr, calc inr b' = H (inl ()) : Hb'⁻¹ ... = H (H⁻¹ (inr b)) : (ap H Hu')⁻¹ ... = inr b : to_right_inv H (inr b)}, { exfalso, cases x with a Ha, apply empty_of_inl_eq_inr, cases u, apply concat, apply Hu⁻¹, apply concat, apply (to_right_inv H), apply ap H, apply concat, apply Ha⁻¹, apply ap inr, dsimp, apply sum.rec, intro x, exfalso, apply empty_of_inl_eq_inr, apply concat, exact x.2⁻¹, apply Ha, intro x, cases x with a' Ha', dsimp, apply eq_of_inr_eq_inr, apply Ha'⁻¹ ⬝ Ha } } }, { intro x, cases x with b' Hb', dsimp, apply eq_of_inr_eq_inr, refine Hb'⁻¹ ⬝ _, cases sum.mem_cases (H⁻¹ (inr b)) with x x, { cases x with u Hu, dsimp, cases sum.mem_cases (H⁻¹ (inl ())) with x x, { cases x with u' Hu', exfalso, apply empty_of_inl_eq_inr, calc inl () = H (H⁻¹ (inl ())) : (to_right_inv H (inl ()))⁻¹ ... = H (inl u') : ap H Hu' ... = H (inl u) : ap H (is_prop.elim u' u) ... = H (H⁻¹ (inr b)) : ap H Hu⁻¹ ... = inr b : to_right_inv H (inr b) }, { cases x with a Ha, exfalso, apply empty_of_inl_eq_inr, apply concat, exact Hb', have Ha' : inl () = H (inr a), by apply (to_right_inv H _)⁻¹ ⬝ ap H Ha, apply concat Ha', apply ap H, apply ap inr, apply sum.rec, intro x, cases x with u' Hu', dsimp, apply sum.rec, intro x, cases x with u'' Hu'', dsimp, apply empty.rec, intro x, cases x with a'' Ha'', dsimp, rwr Ha' at Ha'', apply eq_of_inr_eq_inr, apply (to_left_inv H _)⁻¹ ⬝ Ha'', intro x, exfalso, cases x with a'' Ha'', apply empty_of_inl_eq_inr, apply Hu⁻¹ ⬝ Ha'', } }, { cases x with a' Ha', dsimp, refine _ ⬝ (to_right_inv H _), apply ap H, apply Ha'⁻¹ } } end-/ sorry @[hott] def unit_sum_equiv_cancel : A ≃ B := begin fapply equiv.MK, apply unit_sum_equiv_cancel_map H, apply unit_sum_equiv_cancel_map H⁻¹ᵉ, intro b, apply unit_sum_equiv_cancel_inv, { intro a, have eH : H = (H⁻¹ᵉ)⁻¹ᵉ, { symmetry, apply equiv.symm_symm }, transitivity, apply ap (unit_sum_equiv_cancel_map H⁻¹ᵉ), exact ap011 _ eH idp, apply unit_sum_equiv_cancel_inv } end end /- universal property -/ @[hott] def sum_rec_unc {P : A ⊎ B → Type _} (fg : (Πa, P (inl a)) × (Πb, P (inr b))) : Πz, P z := sum.rec fg.1 fg.2 @[hott] def is_equiv_sum_rec (P : A ⊎ B → Type _) : is_equiv (sum_rec_unc : (Πa, P (inl a)) × (Πb, P (inr b)) → Πz, P z) := begin apply adjointify sum_rec_unc (λf, (λa, f (inl a), λb, f (inr b))), intro f, apply eq_of_homotopy, intro z, { induction z; refl }, intro h, induction h with f g, refl end @[hott] def equiv_sum_rec (P : A ⊎ B → Type _) : (Πa, P (inl a)) × (Πb, P (inr b)) ≃ Πz, P z := equiv.mk _ (is_equiv_sum_rec _) @[hott] def imp_prod_imp_equiv_sum_imp (A B C : Type _) : (A → C) × (B → C) ≃ (A ⊎ B → C) := equiv_sum_rec (λ x, C) /- truncatedness -/ @[hott] def is_trunc_sum (n : ℕ₋₂) (A B : Type _) [HA : is_trunc (n.+1.+1) A] [HB : is_trunc (n.+1.+1) B] : is_trunc (n.+1.+1) (A ⊎ B) := begin apply is_trunc_succ_intro, intros z z', apply is_trunc_equiv_closed_rev, apply sum_eq_equiv, hinduction z with a b; hinduction z' with a' b'; dsimp[sum.code]; infer end @[hott] def is_trunc_sum_excluded (n : ℕ₋₂) (A B : Type _) [HA : is_trunc n A] [HB : is_trunc n B] (H : A → B → empty) : is_trunc n (A ⊎ B) := begin resetI, induction n with n IH, { apply empty.elim, exact H (center _) (center _) }, { clear IH, induction n with n IH, { apply is_prop.mk, intros x y, induction x; induction y; try { exfalso; apply H; assumption; assumption }, apply ap inl, apply is_prop.elim, apply empty.elim, exact H x y, apply empty.elim, exact H y x, apply ap inr, apply is_prop.elim }, { apply is_trunc_sum}} end @[hott] def is_contr_sum_left (A : Type _) {B : Type _} [HA : is_contr A] (H : ¬B) : is_contr (A ⊎ B) := is_contr.mk (inl (center _)) (λx, sum.rec_on x (λa, ap inl (center_eq _)) (λb, empty.elim (H b))) /- Sums are equivalent to dependent sigmas where the first component is a bool. The current construction only works for A and B in the same universe. If we need it for A and B in different universes, we need to insert some lifts. -/ @[hott] def sum_of_sigma_bool {A B : Type u} (v : Σ(b : bool), bool.rec A B b) : A ⊎ B := by { induction v with b x, induction b, exact inl x, exact inr x } @[hott] def sigma_bool_of_sum {A B : Type u} (z : A ⊎ B) : Σ(b : bool), bool.rec A B b := by { induction z with a b, exact ⟨ff, a⟩, exact ⟨tt, b⟩ } @[hott] def sum_equiv_sigma_bool (A B : Type u) : A ⊎ B ≃ Σ(b : bool), bool.rec A B b := equiv.MK sigma_bool_of_sum sum_of_sigma_bool begin intro v, induction v with b x, induction b; refl end begin intro z, induction z with a b; refl end variables {A₀₀ A₂₀ A₀₂ A₂₂ B₀₀ B₂₀ B₀₂ B₂₂ C C' : Type} {f₁₀ : A₀₀ → A₂₀} {f₁₂ : A₀₂ → A₂₂} {f₀₁ : A₀₀ → A₀₂} {f₂₁ : A₂₀ → A₂₂} {g₁₀ : B₀₀ → B₂₀} {g₁₂ : B₀₂ → B₂₂} {g₀₁ : B₀₀ → B₀₂} {g₂₁ : B₂₀ → B₂₂} {h₀₁ : B₀₀ → A₀₂} {h₂₁ : B₂₀ → A₂₂} open function /-@[hott] def sum_rec_hsquare (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ f₁₂ h₀₁ h₂₁) : hsquare (f₁₀ +→ g₁₀) f₁₂ (sum.rec f₀₁ h₀₁) (sum.rec f₂₁ h₂₁) := begin intro x, induction x with a b, exact h a, exact k b end def sum_functor_hsquare [unfold 19] (h : hsquare f₁₀ f₁₂ f₀₁ f₂₁) (k : hsquare g₁₀ g₁₂ g₀₁ g₂₁) : hsquare (f₁₀ +→ g₁₀) (f₁₂ +→ g₁₂) (f₀₁ +→ g₀₁) (f₂₁ +→ g₂₁) := sum_rec_hsquare (λa, ap inl (h a)) (λb, ap inr (k b))-/ /-@[hott] def sum_functor_compose (g : B → C) (f : A → B) (g' : B' → C') (f' : A' → B') : (g ∘ f) +→ (g' ∘ f') ~ g +→ g' ∘ f +→ f' := begin intro x, induction x with a a': reflexivity end def sum_rec_sum_functor (g : B → C) (g' : B' → C) (f : A → B) (f' : A' → B') : sum.rec g g' ∘ sum_functor f f' ~ sum.rec (g ∘ f) (g' ∘ f') := begin intro x, induction x with a a': reflexivity end def sum_rec_same_compose (g : B → C) (f : A → B) : sum.rec (g ∘ f) (g ∘ f) ~ g ∘ sum.rec f f := begin intro x, induction x with a a': reflexivity end def sum_rec_same (f : A → B) : sum.rec f f ~ f ∘ sum.rec id id := by exact sum_rec_same_compose f id-/ /- pointed sums. We arbitrarily choose (inl pt) as basepoint for the sum -/ open hott.pointed @[hott] def psum (A B : Type*) : Type* := pointed.MK (A ⊎ B) (inl pt) infixr ` +* `:30 := psum end sum open sum pi namespace decidable /- some properties about the inductive type `decidable` decidable A is equivalent to A ⊎ ¬A -/ @[hott] def decidable_equiv (A : Type _) : decidable A ≃ A ⊎ ¬A := begin fapply equiv.MK; intro a; induction a; try { constructor, assumption }, apply inr a, apply decidable.inr a, refl, refl, refl, refl end @[hott] def is_trunc_decidable (A : Type _) (n : ℕ₋₂) [H : is_trunc n A] : is_trunc n (decidable A) := begin resetI, apply is_trunc_equiv_closed_rev, apply decidable_equiv, induction n with n IH, { apply is_contr_sum_left, exact λna, na (center _)}, { apply is_trunc_sum_excluded, exact λa na, na a} end @[hott] def double_neg_elim {A : Type _} (H : decidable A) (p : ¬ ¬ A) : A := begin resetI, induction H, assumption, apply empty.elim, exact p H end @[hott] def dite_true {C : Type _} [H : decidable C] {A : Type _} {t : C → A} {e : ¬ C → A} (c : C) (H' : is_prop C) : dite C t e = t c := begin resetI, induction H with H H, exact ap t (is_prop.elim _ _), apply empty.elim, exact H c, end @[hott] def dite_false {C : Type _} [H : decidable C] {A : Type _} {t : C → A} {e : ¬ C → A} (c : ¬ C) : dite C t e = e c := begin resetI, induction H with H H, apply empty.elim, exact c H, exact ap e (is_prop.elim _ _), end @[hott] def decidable_eq_of_is_prop (A : Type _) [is_prop A] : hott.decidable_eq A := λa a', decidable.inl (is_prop.elim _ _) @[hott, instance] def decidable_eq_sigma {A : Type _} (B : A → Type _) [HA : hott.decidable_eq A] [HB : Πa, hott.decidable_eq (B a)] : hott.decidable_eq (Σa, B a) := begin intros v v', induction v with a b, induction v' with a' b', cases HA a a' with p np, { induction p, cases HB a b b' with q nq, induction q, exact decidable.inl idp, apply decidable.inr, intro p, apply nq, apply @eq_of_pathover_idp A B, exact change_path (is_prop.elim _ _) p..2 }, { apply decidable.inr, intro p, apply np, exact p..1 } end open sum @[hott, instance] def decidable_eq_sum (A B : Type _) [HA : hott.decidable_eq A] [HB : hott.decidable_eq B] : hott.decidable_eq (A ⊎ B) := begin intros v v', induction v with a b; induction v' with a' b', { hinduction HA a a', { exact decidable.inl (ap sum.inl a_1) }, { apply decidable.inr, intro p, apply a_1, exact ulift.down (sum.encode p) }}, { apply decidable.inr, intro p, apply empty_of_inl_eq_inr p }, { apply decidable.inr, intro p, apply empty_of_inr_eq_inl p }, { hinduction HB b b', { exact decidable.inl (ap sum.inr a) }, { apply decidable.inr, intro p, apply a, exact ulift.down (sum.encode p) }}, end end decidable @[hott]def tsum {n : ℕ₋₂} (A B : (n.+2)-Type) : (n.+2)-Type := trunctype.mk (A ⊎ B) (is_trunc_sum _ _ _) infixr `+t`:25 := tsum
25c4ded3961b1b6e84683c7f7819fc78764a1c7e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/dynamics/ergodic/conservative.lean
b83f718535a37029fc72186eb8599394beeceea4
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
10,016
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 dynamics.ergodic.measure_preserving import combinatorics.pigeonhole /-! # Conservative systems In this file we define `f : α → α` to be a *conservative* system w.r.t a measure `μ` if `f` is non-singular (`measure_theory.quasi_measure_preserving`) and for every measurable set `s` of positive measure at least one point `x ∈ s` returns back to `s` after some number of iterations of `f`. There are several properties that look like they are stronger than this one but actually follow from it: * `measure_theory.conservative.frequently_measure_inter_ne_zero`, `measure_theory.conservative.exists_gt_measure_inter_ne_zero`: if `μ s ≠ 0`, then for infinitely many `n`, the measure of `s ∩ (f^[n]) ⁻¹' s` is positive. * `measure_theory.conservative.measure_mem_forall_ge_image_not_mem_eq_zero`, `measure_theory.conservative.ae_mem_imp_frequently_image_mem`: a.e. every point of `s` visits `s` infinitely many times (Poincaré recurrence theorem). We also prove the topological Poincaré recurrence theorem `measure_theory.conservative.ae_frequently_mem_of_mem_nhds`. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. ## Tags conservative dynamical system, Poincare recurrence theorem -/ noncomputable theory open classical set filter measure_theory finset function topological_space open_locale classical topological_space variables {ι : Type*} {α : Type*} [measurable_space α] {f : α → α} {s : set α} {μ : measure α} namespace measure_theory open measure /-- We say that a non-singular (`measure_theory.quasi_measure_preserving`) self-map is *conservative* if for any measurable set `s` of positive measure there exists `x ∈ s` such that `x` returns back to `s` under some iteration of `f`. -/ structure conservative (f : α → α) (μ : measure α . volume_tac) extends quasi_measure_preserving f μ μ : Prop := (exists_mem_image_mem : ∀ ⦃s⦄, measurable_set s → μ s ≠ 0 → ∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s) /-- A self-map preserving a finite measure is conservative. -/ protected lemma measure_preserving.conservative [finite_measure μ] (h : measure_preserving f μ μ) : conservative f μ := ⟨h.quasi_measure_preserving, λ s hsm h0, h.exists_mem_image_mem hsm h0⟩ namespace conservative /-- The identity map is conservative w.r.t. any measure. -/ protected lemma id (μ : measure α) : conservative id μ := { to_quasi_measure_preserving := quasi_measure_preserving.id μ, exists_mem_image_mem := λ s hs h0, let ⟨x, hx⟩ := nonempty_of_measure_ne_zero h0 in ⟨x, hx, 1, one_ne_zero, hx⟩ } /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for infinitely many values of `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ lemma frequently_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) : ∃ᶠ m in at_top, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 := begin by_contra H, simp only [not_frequently, eventually_at_top, ne.def, not_not] at H, rcases H with ⟨N, hN⟩, induction N with N ihN, { apply h0, simpa using hN 0 le_rfl }, rw [imp_false] at ihN, push_neg at ihN, rcases ihN with ⟨n, hn, hμn⟩, set T := s ∩ ⋃ n ≥ N + 1, (f^[n]) ⁻¹' s, have hT : measurable_set T, from hs.inter (measurable_set.bUnion (countable_encodable _) (λ _ _, hf.measurable.iterate _ hs)), have hμT : μ T = 0, { convert (measure_bUnion_null_iff $ countable_encodable _).2 hN, rw ← set.inter_bUnion, refl }, have : μ ((s ∩ (f^[n]) ⁻¹' s) \ T) ≠ 0, by rwa [measure_diff_null hμT], rcases hf.exists_mem_image_mem ((hs.inter (hf.measurable.iterate n hs)).diff hT) this with ⟨x, ⟨⟨hxs, hxn⟩, hxT⟩, m, hm0, ⟨hxms, hxm⟩, hxx⟩, refine hxT ⟨hxs, mem_bUnion_iff.2 ⟨n + m, _, _⟩⟩, { exact add_le_add hn (nat.one_le_of_lt $ pos_iff_ne_zero.2 hm0) }, { rwa [set.mem_preimage, ← iterate_add_apply] at hxm } end /-- If `f` is a conservative map and `s` is a measurable set of nonzero measure, then for an arbitrarily large `m` a positive measure of points `x ∈ s` returns back to `s` after `m` iterations of `f`. -/ lemma exists_gt_measure_inter_ne_zero (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) (N : ℕ) : ∃ m > N, μ (s ∩ (f^[m]) ⁻¹' s) ≠ 0 := let ⟨m, hm, hmN⟩ := ((hf.frequently_measure_inter_ne_zero hs h0).and_eventually (eventually_gt_at_top N)).exists in ⟨m, hmN, hm⟩ /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, the set of points `x ∈ s` such that `x` does not return to `s` after `≥ n` iterations has measure zero. -/ lemma measure_mem_forall_ge_image_not_mem_eq_zero (hf : conservative f μ) (hs : measurable_set s) (n : ℕ) : μ {x ∈ s | ∀ m ≥ n, f^[m] x ∉ s} = 0 := begin by_contradiction H, have : measurable_set (s ∩ {x | ∀ m ≥ n, f^[m] x ∉ s}), { simp only [set_of_forall, ← compl_set_of], exact hs.inter (measurable_set.bInter (countable_encodable _) (λ m _, hf.measurable.iterate m hs.compl)) }, rcases (hf.exists_gt_measure_inter_ne_zero this H) n with ⟨m, hmn, hm⟩, rcases nonempty_of_measure_ne_zero hm with ⟨x, ⟨hxs, hxn⟩, hxm, -⟩, exact hxn m hmn.lt.le hxm end /-- Poincaré recurrence theorem: given a conservative map `f` and a measurable set `s`, almost every point `x ∈ s` returns back to `s` infinitely many times. -/ lemma ae_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) : ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s := begin simp only [frequently_at_top, @forall_swap (_ ∈ s), ae_all_iff], intro n, filter_upwards [measure_zero_iff_ae_nmem.1 (hf.measure_mem_forall_ge_image_not_mem_eq_zero hs n)], simp end lemma inter_frequently_image_mem_ae_eq (hf : conservative f μ) (hs : measurable_set s) : (s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s} : set α) =ᵐ[μ] s := inter_eventually_eq_left.2 $ hf.ae_mem_imp_frequently_image_mem hs lemma measure_inter_frequently_image_mem_eq (hf : conservative f μ) (hs : measurable_set s) : μ (s ∩ {x | ∃ᶠ n in at_top, f^[n] x ∈ s}) = μ s := measure_congr (hf.inter_frequently_image_mem_ae_eq hs) /-- Poincaré recurrence theorem: if `f` is a conservative dynamical system and `s` is a measurable set, then for `μ`-a.e. `x`, if the orbit of `x` visits `s` at least once, then it visits `s` infinitely many times. -/ lemma ae_forall_image_mem_imp_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) : ∀ᵐ x ∂μ, ∀ k, f^[k] x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s := begin refine ae_all_iff.2 (λ k, _), refine (hf.ae_mem_imp_frequently_image_mem (hf.measurable.iterate k hs)).mono (λ x hx hk, _), rw [← map_add_at_top_eq_nat k, frequently_map], refine (hx hk).mono (λ n hn, _), rwa [add_comm, iterate_add_apply] end /-- If `f` is a conservative self-map and `s` is a measurable set of positive measure, then `μ.ae`-frequently we have `x ∈ s` and `s` returns to `s` under infinitely many iterations of `f`. -/ lemma frequently_ae_mem_and_frequently_image_mem (hf : conservative f μ) (hs : measurable_set s) (h0 : μ s ≠ 0) : ∃ᵐ x ∂μ, x ∈ s ∧ ∃ᶠ n in at_top, (f^[n] x) ∈ s := ((frequently_ae_mem_iff.2 h0).and_eventually (hf.ae_mem_imp_frequently_image_mem hs)).mono $ λ x hx, ⟨hx.1, hx.2 hx.1⟩ /-- Poincaré recurrence theorem. Let `f : α → α` be a conservative dynamical system on a topological space with second countable topology and measurable open sets. Then almost every point `x : α` is recurrent: it visits every neighborhood `s ∈ 𝓝 x` infinitely many times. -/ lemma ae_frequently_mem_of_mem_nhds [topological_space α] [second_countable_topology α] [opens_measurable_space α] {f : α → α} {μ : measure α} (h : conservative f μ) : ∀ᵐ x ∂μ, ∀ s ∈ 𝓝 x, ∃ᶠ n in at_top, f^[n] x ∈ s := begin have : ∀ s ∈ countable_basis α, ∀ᵐ x ∂μ, x ∈ s → ∃ᶠ n in at_top, (f^[n] x) ∈ s, from λ s hs, h.ae_mem_imp_frequently_image_mem (is_open_of_mem_countable_basis hs).measurable_set, refine ((ae_ball_iff $ countable_countable_basis α).2 this).mono (λ x hx s hs, _), rcases (is_basis_countable_basis α).mem_nhds_iff.1 hs with ⟨o, hoS, hxo, hos⟩, exact (hx o hoS hxo).mono (λ n hn, hos hn) end /-- Iteration of a conservative system is a conservative system. -/ protected lemma iterate (hf : conservative f μ) (n : ℕ) : conservative (f^[n]) μ := begin cases n, { exact conservative.id μ }, -- Discharge the trivial case `n = 0` refine ⟨hf.1.iterate _, λ s hs hs0, _⟩, rcases (hf.frequently_ae_mem_and_frequently_image_mem hs hs0).exists with ⟨x, hxs, hx⟩, /- We take a point `x ∈ s` such that `f^[k] x ∈ s` for infinitely many values of `k`, then we choose two of these values `k < l` such that `k ≡ l [MOD (n + 1)]`. Then `f^[k] x ∈ s` and `(f^[n + 1])^[(l - k) / (n + 1)] (f^[k] x) = f^[l] x ∈ s`. -/ rw nat.frequently_at_top_iff_infinite at hx, rcases nat.exists_lt_modeq_of_infinite hx n.succ_pos with ⟨k, hk, l, hl, hkl, hn⟩, set m := (l - k) / (n + 1), have : (n + 1) * m = l - k, { apply nat.mul_div_cancel', exact (nat.modeq.modeq_iff_dvd' hkl.le).1 hn }, refine ⟨f^[k] x, hk, m, _, _⟩, { intro hm, rw [hm, mul_zero, eq_comm, nat.sub_eq_zero_iff_le] at this, exact this.not_lt hkl }, { rwa [← iterate_mul, this, ← iterate_add_apply, nat.sub_add_cancel], exact hkl.le } end end conservative end measure_theory
0e4551478cb8e08a86290f436ab72b1a9e9eaa21
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/limits/shapes/types.lean
1fb3086376ac7c03654368aacf810655790d53b5
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
18,498
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.types import category_theory.limits.shapes.products import category_theory.limits.shapes.binary_products import category_theory.limits.shapes.terminal import tactic.elementwise /-! # Special shapes for limits in `Type`. The general shape (co)limits defined in `category_theory.limits.types` are intended for use through the limits API, and the actual implementation should mostly be considered "sealed". In this file, we provide definitions of the "standard" special shapes of limits in `Type`, giving the expected definitional implementation: * the terminal object is `punit` * the binary product of `X` and `Y` is `X × Y` * the product of a family `f : J → Type` is `Π j, f j` * the coproduct of a family `f : J → Type` is `Σ j, f j` * the binary coproduct of `X` and `Y` is the sum type `X ⊕ Y` * the equalizer of a pair of maps `(g, h)` is the subtype `{x : Y // g x = h x}` * the coequalizer of a pair of maps `(f, g)` is the quotient of `Y` by `∀ x : Y, f x ~ g x` * the pullback of `f : X ⟶ Z` and `g : Y ⟶ Z` is the subtype `{ p : X × Y // f p.1 = g p.2 }` of the product We first construct terms of `is_limit` and `limit_cone`, and then provide isomorphisms with the types generated by the `has_limit` API. As an example, when setting up the monoidal category structure on `Type` we use the `types_has_terminal` and `types_has_binary_products` instances. -/ universes u open category_theory open category_theory.limits namespace category_theory.limits.types local attribute [tidy] tactic.discrete_cases /-- A restatement of `types.lift_π_apply` that uses `pi.π` and `pi.lift`. -/ @[simp] lemma pi_lift_π_apply {β : Type u} (f : β → Type u) {P : Type u} (s : Π b, P ⟶ f b) (b : β) (x : P) : (pi.π f b : (∏ f) → f b) (@pi.lift β _ _ f _ P s x) = s b x := congr_fun (limit.lift_π (fan.mk P s) ⟨b⟩) x /-- A restatement of `types.map_π_apply` that uses `pi.π` and `pi.map`. -/ @[simp] lemma pi_map_π_apply {β : Type u} {f g : β → Type u} (α : Π j, f j ⟶ g j) (b : β) (x) : (pi.π g b : (∏ g) → g b) (pi.map α x) = α b ((pi.π f b : (∏ f) → f b) x) := limit.map_π_apply _ _ _ /-- The category of types has `punit` as a terminal object. -/ def terminal_limit_cone : limits.limit_cone (functor.empty (Type u)) := { cone := { X := punit, π := by tidy, }, is_limit := by tidy, } /-- The terminal object in `Type u` is `punit`. -/ noncomputable def terminal_iso : ⊤_ (Type u) ≅ punit := limit.iso_limit_cone terminal_limit_cone /-- The category of types has `pempty` as an initial object. -/ def initial_colimit_cocone : limits.colimit_cocone (functor.empty (Type u)) := { cocone := { X := pempty, ι := by tidy, }, is_colimit := by tidy, } /-- The initial object in `Type u` is `pempty`. -/ noncomputable def initial_iso : ⊥_ (Type u) ≅ pempty := colimit.iso_colimit_cocone initial_colimit_cocone open category_theory.limits.walking_pair /-- The product type `X × Y` forms a cone for the binary product of `X` and `Y`. -/ -- We manually generate the other projection lemmas since the simp-normal form for the legs is -- otherwise not created correctly. @[simps X] def binary_product_cone (X Y : Type u) : binary_fan X Y := binary_fan.mk prod.fst prod.snd @[simp] lemma binary_product_cone_fst (X Y : Type u) : (binary_product_cone X Y).fst = prod.fst := rfl @[simp] lemma binary_product_cone_snd (X Y : Type u) : (binary_product_cone X Y).snd = prod.snd := rfl /-- The product type `X × Y` is a binary product for `X` and `Y`. -/ @[simps] def binary_product_limit (X Y : Type u) : is_limit (binary_product_cone X Y) := { lift := λ (s : binary_fan X Y) x, (s.fst x, s.snd x), fac' := λ s j, discrete.rec_on j (λ j, walking_pair.cases_on j rfl rfl), uniq' := λ s m w, funext $ λ x, prod.ext (congr_fun (w ⟨left⟩) x) (congr_fun (w ⟨right⟩) x) } /-- The category of types has `X × Y`, the usual cartesian product, as the binary product of `X` and `Y`. -/ @[simps] def binary_product_limit_cone (X Y : Type u) : limits.limit_cone (pair X Y) := ⟨_, binary_product_limit X Y⟩ /-- The categorical binary product in `Type u` is cartesian product. -/ noncomputable def binary_product_iso (X Y : Type u) : limits.prod X Y ≅ X × Y := limit.iso_limit_cone (binary_product_limit_cone X Y) @[simp, elementwise] lemma binary_product_iso_hom_comp_fst (X Y : Type u) : (binary_product_iso X Y).hom ≫ prod.fst = limits.prod.fst := limit.iso_limit_cone_hom_π (binary_product_limit_cone X Y) ⟨walking_pair.left⟩ @[simp, elementwise] lemma binary_product_iso_hom_comp_snd (X Y : Type u) : (binary_product_iso X Y).hom ≫ prod.snd = limits.prod.snd := limit.iso_limit_cone_hom_π (binary_product_limit_cone X Y) ⟨walking_pair.right⟩ @[simp, elementwise] lemma binary_product_iso_inv_comp_fst (X Y : Type u) : (binary_product_iso X Y).inv ≫ limits.prod.fst = prod.fst := limit.iso_limit_cone_inv_π (binary_product_limit_cone X Y) ⟨walking_pair.left⟩ @[simp, elementwise] lemma binary_product_iso_inv_comp_snd (X Y : Type u) : (binary_product_iso X Y).inv ≫ limits.prod.snd = prod.snd := limit.iso_limit_cone_inv_π (binary_product_limit_cone X Y) ⟨walking_pair.right⟩ /-- The functor which sends `X, Y` to the product type `X × Y`. -/ -- We add the option `type_md` to tell `@[simps]` to not treat homomorphisms `X ⟶ Y` in `Type*` as -- a function type @[simps {type_md := reducible}] def binary_product_functor : Type u ⥤ Type u ⥤ Type u := { obj := λ X, { obj := λ Y, X × Y, map := λ Y₁ Y₂ f, (binary_product_limit X Y₂).lift (binary_fan.mk prod.fst (prod.snd ≫ f)) }, map := λ X₁ X₂ f, { app := λ Y, (binary_product_limit X₂ Y).lift (binary_fan.mk (prod.fst ≫ f) prod.snd) } } /-- The product functor given by the instance `has_binary_products (Type u)` is isomorphic to the explicit binary product functor given by the product type. -/ noncomputable def binary_product_iso_prod : binary_product_functor ≅ (prod.functor : Type u ⥤ _) := begin apply nat_iso.of_components (λ X, _) _, { apply nat_iso.of_components (λ Y, _) _, { exact ((limit.is_limit _).cone_point_unique_up_to_iso (binary_product_limit X Y)).symm }, { intros Y₁ Y₂ f, ext1; simp } }, { intros X₁ X₂ g, ext : 3; simp } end /-- The sum type `X ⊕ Y` forms a cocone for the binary coproduct of `X` and `Y`. -/ @[simps] def binary_coproduct_cocone (X Y : Type u) : cocone (pair X Y) := binary_cofan.mk sum.inl sum.inr /-- The sum type `X ⊕ Y` is a binary coproduct for `X` and `Y`. -/ @[simps] def binary_coproduct_colimit (X Y : Type u) : is_colimit (binary_coproduct_cocone X Y) := { desc := λ (s : binary_cofan X Y), sum.elim s.inl s.inr, fac' := λ s j, discrete.rec_on j (λ j, walking_pair.cases_on j rfl rfl), uniq' := λ s m w, funext $ λ x, sum.cases_on x (congr_fun (w ⟨left⟩)) (congr_fun (w ⟨right⟩)) } /-- The category of types has `X ⊕ Y`, as the binary coproduct of `X` and `Y`. -/ def binary_coproduct_colimit_cocone (X Y : Type u) : limits.colimit_cocone (pair X Y) := ⟨_, binary_coproduct_colimit X Y⟩ /-- The categorical binary coproduct in `Type u` is the sum `X ⊕ Y`. -/ noncomputable def binary_coproduct_iso (X Y : Type u) : limits.coprod X Y ≅ X ⊕ Y := colimit.iso_colimit_cocone (binary_coproduct_colimit_cocone X Y) open_locale category_theory.Type @[simp, elementwise] lemma binary_coproduct_iso_inl_comp_hom (X Y : Type u) : limits.coprod.inl ≫ (binary_coproduct_iso X Y).hom = sum.inl := colimit.iso_colimit_cocone_ι_hom (binary_coproduct_colimit_cocone X Y) ⟨walking_pair.left⟩ @[simp, elementwise] lemma binary_coproduct_iso_inr_comp_hom (X Y : Type u) : limits.coprod.inr ≫ (binary_coproduct_iso X Y).hom = sum.inr := colimit.iso_colimit_cocone_ι_hom (binary_coproduct_colimit_cocone X Y) ⟨walking_pair.right⟩ @[simp, elementwise] lemma binary_coproduct_iso_inl_comp_inv (X Y : Type u) : ↾(sum.inl : X ⟶ X ⊕ Y) ≫ (binary_coproduct_iso X Y).inv = limits.coprod.inl := colimit.iso_colimit_cocone_ι_inv (binary_coproduct_colimit_cocone X Y) ⟨walking_pair.left⟩ @[simp, elementwise] lemma binary_coproduct_iso_inr_comp_inv (X Y : Type u) : ↾(sum.inr : Y ⟶ X ⊕ Y) ≫ (binary_coproduct_iso X Y).inv = limits.coprod.inr := colimit.iso_colimit_cocone_ι_inv (binary_coproduct_colimit_cocone X Y) ⟨walking_pair.right⟩ /-- The category of types has `Π j, f j` as the product of a type family `f : J → Type`. -/ def product_limit_cone {J : Type u} (F : J → Type u) : limits.limit_cone (discrete.functor F) := { cone := { X := Π j, F j, π := { app := λ j f, f j.as }, }, is_limit := { lift := λ s x j, s.π.app ⟨j⟩ x, uniq' := λ s m w, funext $ λ x, funext $ λ j, (congr_fun (w ⟨j⟩) x : _) } } /-- The categorical product in `Type u` is the type theoretic product `Π j, F j`. -/ noncomputable def product_iso {J : Type u} (F : J → Type u) : ∏ F ≅ Π j, F j := limit.iso_limit_cone (product_limit_cone F) @[simp, elementwise] lemma product_iso_hom_comp_eval {J : Type u} (F : J → Type u) (j : J) : (product_iso F).hom ≫ (λ f, f j) = pi.π F j := rfl @[simp, elementwise] lemma product_iso_inv_comp_π {J : Type u} (F : J → Type u) (j : J) : (product_iso F).inv ≫ pi.π F j = (λ f, f j) := limit.iso_limit_cone_inv_π (product_limit_cone F) ⟨j⟩ /-- The category of types has `Σ j, f j` as the coproduct of a type family `f : J → Type`. -/ def coproduct_colimit_cocone {J : Type u} (F : J → Type u) : limits.colimit_cocone (discrete.functor F) := { cocone := { X := Σ j, F j, ι := { app := λ j x, ⟨j.as, x⟩ }, }, is_colimit := { desc := λ s x, s.ι.app ⟨x.1⟩ x.2, uniq' := λ s m w, begin ext ⟨j, x⟩, have := congr_fun (w ⟨j⟩) x, exact this, end }, } /-- The categorical coproduct in `Type u` is the type theoretic coproduct `Σ j, F j`. -/ noncomputable def coproduct_iso {J : Type u} (F : J → Type u) : ∐ F ≅ Σ j, F j := colimit.iso_colimit_cocone (coproduct_colimit_cocone F) @[simp, elementwise] lemma coproduct_iso_ι_comp_hom {J : Type u} (F : J → Type u) (j : J) : sigma.ι F j ≫ (coproduct_iso F).hom = (λ x : F j, (⟨j, x⟩ : Σ j, F j)) := colimit.iso_colimit_cocone_ι_hom (coproduct_colimit_cocone F) ⟨j⟩ @[simp, elementwise] lemma coproduct_iso_mk_comp_inv {J : Type u} (F : J → Type u) (j : J) : ↾(λ x : F j, (⟨j, x⟩ : Σ j, F j)) ≫ (coproduct_iso F).inv = sigma.ι F j := rfl section fork variables {X Y Z : Type u} (f : X ⟶ Y) {g h : Y ⟶ Z} (w : f ≫ g = f ≫ h) /-- Show the given fork in `Type u` is an equalizer given that any element in the "difference kernel" comes from `X`. The converse of `unique_of_type_equalizer`. -/ noncomputable def type_equalizer_of_unique (t : ∀ (y : Y), g y = h y → ∃! (x : X), f x = y) : is_limit (fork.of_ι _ w) := fork.is_limit.mk' _ $ λ s, begin refine ⟨λ i, _, _, _⟩, { apply classical.some (t (s.ι i) _), apply congr_fun s.condition i }, { ext i, apply (classical.some_spec (t (s.ι i) _)).1 }, { intros m hm, ext i, apply (classical.some_spec (t (s.ι i) _)).2, apply congr_fun hm i }, end /-- The converse of `type_equalizer_of_unique`. -/ lemma unique_of_type_equalizer (t : is_limit (fork.of_ι _ w)) (y : Y) (hy : g y = h y) : ∃! (x : X), f x = y := begin let y' : punit ⟶ Y := λ _, y, have hy' : y' ≫ g = y' ≫ h := funext (λ _, hy), refine ⟨(fork.is_limit.lift' t _ hy').1 ⟨⟩, congr_fun (fork.is_limit.lift' t y' _).2 ⟨⟩, _⟩, intros x' hx', suffices : (λ (_ : punit), x') = (fork.is_limit.lift' t y' hy').1, rw ← this, apply fork.is_limit.hom_ext t, ext ⟨⟩, apply hx'.trans (congr_fun (fork.is_limit.lift' t _ hy').2 ⟨⟩).symm, end lemma type_equalizer_iff_unique : nonempty (is_limit (fork.of_ι _ w)) ↔ (∀ (y : Y), g y = h y → ∃! (x : X), f x = y) := ⟨λ i, unique_of_type_equalizer _ _ (classical.choice i), λ k, ⟨type_equalizer_of_unique f w k⟩⟩ /-- Show that the subtype `{x : Y // g x = h x}` is an equalizer for the pair `(g,h)`. -/ def equalizer_limit : limits.limit_cone (parallel_pair g h) := { cone := fork.of_ι (subtype.val : {x : Y // g x = h x} → Y) (funext subtype.prop), is_limit := fork.is_limit.mk' _ $ λ s, ⟨λ i, ⟨s.ι i, by apply congr_fun s.condition i⟩, rfl, λ m hm, funext $ λ x, subtype.ext (congr_fun hm x)⟩ } variables (g h) /-- The categorical equalizer in `Type u` is `{x : Y // g x = h x}`. -/ noncomputable def equalizer_iso : equalizer g h ≅ {x : Y // g x = h x} := limit.iso_limit_cone equalizer_limit @[simp, elementwise] lemma equalizer_iso_hom_comp_subtype : (equalizer_iso g h).hom ≫ subtype.val = equalizer.ι g h := rfl @[simp, elementwise] lemma equalizer_iso_inv_comp_ι : (equalizer_iso g h).inv ≫ equalizer.ι g h = subtype.val := limit.iso_limit_cone_inv_π equalizer_limit walking_parallel_pair.zero end fork section cofork variables {X Y Z : Type u} (f g : X ⟶ Y) /-- (Implementation) The relation to be quotiented to obtain the coequalizer. -/ inductive coequalizer_rel : Y → Y → Prop | rel (x : X) : coequalizer_rel (f x) (g x) /-- Show that the quotient by the relation generated by `f(x) ~ g(x)` is a coequalizer for the pair `(f, g)`. -/ def coequalizer_colimit : limits.colimit_cocone (parallel_pair f g) := { cocone := cofork.of_π (quot.mk (coequalizer_rel f g)) (funext (λ x, quot.sound (coequalizer_rel.rel x))), is_colimit := cofork.is_colimit.mk' _ $ λ s, ⟨ quot.lift s.π (λ a b (h : coequalizer_rel f g a b), by { cases h, exact congr_fun s.condition h_1 }), rfl, λ m hm, funext $ λ x, quot.induction_on x (congr_fun hm : _) ⟩ } /-- If `π : Y ⟶ Z` is an equalizer for `(f, g)`, and `U ⊆ Y` such that `f ⁻¹' U = g ⁻¹' U`, then `π ⁻¹' (π '' U) = U`. -/ lemma coequalizer_preimage_image_eq_of_preimage_eq (π : Y ⟶ Z) (e : f ≫ π = g ≫ π) (h : is_colimit (cofork.of_π π e)) (U : set Y) (H : f ⁻¹' U = g ⁻¹' U) : π ⁻¹' (π '' U) = U := begin have lem : ∀ x y, (coequalizer_rel f g x y) → (x ∈ U ↔ y ∈ U), { rintros _ _ ⟨x⟩, change x ∈ f ⁻¹' U ↔ x ∈ g ⁻¹' U, congr' 2 }, have eqv : _root_.equivalence (λ x y, x ∈ U ↔ y ∈ U) := by tidy, ext, split, { rw ← (show _ = π, from h.comp_cocone_point_unique_up_to_iso_inv (coequalizer_colimit f g).2 walking_parallel_pair.one), rintro ⟨y, hy, e'⟩, dsimp at e', replace e' := (mono_iff_injective (h.cocone_point_unique_up_to_iso (coequalizer_colimit f g).is_colimit).inv).mp infer_instance e', exact (eqv.eqv_gen_iff.mp (eqv_gen.mono lem (quot.exact _ e'))).mp hy }, { exact λ hx, ⟨x, hx, rfl⟩ } end /-- The categorical coequalizer in `Type u` is the quotient by `f g ~ g x`. -/ noncomputable def coequalizer_iso : coequalizer f g ≅ _root_.quot (coequalizer_rel f g) := colimit.iso_colimit_cocone (coequalizer_colimit f g) @[simp, elementwise] lemma coequalizer_iso_π_comp_hom : coequalizer.π f g ≫ (coequalizer_iso f g).hom = quot.mk (coequalizer_rel f g) := colimit.iso_colimit_cocone_ι_hom (coequalizer_colimit f g) walking_parallel_pair.one @[simp, elementwise] lemma coequalizer_iso_quot_comp_inv : ↾(quot.mk (coequalizer_rel f g)) ≫ (coequalizer_iso f g).inv = coequalizer.π f g := rfl end cofork section pullback open category_theory.limits.walking_pair open category_theory.limits.walking_cospan open category_theory.limits.walking_cospan.hom variables {W X Y Z : Type u} variables (f : X ⟶ Z) (g : Y ⟶ Z) /-- The usual explicit pullback in the category of types, as a subtype of the product. The full `limit_cone` data is bundled as `pullback_limit_cone f g`. -/ @[nolint has_nonempty_instance] abbreviation pullback_obj : Type u := { p : X × Y // f p.1 = g p.2 } -- `pullback_obj f g` comes with a coercion to the product type `X × Y`. example (p : pullback_obj f g) : X × Y := p /-- The explicit pullback cone on `pullback_obj f g`. This is bundled with the `is_limit` data as `pullback_limit_cone f g`. -/ abbreviation pullback_cone : limits.pullback_cone f g := pullback_cone.mk (λ p : pullback_obj f g, p.1.1) (λ p, p.1.2) (funext (λ p, p.2)) /-- The explicit pullback in the category of types, bundled up as a `limit_cone` for given `f` and `g`. -/ @[simps] def pullback_limit_cone (f : X ⟶ Z) (g : Y ⟶ Z) : limits.limit_cone (cospan f g) := { cone := pullback_cone f g, is_limit := pullback_cone.is_limit_aux _ (λ s x, ⟨⟨s.fst x, s.snd x⟩, congr_fun s.condition x⟩) (by tidy) (by tidy) (λ s m w, funext $ λ x, subtype.ext $ prod.ext (congr_fun (w walking_cospan.left) x) (congr_fun (w walking_cospan.right) x)) } /-- The pullback cone given by the instance `has_pullbacks (Type u)` is isomorphic to the explicit pullback cone given by `pullback_limit_cone`. -/ noncomputable def pullback_cone_iso_pullback : limit.cone (cospan f g) ≅ pullback_cone f g := (limit.is_limit _).unique_up_to_iso (pullback_limit_cone f g).is_limit /-- The pullback given by the instance `has_pullbacks (Type u)` is isomorphic to the explicit pullback object given by `pullback_limit_obj`. -/ noncomputable def pullback_iso_pullback : pullback f g ≅ pullback_obj f g := (cones.forget _).map_iso $ pullback_cone_iso_pullback f g @[simp] lemma pullback_iso_pullback_hom_fst (p : pullback f g) : ((pullback_iso_pullback f g).hom p : X × Y).fst = (pullback.fst : _ ⟶ X) p := congr_fun ((pullback_cone_iso_pullback f g).hom.w left) p @[simp] lemma pullback_iso_pullback_hom_snd (p : pullback f g) : ((pullback_iso_pullback f g).hom p : X × Y).snd = (pullback.snd : _ ⟶ Y) p := congr_fun ((pullback_cone_iso_pullback f g).hom.w right) p @[simp] lemma pullback_iso_pullback_inv_fst : (pullback_iso_pullback f g).inv ≫ pullback.fst = (λ p, (p : X × Y).fst) := (pullback_cone_iso_pullback f g).inv.w left @[simp] lemma pullback_iso_pullback_inv_snd : (pullback_iso_pullback f g).inv ≫ pullback.snd = (λ p, (p : X × Y).snd) := (pullback_cone_iso_pullback f g).inv.w right end pullback end category_theory.limits.types
637f83fe076538c772b9f4f2a25cd80f60b03b1f
94e33a31faa76775069b071adea97e86e218a8ee
/src/combinatorics/additive/behrend.lean
872e74b79b0ac9effba7557d684f8ad1cf3d6893
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
8,382
lean
/- Copyright (c) 2022 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.inner_product_space.pi_L2 import combinatorics.additive.salem_spencer /-! # Behrend's bound on Roth numbers This file proves Behrend's lower bound on Roth numbers. This says that we can find a subset of `{1, ..., n}` of size `n / exp (O (sqrt (log n)))` which does not contain arithmetic progressions of length `3`. The idea is that the sphere (in the `n` dimensional Euclidean space) doesn't contain arithmetic progressions (literally) because the corresponding ball is strictly convex. Thus we can take integer points on that sphere and map them onto `ℕ` in a way that preserves arithmetic progressions (`behrend.map`). ## Main declarations * `behrend.sphere`: The intersection of the Euclidean sphere with the positive integer quadrant. This is the set that we will map on `ℕ`. * `behrend.map`: Given a natural number `d`, `behrend.map d : ℕⁿ → ℕ` reads off the coordinates as digits in base `d`. * `behrend.card_sphere_le_roth_number_nat`: Implicit lower bound on Roth numbers in terms of `behrend.sphere`. ## References * [Bryan Gillespie, *Behrend’s Construction*] (http://www.epsilonsmall.com/resources/behrends-construction/behrend.pdf) * Behrend, F. A., "On sets of integers which contain no three terms in arithmetical progression" * [Wikipedia, *Salem-Spencer set*](https://en.wikipedia.org/wiki/Salem–Spencer_set) ## Tags Salem-Spencer, Behrend construction, arithmetic progression, sphere, strictly convex -/ open finset nat real open_locale big_operators pointwise namespace behrend variables {α β : Type*} {n d k N : ℕ} {x : fin n → ℕ} /-! ### Turning the sphere into a Salem-Spencer set We define `behrend.sphere`, the intersection of the $$L^2$$ sphere with the positive quadrant of integer points. Because the $$L^2$$ closed ball is strictly convex, the $$L^2$$ sphere and `behrend.sphere` are Salem-Spencer (`add_salem_spencer_sphere`). Then we can turn this set in `fin n → ℕ` into a set in `ℕ` using `behrend.map`, which preserves `add_salem_spencer` because it is an additive monoid homomorphism. -/ /-- The box `{0, ..., d - 1}^n` as a finset. -/ def box (n d : ℕ) : finset (fin n → ℕ) := fintype.pi_finset $ λ _, range d lemma mem_box : x ∈ box n d ↔ ∀ i, x i < d := by simp only [box, fintype.mem_pi_finset, mem_range] @[simp] lemma card_box : (box n d).card = d ^ n := by simp [box] @[simp] lemma box_zero : box (n + 1) 0 = ∅ := by simp [box] /-- The intersection of the sphere of radius `sqrt k` with the integer points in the positive quadrant. -/ def sphere (n d k : ℕ) : finset (fin n → ℕ) := (box n d).filter $ λ x, ∑ i, x i^2 = k lemma sphere_zero_subset : sphere n d 0 ⊆ 0 := λ x, by simp [sphere, function.funext_iff] {contextual := tt} @[simp] lemma sphere_zero_right (n k : ℕ) : sphere (n + 1) 0 k = ∅ := by simp [sphere] lemma sphere_subset_box : sphere n d k ⊆ box n d := filter_subset _ _ lemma norm_of_mem_sphere {x : fin n → ℕ} (hx : x ∈ sphere n d k) : ∥(pi_Lp.equiv 2 _).symm (coe ∘ x : fin n → ℝ)∥ = sqrt k := begin rw euclidean_space.norm_eq, dsimp, simp_rw [abs_cast, ←cast_pow, ←cast_sum, (mem_filter.1 hx).2], end lemma sphere_subset_preimage_metric_sphere : (sphere n d k : set (fin n → ℕ)) ⊆ (λ x : fin n → ℕ, (pi_Lp.equiv 2 _).symm (coe ∘ x : fin n → ℝ)) ⁻¹' metric.sphere (0 : pi_Lp 2 (λ _ : fin n, ℝ)) (sqrt k) := λ x hx, by rw [set.mem_preimage, mem_sphere_zero_iff_norm, norm_of_mem_sphere hx] /-- The map that appears in Behrend's bound on Roth numbers. -/ @[simps] def map (d : ℕ) : (fin n → ℕ) →+ ℕ := { to_fun := λ a, ∑ i, a i * d ^ (i : ℕ), map_zero' := by simp_rw [pi.zero_apply, zero_mul, sum_const_zero], map_add' := λ a b, by simp_rw [pi.add_apply, add_mul, sum_add_distrib] } @[simp] lemma map_zero (d : ℕ) (a : fin 0 → ℕ) : map d a = 0 := by simp [map] lemma map_succ (a : fin (n + 1) → ℕ) : map d a = a 0 + (∑ x : fin n, a x.succ * d ^ (x : ℕ)) * d := by simp [map, fin.sum_univ_succ, pow_succ', ←mul_assoc, ←sum_mul] lemma map_succ' (a : fin (n + 1) → ℕ) : map d a = a 0 + map d (a ∘ fin.succ) * d := map_succ _ lemma map_monotone (d : ℕ) : monotone (map d : (fin n → ℕ) → ℕ) := λ x y h, by { dsimp, exact sum_le_sum (λ i _, nat.mul_le_mul_right _ $ h i) } lemma map_mod (a : fin n.succ → ℕ) : map d a % d = a 0 % d := by rw [map_succ, nat.add_mul_mod_self_right] lemma map_eq_iff {x₁ x₂ : fin n.succ → ℕ} (hx₁ : ∀ i, x₁ i < d) (hx₂ : ∀ i, x₂ i < d) : map d x₁ = map d x₂ ↔ x₁ 0 = x₂ 0 ∧ map d (x₁ ∘ fin.succ) = map d (x₂ ∘ fin.succ) := begin refine ⟨λ h, _, λ h, by rw [map_succ', map_succ', h.1, h.2]⟩, have : x₁ 0 = x₂ 0, { rw [←mod_eq_of_lt (hx₁ _), ←map_mod, ←mod_eq_of_lt (hx₂ _), ←map_mod, h] }, rw [map_succ, map_succ, this, add_right_inj, mul_eq_mul_right_iff] at h, exact ⟨this, h.resolve_right (pos_of_gt (hx₁ 0)).ne'⟩, end lemma map_inj_on : {x : fin n → ℕ | ∀ i, x i < d}.inj_on (map d) := begin intros x₁ hx₁ x₂ hx₂ h, induction n with n ih, { simp }, ext i, have x := (map_eq_iff hx₁ hx₂).1 h, refine fin.cases x.1 (congr_fun $ ih (λ _, _) (λ _, _) x.2) i, { exact hx₁ _ }, { exact hx₂ _ } end lemma map_le_of_mem_box (hx : x ∈ box n d) : map (2 * d - 1) x ≤ ∑ i : fin n, (d - 1) * (2 * d - 1) ^ (i : ℕ) := map_monotone (2 * d - 1) $ λ _, nat.le_pred_of_lt $ mem_box.1 hx _ lemma add_salem_spencer_sphere : add_salem_spencer (sphere n d k : set (fin n → ℕ)) := begin set f : (fin n → ℕ) →+ euclidean_space ℝ (fin n) := { to_fun := λ f, (coe : ℕ → ℝ) ∘ f, map_zero' := funext $ λ _, cast_zero, map_add' := λ _ _, funext $ λ _, cast_add _ _ }, refine add_salem_spencer.of_image (f.to_add_freiman_hom (sphere n d k) 2) _ _, { exact cast_injective.comp_left.inj_on _ }, refine (add_salem_spencer_sphere 0 $ sqrt k).mono (set.image_subset_iff.2 $ λ x, _), rw [set.mem_preimage, mem_sphere_zero_iff_norm], exact norm_of_mem_sphere, end lemma add_salem_spencer_image_sphere : add_salem_spencer ((sphere n d k).image (map (2 * d - 1)) : set ℕ) := begin rw coe_image, refine @add_salem_spencer.image _ (fin n → ℕ) ℕ _ _ (sphere n d k) _ (map (2 * d - 1)) (map_inj_on.mono _) add_salem_spencer_sphere, rw set.add_subset_iff, rintro a ha b hb i, have hai := mem_box.1 (sphere_subset_box ha) i, have hbi := mem_box.1 (sphere_subset_box hb) i, rw [lt_tsub_iff_right, ←succ_le_iff, two_mul], exact (add_add_add_comm _ _ 1 1).trans_le (add_le_add hai hbi), end lemma sum_sq_le_of_mem_box (hx : x ∈ box n d) : ∑ i : fin n, (x i)^2 ≤ n * (d - 1)^2 := begin rw mem_box at hx, have : ∀ i, x i ^ 2 ≤ (d - 1) ^ 2 := λ i, nat.pow_le_pow_of_le_left (nat.le_pred_of_lt (hx i)) _, exact (sum_le_card_nsmul univ _ _ $ λ i _, this i).trans (by rw [card_fin, smul_eq_mul]), end lemma sum_eq : ∑ i : fin n, d * (2 * d + 1) ^ (i : ℕ) = ((2 * d + 1) ^ n - 1) / 2 := begin refine (nat.div_eq_of_eq_mul_left zero_lt_two _).symm, rw [←sum_range (λ i, d * (2 * d + 1) ^ (i : ℕ)), ←mul_sum, mul_right_comm, mul_comm d, ←geom_sum_mul_add, add_tsub_cancel_right, mul_comm], end lemma sum_lt : ∑ i : fin n, d * (2 * d + 1) ^ (i : ℕ) < (2 * d + 1) ^ n := sum_eq.trans_lt $ (nat.div_le_self _ 2).trans_lt $ pred_lt (pow_pos (succ_pos _) _).ne' lemma card_sphere_le_roth_number_nat (n d k : ℕ) : (sphere n d k).card ≤ roth_number_nat ((2 * d - 1) ^ n) := begin cases n, { refine (card_le_univ _).trans_eq _, rw pow_zero, exact fintype.card_unique }, cases d, { simp }, refine add_salem_spencer_image_sphere.le_roth_number_nat _ _ (card_image_of_inj_on _), { simp only [subset_iff, mem_image, and_imp, forall_exists_index, mem_range, forall_apply_eq_imp_iff₂, sphere, mem_filter], rintro _ x hx _ rfl, exact (map_le_of_mem_box hx).trans_lt sum_lt }, refine map_inj_on.mono (λ x, _), simp only [mem_coe, sphere, mem_filter, mem_box, and_imp, two_mul], exact λ h _ i, (h i).trans_le le_self_add, end end behrend
06e225a8196bcd4e498c0fdd76e491868311b1bf
8b0adce7bd4e8e06a22dbf65d3ef29169133227b
/inClassNotes/04_type_library/option_test.lean
a39fd6d63166a8fc06293bff6fe407666f0b11ae
[]
no_license
parvahujauva/complogic-s21
5420bce9c456cd9dafcb4965719d2e45fb53437a
ba8d38bfb9000420e0051bc07195026b0e39a29c
refs/heads/master
1,677,682,663,658
1,613,232,309,000
1,613,232,309,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,017
lean
/- The nat type in Lean is defined just as it is in our nat.lean file, so we just use Lean's definition here. For reference, here's Lean's definition. inductive nat : Type | zero : nat | succ : nat → nat That's it. To fully understand how this definition produces a set of terms that we can view interpret as representing natural numbers, you need a few facts: (1) Constructors are *disjoint*. This means that terms built using different constructors are never equal. (2) Constructors are *injective*. This means that even if you use the same contructor, as long as you provide different argument values, you will always get terms that are not equal. (3) The values of a type include all values obtainable by any finite number of applications of its constructors. -/ #print nat /- The key to writing functions that take nat arguments is, as usual, case analysis. If we're given a natural number (term of type ℕ), n, we first determine which constructor was used to create it (zero or succ), and if it was succ, then what one-smaller nat value succ was applied to to produce our argument. -/ /- Zero. Zero is the smallest natural number. It is implemented by the zero constructor. -/ #eval nat.zero /- Successor. The successor function takes a nat and yields a one-bigger nat. It is implemented by the succ constructor. This constructor takes a term of type nat as an argument and constructs/returns a new term with one additional "succ" at its front. -/ #eval nat.succ nat.zero /- Predecessor. Here we define a truncated version of the predecessor function on natural numbers, defined mathematically by the following cases: pred 0 = 0, pred (n' + 1) = n' -/ def pred : ℕ → ℕ | nat.zero := nat.zero | (nat.succ n') := n' #eval pred 0 #eval pred 1 #eval pred 5 /- We can easily write a predicate function that returns true iff its argument is zero. -/ def isZero : ℕ → bool | nat.zero := tt | _ := ff /- Because larger values of type nat are constructed from smaller values of the same type, many functions that consume a nat argument will work by applying themselves recursively to smaller values of the same type. Here's an easy example. We can define a function, double, that takes a nat argument and returns double its value, recursively, like this: double 0 = 0 double (1 + n') = 2 + double n' -/ def double : ℕ → ℕ | nat.zero := 0 -- 0 is nat.zero | (nat.succ n') := 2 + double n' /- Weird detail: In this example, we take advantage of Lean's notations for natural numbers. We can use the usual numerals (0 instead of nat.zero for example); and Lean "de-sugars" (n'+ 1) to nat.succ n', but this trick doesn't work for 1 + n'. -/ /- Exercise. Implement the factorial function on natural numbers, defined by the following cases: fac 0 := 1 fac (n' + 1) := fac (n' + 1) * fac n' -/ -- Ans: def fac : ℕ → ℕ | 0 := 1 | (nat.succ n') := (nat.succ n') * fac n' /- Exercise: Define the n'th Fibonacci number by the following cases: fib 0 = 1 fib 1 = 1 fib (n' + 2) = fib (n' +1) + fib n' -/ -- Ans, now using some Lean notations def fib : ℕ → ℕ | 0 := 1 | 1 := 1 | (n' + 2) := fib (n' + 1) + fib n' #eval fib 5 /- Exercise: On a piece of paper, draw the complete computation tree for fib 5. fib 5 / \ fib 4 fib 3 / \ /\ ... fib 3 fib 2 / \ /\ ... fib 2 fib 1 / \ /\ ... fib 1 fib 0 | | 1 1 -/ /- Addition: 0 + m = m (n' + 1) + m = (n' + m) + 1 Be sure you understand that! -/ def add : ℕ → ℕ → ℕ | 0 m := m | (n' + 1) m := 1 + (add n' m) /- EXERCISE: write a mathematical definition of multiplication of n by m, then implement it, using your add function if/as necessary to carry out addition. -/ /- EXERCISE: write a mathematical definition of exponentiation and implement it, using your definition of multiplication if/as necessary. -/
382d783dddd23209b39d49b94d68b1befa4538c5
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/degree/lemmas.lean
f9f10db9a956309b85f98fe749a04b730a1cdabf
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
12,622
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.eval /-! # Theory of degrees of polynomials Some of the main results include - `nat_degree_comp_le` : The degree of the composition is at most the product of degrees -/ noncomputable theory open_locale classical polynomial open finsupp finset namespace polynomial universes u v w variables {R : Type u} {S : Type v} { ι : Type w} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} section degree lemma nat_degree_comp_le : nat_degree (p.comp q) ≤ nat_degree p * nat_degree q := if h0 : p.comp q = 0 then by rw [h0, nat_degree_zero]; exact nat.zero_le _ else with_bot.coe_le_coe.1 $ calc ↑(nat_degree (p.comp q)) = degree (p.comp q) : (degree_eq_nat_degree h0).symm ... = _ : congr_arg degree comp_eq_sum_left ... ≤ _ : degree_sum_le _ _ ... ≤ _ : finset.sup_le (λ n hn, calc degree (C (coeff p n) * q ^ n) ≤ degree (C (coeff p n)) + degree (q ^ n) : degree_mul_le _ _ ... ≤ nat_degree (C (coeff p n)) + n • (degree q) : add_le_add degree_le_nat_degree (degree_pow_le _ _) ... ≤ nat_degree (C (coeff p n)) + n • (nat_degree q) : add_le_add_left (nsmul_le_nsmul_of_le_right (@degree_le_nat_degree _ _ q) n) _ ... = (n * nat_degree q : ℕ) : by rw [nat_degree_C, with_bot.coe_zero, zero_add, ← with_bot.coe_nsmul, nsmul_eq_mul]; simp ... ≤ (nat_degree p * nat_degree q : ℕ) : with_bot.coe_le_coe.2 $ mul_le_mul_of_nonneg_right (le_nat_degree_of_ne_zero (mem_support_iff.1 hn)) (nat.zero_le _)) lemma degree_pos_of_root {p : R[X]} (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, simp only [h, ring_hom.map_zero] at this, exact hp this, end lemma nat_degree_le_iff_coeff_eq_zero : p.nat_degree ≤ n ↔ ∀ N : ℕ, n < N → p.coeff N = 0 := by simp_rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero, with_bot.coe_lt_coe] lemma nat_degree_add_le_iff_left {n : ℕ} (p q : R[X]) (qn : q.nat_degree ≤ n) : (p + q).nat_degree ≤ n ↔ p.nat_degree ≤ n := begin refine ⟨λ h, _, λ h, nat_degree_add_le_of_degree_le h qn⟩, refine nat_degree_le_iff_coeff_eq_zero.mpr (λ m hm, _), convert nat_degree_le_iff_coeff_eq_zero.mp h m hm using 1, rw [coeff_add, nat_degree_le_iff_coeff_eq_zero.mp qn _ hm, add_zero], end lemma nat_degree_add_le_iff_right {n : ℕ} (p q : R[X]) (pn : p.nat_degree ≤ n) : (p + q).nat_degree ≤ n ↔ q.nat_degree ≤ n := begin rw add_comm, exact nat_degree_add_le_iff_left _ _ pn, end lemma nat_degree_C_mul_le (a : R) (f : R[X]) : (C a * f).nat_degree ≤ f.nat_degree := calc (C a * f).nat_degree ≤ (C a).nat_degree + f.nat_degree : nat_degree_mul_le ... = 0 + f.nat_degree : by rw nat_degree_C a ... = f.nat_degree : zero_add _ lemma nat_degree_mul_C_le (f : R[X]) (a : R) : (f * C a).nat_degree ≤ f.nat_degree := calc (f * C a).nat_degree ≤ f.nat_degree + (C a).nat_degree : nat_degree_mul_le ... = f.nat_degree + 0 : by rw nat_degree_C a ... = f.nat_degree : add_zero _ lemma eq_nat_degree_of_le_mem_support (pn : p.nat_degree ≤ n) (ns : n ∈ p.support) : p.nat_degree = n := le_antisymm pn (le_nat_degree_of_mem_supp _ ns) lemma nat_degree_C_mul_eq_of_mul_eq_one {ai : R} (au : ai * a = 1) : (C a * p).nat_degree = p.nat_degree := le_antisymm (nat_degree_C_mul_le a p) (calc p.nat_degree = (1 * p).nat_degree : by nth_rewrite 0 [← one_mul p] ... = (C ai * (C a * p)).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (C a * p).nat_degree : nat_degree_C_mul_le ai (C a * p)) lemma nat_degree_mul_C_eq_of_mul_eq_one {ai : R} (au : a * ai = 1) : (p * C a).nat_degree = p.nat_degree := le_antisymm (nat_degree_mul_C_le p a) (calc p.nat_degree = (p * 1).nat_degree : by nth_rewrite 0 [← mul_one p] ... = ((p * C a) * C ai).nat_degree : by rw [← C_1, ← au, ring_hom.map_mul, ← mul_assoc] ... ≤ (p * C a).nat_degree : nat_degree_mul_C_le (p * C a) ai) /-- Although not explicitly stated, the assumptions of lemma `nat_degree_mul_C_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_mul_C_eq_of_mul_ne_zero (h : p.leading_coeff * a ≠ 0) : (p * C a).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_mul_C_le p a) _, refine mem_support_iff.mpr _, rwa coeff_mul_C, end /-- Although not explicitly stated, the assumptions of lemma `nat_degree_C_mul_eq_of_mul_ne_zero` force the polynomial `p` to be non-zero, via `p.leading_coeff ≠ 0`. -/ lemma nat_degree_C_mul_eq_of_mul_ne_zero (h : a * p.leading_coeff ≠ 0) : (C a * p).nat_degree = p.nat_degree := begin refine eq_nat_degree_of_le_mem_support (nat_degree_C_mul_le a p) _, refine mem_support_iff.mpr _, rwa coeff_C_mul, end lemma nat_degree_add_coeff_mul (f g : R[X]) : (f * g).coeff (f.nat_degree + g.nat_degree) = f.coeff f.nat_degree * g.coeff g.nat_degree := by simp only [coeff_nat_degree, coeff_mul_degree_add_degree] lemma nat_degree_lt_coeff_mul (h : p.nat_degree + q.nat_degree < m + n) : (p * q).coeff (m + n) = 0 := coeff_eq_zero_of_nat_degree_lt (nat_degree_mul_le.trans_lt h) lemma coeff_mul_of_nat_degree_le (pm : p.nat_degree ≤ m) (qn : q.nat_degree ≤ n) : (p * q).coeff (m + n) = p.coeff m * q.coeff n := begin rcases eq_or_lt_of_le pm with rfl | hm; rcases eq_or_lt_of_le qn with rfl | hn, { exact nat_degree_add_coeff_mul _ _ }, { rw [coeff_eq_zero_of_nat_degree_lt hn, mul_zero], exact nat_degree_lt_coeff_mul (add_lt_add_left hn _) }, { rw [coeff_eq_zero_of_nat_degree_lt hm, zero_mul], exact nat_degree_lt_coeff_mul (add_lt_add_right hm _) }, { rw [coeff_eq_zero_of_nat_degree_lt hn, mul_zero], exact nat_degree_lt_coeff_mul (add_lt_add hm hn) }, end lemma coeff_pow_of_nat_degree_le (pn : p.nat_degree ≤ n) : (p ^ m).coeff (n * m) = (p.coeff n) ^ m := begin induction m with m hm, { simp }, { rw [pow_succ', pow_succ', ← hm, nat.mul_succ, coeff_mul_of_nat_degree_le _ pn], refine nat_degree_pow_le.trans (le_trans _ (mul_comm _ _).le), exact mul_le_mul_of_nonneg_left pn m.zero_le } end lemma coeff_add_eq_left_of_lt (qn : q.nat_degree < n) : (p + q).coeff n = p.coeff n := (coeff_add _ _ _).trans $ (congr_arg _ $ coeff_eq_zero_of_nat_degree_lt $ qn).trans $ add_zero _ lemma coeff_add_eq_right_of_lt (pn : p.nat_degree < n) : (p + q).coeff n = q.coeff n := by { rw add_comm, exact coeff_add_eq_left_of_lt pn } lemma degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (degree ∘ f))) : degree (s.sum f) = s.sup (λ i, degree (f i)) := begin induction s using finset.induction_on with x s hx IH, { simp }, { simp only [hx, finset.sum_insert, not_false_iff, finset.sup_insert], specialize IH (h.mono (λ _, by simp {contextual := tt})), rcases lt_trichotomy (degree (f x)) (degree (s.sum f)) with H|H|H, { rw [←IH, sup_eq_right.mpr H.le, degree_add_eq_right_of_degree_lt H] }, { rcases s.eq_empty_or_nonempty with rfl|hs, { simp }, obtain ⟨y, hy, hy'⟩ := finset.exists_mem_eq_sup s hs (λ i, degree (f i)), rw [IH, hy'] at H, by_cases hx0 : f x = 0, { simp [hx0, IH] }, have hy0 : f y ≠ 0, { contrapose! H, simpa [H, degree_eq_bot] using hx0 }, refine absurd H (h _ _ (λ H, hx _)), { simp [hx0] }, { simp [hy, hy0] }, { exact H.symm ▸ hy } }, { rw [←IH, sup_eq_left.mpr H.le, degree_add_eq_left_of_degree_lt H] } } end lemma nat_degree_sum_eq_of_disjoint (f : S → R[X]) (s : finset S) (h : set.pairwise { i | i ∈ s ∧ f i ≠ 0 } (ne on (nat_degree ∘ f))) : nat_degree (s.sum f) = s.sup (λ i, nat_degree (f i)) := begin by_cases H : ∃ x ∈ s, f x ≠ 0, { obtain ⟨x, hx, hx'⟩ := H, have hs : s.nonempty := ⟨x, hx⟩, refine nat_degree_eq_of_degree_eq_some _, rw degree_sum_eq_of_disjoint, { rw [←finset.sup'_eq_sup hs, ←finset.sup'_eq_sup hs, finset.coe_sup', ←finset.sup'_eq_sup hs], refine le_antisymm _ _, { rw finset.sup'_le_iff, intros b hb, by_cases hb' : f b = 0, { simpa [hb'] using hs }, rw degree_eq_nat_degree hb', exact finset.le_sup' _ hb }, { rw finset.sup'_le_iff, intros b hb, simp only [finset.le_sup'_iff, exists_prop, function.comp_app], by_cases hb' : f b = 0, { refine ⟨x, hx, _⟩, contrapose! hx', simpa [hb', degree_eq_bot] using hx' }, exact ⟨b, hb, (degree_eq_nat_degree hb').ge⟩ } }, { exact h.imp (λ x y hxy hxy', hxy (nat_degree_eq_of_degree_eq hxy')) } }, { push_neg at H, rw [finset.sum_eq_zero H, nat_degree_zero, eq_comm, show 0 = ⊥, from rfl, finset.sup_eq_bot_iff], intros x hx, simp [H x hx] } end lemma nat_degree_bit0 (a : R[X]) : (bit0 a).nat_degree ≤ a.nat_degree := (nat_degree_add_le _ _).trans (max_self _).le lemma nat_degree_bit1 (a : R[X]) : (bit1 a).nat_degree ≤ a.nat_degree := (nat_degree_add_le _ _).trans (by simp [nat_degree_bit0]) variables [semiring S] lemma nat_degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < nat_degree p := lt_of_not_ge $ λ hlt, begin have A : p = C (p.coeff 0) := eq_C_of_nat_degree_le_zero hlt, rw [A, eval₂_C] at hz, simp only [inj (p.coeff 0) hz, ring_hom.map_zero] at A, exact hp A end lemma degree_pos_of_eval₂_root {p : R[X]} (hp : p ≠ 0) (f : R →+* S) {z : S} (hz : eval₂ f z p = 0) (inj : ∀ (x : R), f x = 0 → x = 0) : 0 < degree p := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_eval₂_root hp f hz inj) @[simp] lemma coe_lt_degree {p : R[X]} {n : ℕ} : ((n : with_bot ℕ) < degree p) ↔ n < nat_degree p := begin by_cases h : p = 0, { simp [h] }, rw [degree_eq_nat_degree h, with_bot.coe_lt_coe], end end degree end semiring section ring variables [ring R] {p q : R[X]} lemma nat_degree_sub : (p - q).nat_degree = (q - p).nat_degree := by rw [← nat_degree_neg, neg_sub] lemma nat_degree_sub_le_iff_left (qn : q.nat_degree ≤ n) : (p - q).nat_degree ≤ n ↔ p.nat_degree ≤ n := begin rw ← nat_degree_neg at qn, rw [sub_eq_add_neg, nat_degree_add_le_iff_left _ _ qn], end lemma nat_degree_sub_le_iff_right (pn : p.nat_degree ≤ n) : (p - q).nat_degree ≤ n ↔ q.nat_degree ≤ n := by rwa [nat_degree_sub, nat_degree_sub_le_iff_left] lemma coeff_sub_eq_left_of_lt (dg : q.nat_degree < n) : (p - q).coeff n = p.coeff n := begin rw ← nat_degree_neg at dg, rw [sub_eq_add_neg, coeff_add_eq_left_of_lt dg], end lemma coeff_sub_eq_neg_right_of_lt (df : p.nat_degree < n) : (p - q).coeff n = - q.coeff n := by rwa [sub_eq_add_neg, coeff_add_eq_right_of_lt, coeff_neg] end ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} lemma degree_mul_C (a0 : a ≠ 0) : (p * C a).degree = p.degree := by rw [degree_mul, degree_C a0, add_zero] lemma degree_C_mul (a0 : a ≠ 0) : (C a * p).degree = p.degree := by rw [degree_mul, degree_C a0, zero_add] lemma nat_degree_mul_C (a0 : a ≠ 0) : (p * C a).nat_degree = p.nat_degree := by simp only [nat_degree, degree_mul_C a0] lemma nat_degree_C_mul (a0 : a ≠ 0) : (C a * p).nat_degree = p.nat_degree := by simp only [nat_degree, degree_C_mul a0] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := begin by_cases q0 : q.nat_degree = 0, { rw [degree_le_zero_iff.mp (nat_degree_eq_zero_iff_degree_le_zero.mp q0), comp_C, nat_degree_C, nat_degree_C, mul_zero] }, { by_cases p0 : p = 0, { simp only [p0, zero_comp, nat_degree_zero, zero_mul] }, refine le_antisymm nat_degree_comp_le (le_nat_degree_of_ne_zero _), simp only [coeff_comp_degree_mul_degree q0, p0, mul_eq_zero, leading_coeff_eq_zero, or_self, ne_zero_of_nat_degree_gt (nat.pos_of_ne_zero q0), pow_ne_zero, ne.def, not_false_iff] } end lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) = leading_coeff p * leading_coeff q ^ nat_degree p := by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp, coeff_nat_degree] end no_zero_divisors end polynomial
51fd4e54f49abff9990a125ca9dca0d17031d18e
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/real/cau_seq_completion.lean
c0a9f7d2c86968b9035b71987f923ff668bf03b5
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,166
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis -/ import data.real.cau_seq /-! # Cauchy completion This file generalizes the Cauchy completion of `(ℚ, abs)` to the completion of a commutative ring with absolute value. -/ namespace cau_seq.completion open cau_seq section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] /-- The Cauchy completion of a commutative ring with absolute value. -/ def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv /-- The map from Cauchy sequences into the Cauchy completion. -/ def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq /-- The map from the original ring into the Cauchy completion. -/ def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm, add_assoc] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [neg_sub', (≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, add_assoc, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl instance : has_sub Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f - g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ show ((f₁ - g₁) - (f₂ - g₂)).lim_zero, by simpa [sub_eq_add_neg, add_assoc, add_comm, add_left_comm] using sub_lim_zero hf hg⟩ @[simp] theorem mk_sub (f g : cau_seq β abv) : mk f - mk g = mk (f - g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : add_group Cauchy := by refine { add := (+), zero := (0 : Cauchy), sub := has_sub.sub, neg := has_neg.neg, sub_eq_add_neg := _, nsmul := nsmul_rec, zsmul := zsmul_rec, .. }; try { intros; refl }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, add_comm, add_left_comm, sub_eq_neg_add] } instance : add_group_with_one Cauchy := { nat_cast := λ n, mk n, nat_cast_zero := congr_arg mk nat.cast_zero, nat_cast_succ := λ n, congr_arg mk (nat.cast_succ n), int_cast := λ n, mk n, int_cast_of_nat := λ n, congr_arg mk (int.cast_of_nat n), int_cast_neg_succ_of_nat := λ n, congr_arg mk (int.cast_neg_succ_of_nat n), one := 1, .. Cauchy.add_group } instance : comm_ring Cauchy := by refine { add := (+), zero := (0 : Cauchy), mul := (*), one := 1, npow := npow_rec, .. Cauchy.add_group_with_one, .. }; try { intros; refl }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm, sub_eq_add_neg] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end /-- The Cauchy completion forms a field. See note [reducible non-instances]. -/ @[reducible] noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], exists_pair_ne := ⟨0, 1, zero_ne_one⟩, inv_zero := inv_zero, .. Cauchy.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; [simp [const_lim_zero.1 h], refl] theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] /-- A class stating that a ring with an absolute value is complete, i.e. every Cauchy sequence has a limit. -/ class is_complete : Prop := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete /-- The limit of a Cauchy sequence in a complete ring. Chosen non-computably. -/ noncomputable def lim (s : cau_seq β abv) : β := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_add_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm, ← sub_eq_add_neg]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
44dd8a2a110b38b5aadd47220fbf3f0ef5dac1f8
7cef822f3b952965621309e88eadf618da0c8ae9
/src/tactic/rewrite.lean
999a97888bc63764655621415b03a2fc706d300e
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
7,345
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 data.dlist tactic.core namespace tactic open expr list meta def match_fn (fn : expr) : expr → tactic (expr × expr) | (app (app fn' e₀) e₁) := unify fn fn' $> (e₀, e₁) | _ := failed meta def fill_args : expr → tactic (expr × list expr) | (pi n bi d b) := do v ← mk_meta_var d, (r, vs) ← fill_args (b.instantiate_var v), return (r, v::vs) | e := return (e, []) meta def mk_assoc_pattern' (fn : expr) : expr → tactic (dlist expr) | e := (do (e₀, e₁) ← match_fn fn e, (++) <$> mk_assoc_pattern' e₀ <*> mk_assoc_pattern' e₁) <|> pure (dlist.singleton e) meta def mk_assoc_pattern (fn e : expr) : tactic (list expr) := dlist.to_list <$> mk_assoc_pattern' fn e meta def mk_assoc (fn : expr) : list expr → tactic expr | [] := failed | [x] := pure x | (x₀ :: x₁ :: xs) := mk_assoc (fn x₀ x₁ :: xs) meta def chain_eq_trans : list expr → tactic expr | [] := to_expr ``(rfl) | [e] := pure e | (e :: es) := chain_eq_trans es >>= mk_eq_trans e meta def unify_prefix : list expr → list expr → tactic unit | [] _ := pure () | _ [] := failed | (x :: xs) (y :: ys) := unify x y >> unify_prefix xs ys meta def match_assoc_pattern' (p : list expr) : list expr → tactic (list expr × list expr) | es := unify_prefix p es $> ([], es.drop p.length) <|> match es with | [] := failed | (x :: xs) := prod.map (cons x) id <$> match_assoc_pattern' xs end meta def match_assoc_pattern (fn p e : expr) : tactic (list expr × list expr) := do p' ← mk_assoc_pattern fn p, e' ← mk_assoc_pattern fn e, match_assoc_pattern' p' e' meta def mk_eq_proof (fn : expr) (e₀ e₁ : list expr) (p : expr) : tactic (expr × expr × expr) := do (l, r) ← infer_type p >>= match_eq, if e₀.empty ∧ e₁.empty then pure (l, r, p) else do l' ← mk_assoc fn (e₀ ++ [l] ++ e₁), r' ← mk_assoc fn (e₀ ++ [r] ++ e₁), t ← infer_type l', v ← mk_local_def `x t, e ← mk_assoc fn (e₀ ++ [v] ++ e₁), p ← mk_congr_arg (e.lambdas [v]) p, p' ← mk_id_eq l' r' p, return (l', r', p') meta def assoc_root (fn assoc : expr) : expr → tactic (expr × expr) | e := (do (e₀, e₁) ← match_fn fn e, (ea, eb) ← match_fn fn e₁, let e' := fn (fn e₀ ea) eb, p' ← mk_eq_symm (assoc e₀ ea eb), (e'', p'') ← assoc_root e', prod.mk e'' <$> mk_eq_trans p' p'') <|> prod.mk e <$> mk_eq_refl e meta def assoc_refl' (fn assoc : expr) : expr → expr → tactic expr | l r := (is_def_eq l r >> mk_eq_refl l) <|> do (l', l_p) ← assoc_root fn assoc l <|> fail "A", (el₀, el₁) ← match_fn fn l' <|> fail "B", (r', r_p) ← assoc_root fn assoc r <|> fail "C", (er₀, er₁) ← match_fn fn r' <|> fail "D", p₀ ← assoc_refl' el₀ er₀, p₁ ← is_def_eq el₁ er₁ >> mk_eq_refl el₁, f_eq ← mk_congr_arg fn p₀ <|> fail "G", p' ← mk_congr f_eq p₁ <|> fail "H", r_p' ← mk_eq_symm r_p, chain_eq_trans [l_p, p', r_p'] meta def assoc_refl (fn : expr) : tactic unit := do (l, r) ← target >>= match_eq, assoc ← mk_mapp ``is_associative.assoc [none, fn, none] <|> fail format!"{fn} is not associative", assoc_refl' fn assoc l r >>= tactic.exact meta def flatten (fn assoc e : expr) : tactic (expr × expr) := do ls ← mk_assoc_pattern fn e, e' ← mk_assoc fn ls, p ← assoc_refl' fn assoc e e', return (e', p) meta def assoc_rewrite_intl (assoc h e : expr) : tactic (expr × expr) := do t ← infer_type h, (lhs, rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, (l, r) ← match_assoc_pattern fn lhs e, (lhs', rhs', h') ← mk_eq_proof fn l r h, e_p ← assoc_refl' fn assoc e lhs', (rhs'', rhs_p) ← flatten fn assoc rhs', final_p ← chain_eq_trans [e_p, h', rhs_p], return (rhs'', final_p) -- TODO(Simon): visit expressions built of `fn` nested inside other such expressions: -- e.g.: x + f (a + b + c) + y should generate two rewrite candidates meta def enum_assoc_subexpr' (fn : expr) : expr → tactic (dlist expr) | e := dlist.singleton e <$ (match_fn fn e >> guard (¬ e.has_var)) <|> expr.mfoldl (λ es e', (++ es) <$> enum_assoc_subexpr' e') dlist.empty e meta def enum_assoc_subexpr (fn e : expr) : tactic (list expr) := dlist.to_list <$> enum_assoc_subexpr' fn e meta def mk_assoc_instance (fn : expr) : tactic expr := do t ← mk_mapp ``is_associative [none, fn], inst ← prod.snd <$> solve_aux t assumption <|> (mk_instance t >>= assertv `_inst t) <|> fail format!"{fn} is not associative", mk_mapp ``is_associative.assoc [none, fn, inst] meta def assoc_rewrite (h e : expr) (opt_assoc : option expr := none) : tactic (expr × expr × list expr) := do (t, vs) ← infer_type h >>= fill_args, (lhs, rhs) ← match_eq t, let fn := lhs.app_fn.app_fn, es ← enum_assoc_subexpr fn e, assoc ← match opt_assoc with | none := mk_assoc_instance fn | (some assoc) := pure assoc end, (_, p) ← mfirst (assoc_rewrite_intl assoc $ h.mk_app vs) es, (e', p', _) ← tactic.rewrite p e, pure (e', p', vs) meta def assoc_rewrite_target (h : expr) (opt_assoc : option expr := none) : tactic unit := do tgt ← target, (tgt', p, _) ← assoc_rewrite h tgt opt_assoc, replace_target tgt' p meta def assoc_rewrite_hyp (h hyp : expr) (opt_assoc : option expr := none) : tactic expr := do tgt ← infer_type hyp, (tgt', p, _) ← assoc_rewrite h tgt opt_assoc, replace_hyp hyp tgt' p namespace interactive open lean.parser interactive interactive.types tactic private meta def assoc_rw_goal (rs : list rw_rule) : tactic unit := rs.mmap' $ λ r, do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, assoc_rewrite_target e) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_target e) (eq_lemmas.empty) private meta def uses_hyp (e : expr) (h : expr) : bool := e.fold ff $ λ t _ r, r || (t = h) private meta def assoc_rw_hyp : list rw_rule → expr → tactic unit | [] hyp := skip | (r::rs) hyp := do save_info r.pos, eq_lemmas ← get_rule_eqn_lemmas r, orelse' (do e ← to_expr' r.rule, when (¬ uses_hyp e hyp) $ assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.mfirst $ λ n, do e ← mk_const n, assoc_rewrite_hyp e hyp >>= assoc_rw_hyp rs) (eq_lemmas.empty) private meta def assoc_rw_core (rs : parse rw_rules) (loca : parse location) : tactic unit := match loca with | loc.wildcard := loca.try_apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) | _ := loca.apply (assoc_rw_hyp rs.rules) (assoc_rw_goal rs.rules) end >> try reflexivity >> try (returnopt rs.end_pos >>= save_info) /-- `assoc_rewrite [h₀,← h₁] at ⊢ h₂` behaves like `rewrite [h₀,← h₁] at ⊢ h₂` with the exception that associativity is used implicitly to make rewriting possible. -/ meta def assoc_rewrite (q : parse rw_rules) (l : parse location) : tactic unit := propagate_tags (assoc_rw_core q l) /-- synonym for `assoc_rewrite` -/ meta def assoc_rw (q : parse rw_rules) (l : parse location) : tactic unit := assoc_rewrite q l end interactive end tactic
ade1b86fede8e86bf0aa741f32db6c923d12e863
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/local_homeomorph.lean
c1e6159edd901de24ef30a866985714665d330c9
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
47,444
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 data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open function set filter topological_space (second_countable_topology) open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) (λ _, α → β) := ⟨λ e, e.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (e : local_homeomorph α β) : α → β := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_homeomorph α β) : β → α := e.symm initialize_simps_projections local_homeomorph (to_local_equiv_to_fun → apply, to_local_equiv_inv_fun → symm_apply, to_local_equiv_source → source, to_local_equiv_target → target, -to_local_equiv) protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Replace `to_local_equiv` field to provide better definitional equalities. -/ def replace_equiv (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : local_homeomorph α β := { to_local_equiv := e', open_source := h ▸ e.open_source, open_target := h ▸ e.open_target, continuous_to_fun := h ▸ e.continuous_to_fun, continuous_inv_fun := h ▸ e.continuous_inv_fun } lemma replace_equiv_eq_self (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : e.replace_equiv e' h = e := by { cases e, subst e', refl } lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[{x}ᶜ] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma nhds_within_source_inter {x} (hx : x ∈ e.source) (s : set α) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhds_within_inter_of_mem (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds e.open_source hx) lemma nhds_within_target_inter {x} (hx : x ∈ e.target) (s : set β) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhds_within_source_inter hx s lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_source_inter_eq' s lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.to_local_equiv.image_source_inter_eq s lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.to_local_equiv.source_inter_preimage_inv_preimage s lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_equiv.source_inter_preimage_target_inter s /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (is_open.mem_nhds e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs lemma map_nhds_within_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set α) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] (e x) := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) : congr_arg (map e) (e.nhds_within_source_inter hx _).symm ... = 𝓝[e '' (e.source ∩ s)] (e x) : (e.left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq (e.left_inv hx) (e.continuous_at_symm (e.map_source hx)).continuous_within_at (e.continuous_at hx).continuous_within_at lemma map_nhds_within_preimage_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set β) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] (e x) := by rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhds_within_target_inter (e.map_source hx)] lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs /-! ### `local_homeomorph.is_image` relation We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). This definition is a restatement of `local_equiv.is_image` for local homeomorphisms. In this section we transfer API about `local_equiv.is_image` to local homeomorphisms and add a few `local_homeomorph`-specific lemmas like `local_homeomorph.is_image.closure`. -/ /-- We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma to_local_equiv (h : e.is_image s t) : e.to_local_equiv.is_image s t := h lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.to_local_equiv.symm lemma symm_apply_mem_iff (h : e.is_image s t) (hy : y ∈ e.target) : (e.symm y ∈ s ↔ y ∈ t) := h.symm hy @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := h.to_local_equiv.maps_to lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.to_local_equiv.image_eq lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := local_equiv.is_image.iff_preimage_eq alias iff_preimage_eq ↔ local_homeomorph.is_image.preimage_eq local_homeomorph.is_image.of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ local_homeomorph.is_image.symm_preimage_eq local_homeomorph.is_image.of_symm_preimage_eq lemma iff_symm_preimage_eq' : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' (e.source ∩ s) = e.target ∩ t := by rw [iff_symm_preimage_eq, ← image_source_inter_eq, ← image_source_inter_eq'] alias iff_symm_preimage_eq' ↔ local_homeomorph.is_image.symm_preimage_eq' local_homeomorph.is_image.of_symm_preimage_eq' lemma iff_preimage_eq' : e.is_image s t ↔ e.source ∩ e ⁻¹' (e.target ∩ t) = e.source ∩ s := symm_iff.symm.trans iff_symm_preimage_eq' alias iff_preimage_eq' ↔ local_homeomorph.is_image.preimage_eq' local_homeomorph.is_image.of_preimage_eq' lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := local_equiv.is_image.of_image_eq h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := local_equiv.is_image.of_symm_image_eq h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_homeomorph α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := h.to_local_equiv.left_inv_on_piecewise h' lemma inter_eq_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := h.to_local_equiv.inter_eq_of_inter_eq_of_eq_on h' hs Heq lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := h.to_local_equiv.symm_eq_on_of_inter_eq_of_eq_on hs Heq lemma map_nhds_within_eq (h : e.is_image s t) (hx : x ∈ e.source) : map e (𝓝[s] x) = 𝓝[t] (e x) := by rw [e.map_nhds_within_eq hx, h.image_eq, e.nhds_within_target_inter (e.map_source hx)] protected lemma closure (h : e.is_image s t) : e.is_image (closure s) (closure t) := λ x hx, by simp only [mem_closure_iff_nhds_within_ne_bot, ← h.map_nhds_within_eq hx, map_ne_bot_iff] protected lemma interior (h : e.is_image s t) : e.is_image (interior s) (interior t) := by simpa only [closure_compl, compl_compl] using h.compl.closure.compl protected lemma frontier (h : e.is_image s t) : e.is_image (frontier s) (frontier t) := h.closure.diff h.interior lemma is_open_iff (h : e.is_image s t) : is_open (e.source ∩ s) ↔ is_open (e.target ∩ t) := ⟨λ hs, h.symm_preimage_eq' ▸ e.symm.preimage_open_of_open hs, λ hs, h.preimage_eq' ▸ e.preimage_open_of_open hs⟩ /-- Restrict a `local_homeomorph` to a pair of corresponding open sets. -/ @[simps to_local_equiv] def restr (h : e.is_image s t) (hs : is_open (e.source ∩ s)) : local_homeomorph α β := { to_local_equiv := h.to_local_equiv.restr, open_source := hs, open_target := h.is_open_iff.1 hs, continuous_to_fun := e.continuous_on.mono (inter_subset_left _ _), continuous_inv_fun := e.symm.continuous_on.mono (inter_subset_left _ _) } end is_image lemma is_image_source_target : e.is_image e.source e.target := e.to_local_equiv.is_image_source_target lemma is_image_source_target_of_disjoint (e' : local_homeomorph α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := e.to_local_equiv.is_image_source_target_of_disjoint e'.to_local_equiv hs ht /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := (is_image.of_preimage_eq rfl).interior.preimage_eq lemma preimage_closure (s : set β) : e.source ∩ e ⁻¹' (closure s) = e.source ∩ closure (e ⁻¹' s) := (is_image.of_preimage_eq rfl).closure.preimage_eq lemma preimage_frontier (s : set β) : e.source ∩ e ⁻¹' (frontier s) = e.source ∩ frontier (e ⁻¹' s) := (is_image.of_preimage_eq rfl).frontier.preimage_eq lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (e.source ∩ s)) := image_open_of_open _ (is_open.inter e.open_source hs) (inter_subset_left _ _) /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := (@is_image.of_symm_preimage_eq α β _ _ e s (e.symm ⁻¹' s) rfl).restr (is_open.inter e.open_source hs) @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ @[simps apply symm_apply (mfld_cfg), simps source target {attrs := []}] protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, exact interior_maximal h e.open_source end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq, ← inter_assoc] end /-- The identity on the whole space as a local homeomorphism. -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open.inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ @[simps to_local_equiv apply (mfld_cfg), simps source target symm_apply {attrs := []}] def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := e.continuous_on.prod_map e'.continuous_on, continuous_inv_fun := e.continuous_on_symm.prod_map e'.continuous_on_symm, to_local_equiv := e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans end prod section piecewise /-- Combine two `local_homeomorph`s using `set.piecewise`. The source of the new `local_homeomorph` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. To ensure that the maps `to_fun` and `inv_fun` are inverse of each other on the new `source` and `target`, the definition assumes that the sets `s` and `t` are related both by `e.is_image` and `e'.is_image`. To ensure that the new maps are continuous on `source`/`target`, it also assumes that `e.source` and `e'.source` meet `frontier s` on the same set and `e x = e' x` on this intersection. -/ @[simps to_local_equiv apply {fully_applied := ff}] def piecewise (e e' : local_homeomorph α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : local_homeomorph α β := { to_local_equiv := e.to_local_equiv.piecewise e'.to_local_equiv s t H H', open_source := e.open_source.ite e'.open_source Hs, open_target := e.open_target.ite e'.open_target $ H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq, continuous_to_fun := continuous_on_piecewise_ite e.continuous_on e'.continuous_on Hs Heq, continuous_inv_fun := continuous_on_piecewise_ite e.continuous_on_symm e'.continuous_on_symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) } @[simp] lemma symm_piecewise (e e' : local_homeomorph α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : (e.piecewise e' s t H H' Hs Heq).symm = e.symm.piecewise e'.symm t s H.symm H'.symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) := rfl /-- Combine two `local_homeomorph`s with disjoint sources and disjoint targets. We reuse `local_homeomorph.piecewise` then override `to_local_equiv` to `local_equiv.disjoint_union`. This way we have better definitional equalities for `source` and `target`. -/ def disjoint_union (e e' : local_homeomorph α β) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] (Hs : disjoint e.source e'.source) (Ht : disjoint e.target e'.target) : local_homeomorph α β := (e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint e Hs.symm Ht.symm) (by rw [e.open_source.inter_frontier_eq, e'.open_source.inter_frontier_eq_empty_of_disjoint Hs]) (by { rw e.open_source.inter_frontier_eq, exact eq_on_empty _ _ })).replace_equiv (e.to_local_equiv.disjoint_union e'.to_local_equiv Hs Ht) (local_equiv.disjoint_union_eq_piecewise _ _ _ _).symm end piecewise section pi variables {ι : Type*} [fintype ι] {Xi Yi : ι → Type*} [Π i, topological_space (Xi i)] [Π i, topological_space (Yi i)] (ei : Π i, local_homeomorph (Xi i) (Yi i)) /-- The product of a finite family of `local_homeomorph`s. -/ @[simps to_local_equiv] def pi : local_homeomorph (Π i, Xi i) (Π i, Yi i) := { to_local_equiv := local_equiv.pi (λ i, (ei i).to_local_equiv), open_source := is_open_set_pi finite_univ $ λ i hi, (ei i).open_source, open_target := is_open_set_pi finite_univ $ λ i hi, (ei i).open_target, continuous_to_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial), continuous_inv_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on_symm.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial) } end pi section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [continuous_within_at, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhds_within_preimage_eq (e.map_target h), (∘), e.right_inv h] /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin simp only [← e.symm_image_eq_source_inter_preimage h, continuous_on, ball_image_iff], refine forall_congr (λ x, forall_congr $ λ hx, _), rw [e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuous_within_at_inter], exact is_open.mem_nhds e.open_source (e.map_target (h hx)) end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin refine ⟨(e.continuous_at hx).tendsto.comp, λ fe_cont, _⟩, rw [← continuous_within_at_inter' h] at fe_cont ⊢, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_mem_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := forall_congr $ λ x, forall_congr $ λ hx, e.continuous_within_at_iff_continuous_within_at_comp_left (h hx) (mem_of_superset self_mem_nhds_within h) end continuity /-- A local homeomrphism defines a homeomorphism between its source and target. -/ def to_homeomorph_source_target : e.source ≃ₜ e.target := { to_fun := e.maps_to.restrict _ _ _, inv_fun := e.symm_maps_to.restrict _ _ _, left_inv := λ x, subtype.eq $ e.left_inv x.2, right_inv := λ x, subtype.eq $ e.right_inv x.2, continuous_to_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.continuous_on, continuous_inv_fun := continuous_subtype_mk _ $ continuous_on_iff_continuous_restrict.1 e.symm.continuous_on } lemma second_countable_topology_source [second_countable_topology β] (e : local_homeomorph α β) : second_countable_topology e.source := e.to_homeomorph_source_target.second_countable_topology /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ @[simps apply symm_apply (mfld_cfg)] def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : α ≃ₜ β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : α ≃ₜ β) (e' : β ≃ₜ γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ attribute [simps apply source target {simp_rhs := tt, .. mfld_cfg}] to_local_homeomorph @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ @[simps apply source target (mfld_cfg)] noncomputable def to_local_homeomorph [nonempty α] : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
62fa7ff8d1ab004691405821e03da6807d151c91
46125763b4dbf50619e8846a1371029346f4c3db
/src/algebra/punit_instances.lean
3309000cd32b04eeefb7ba35be798a56212a20cc
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
3,456
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Instances on punit. -/ import algebra.module universes u open lattice namespace punit variables (x y : punit.{u+1}) (s : set punit.{u+1}) @[to_additive add_comm_group] instance : comm_group punit := by refine { mul := λ _ _, star, one := star, inv := λ _, star, .. }; intros; exact subsingleton.elim _ _ instance : comm_ring punit := by refine { .. punit.comm_group, .. punit.add_comm_group, .. }; intros; exact subsingleton.elim _ _ instance : complete_boolean_algebra punit := by refine { le := λ _ _, true, le_antisymm := λ _ _ _ _, subsingleton.elim _ _, lt := λ _ _, false, lt_iff_le_not_le := λ _ _, iff_of_false not_false (λ H, H.2 trivial), top := star, bot := star, sup := λ _ _, star, inf := λ _ _, star, Sup := λ _, star, Inf := λ _, star, sub := λ _ _, star, .. punit.comm_ring, .. }; intros; trivial instance : canonically_ordered_monoid punit := by refine { lt_of_add_lt_add_left := λ _ _ _, id, le_iff_exists_add := λ _ _, iff_of_true _ ⟨star, subsingleton.elim _ _⟩, .. punit.comm_ring, .. punit.lattice.complete_boolean_algebra, .. }; intros; trivial instance : decidable_linear_ordered_cancel_comm_monoid punit := { add_left_cancel := λ _ _ _ _, subsingleton.elim _ _, add_right_cancel := λ _ _ _ _, subsingleton.elim _ _, le_of_add_le_add_left := λ _ _ _ _, trivial, le_total := λ _ _, or.inl trivial, decidable_le := λ _ _, decidable.true, decidable_eq := punit.decidable_eq, decidable_lt := λ _ _, decidable.false, .. punit.canonically_ordered_monoid } instance (R : Type u) [ring R] : module R punit := module.of_core $ by refine { smul := λ _ _, star, .. punit.comm_ring, .. }; intros; exact subsingleton.elim _ _ @[simp] lemma zero_eq : (0 : punit) = star := rfl @[simp, to_additive] lemma one_eq : (1 : punit) = star := rfl @[simp] lemma add_eq : x + y = star := rfl @[simp, to_additive] lemma mul_eq : x * y = star := rfl @[simp] lemma neg_eq : -x = star := rfl @[simp, to_additive] lemma inv_eq : x⁻¹ = star := rfl @[simp] lemma smul_eq : x • y = star := rfl @[simp] lemma top_eq : (⊤ : punit) = star := rfl @[simp] lemma bot_eq : (⊥ : punit) = star := rfl @[simp] lemma sup_eq : x ⊔ y = star := rfl @[simp] lemma inf_eq : x ⊓ y = star := rfl @[simp] lemma Sup_eq : Sup s = star := rfl @[simp] lemma Inf_eq : Inf s = star := rfl @[simp] protected lemma le : x ≤ y := trivial @[simp] lemma not_lt : ¬(x < y) := not_false instance {α : Type*} [has_mul α] (f : α → punit) : is_mul_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [has_add α] (f : α → punit) : is_add_hom f := ⟨λ _ _, subsingleton.elim _ _⟩ instance {α : Type*} [monoid α] (f : α → punit) : is_monoid_hom f := { map_one := subsingleton.elim _ _ } instance {α : Type*} [add_monoid α] (f : α → punit) : is_add_monoid_hom f := { map_zero := subsingleton.elim _ _ } instance {α : Type*} [group α] (f : α → punit) : is_group_hom f := { } instance {α : Type*} [add_group α] (f : α → punit) : is_add_group_hom f := { } instance {α : Type*} [semiring α] (f : α → punit) : is_semiring_hom f := { .. punit.is_monoid_hom f, .. punit.is_add_monoid_hom f } instance {α : Type*} [ring α] (f : α → punit) : is_ring_hom f := { .. punit.is_semiring_hom f } end punit
75f5c8a98d5f312fbe1db8ff4bc1734f02806625
1a2aed113dcb5f1c07ae98040953fba5e6563624
/lean_root/src/scratch.lean
9bff8e89107e01c9a04f812e27bf4eff97ee63a4
[ "Apache-2.0" ]
permissive
kevindoran/lean
61d9fb90363b04587624036136482b29e3c16ebd
77e755095a31e3a214010eb48a61e48d65dfdec9
refs/heads/master
1,670,372,072,769
1,598,920,365,000
1,598,920,365,000
264,824,992
0
0
null
null
null
null
UTF-8
Lean
false
false
1,793
lean
import data.real.basic import data.set namespace my_closure universes u variables {α : Type u} variables P Q Q' : α Prop local notation `|`x`|` := abs x def is_adherent (x : ℝ) (X : set ℝ) : Prop := ∀ ε > 0, ∃y ∈ X, |x - y| < ε def closure(X : set ℝ) : set ℝ := {x : ℝ | is_adherent x X } lemma closure_inter_subset_inter_closure (X Y : set ℝ) : closure (X ∩ Y) ⊆ closure X ∩ closure Y := begin intros a ha, split; { intros ε hε, rcases ha ε hε with ⟨xy, hxy, h₁⟩, use xy, cases hxy, split; assumption, } end lemma closure_inter_subset_inter_closure' (X Y : set ℝ) : closure (X ∩ Y) ⊆ closure X ∩ closure Y := begin intros a ha, split; intros ε hε; rcases ha ε hε with ⟨xy, hxy, h₁⟩; use xy; cases hxy; split; assumption, end lemma universal_impl_distrib {a : α} : (∀ a, P a → Q a ∧ Q' a) ↔ (∀ a, P a → Q a) ∧ (∀ a, P a → Q' a) := iff.intro (assume hl, and.intro (assume a, assume p, and.elim_left (hl a p)) (assume a, assume p, and.elim_right (hl a p))) (assume hr, assume a, assume p, and.intro (and.elim_left hr a p) (and.elim_right hr a p) ) lemma closure_inter_subset_inter_closure'' (X Y : set ℝ) : closure (X ∩ Y) ⊆ closure X ∩ closure Y := begin intros a ha, rw universal_impl_distrib, end lemma closure_inter_subset_inter_closure''' (X Y : set ℝ) : closure (X ∩ Y) ⊆ closure X ∩ closure Y := begin intros a ha, split, { intros ε hε, rcases ha ε hε with ⟨xy, hxy, h₁⟩, use xy, exact ⟨hxy.left, h₁⟩, }, { intros ε hε, rcases ha ε hε with ⟨xy, hxy, h₁⟩, use xy, exact ⟨hxy.right, h₁⟩, } end end my_closure
3f44c766f6c2dda75b30091fffd53ee2e8dae1e3
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/subsemiring/basic.lean
90dc42f73b607870e5fa43153412259437d333ee
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
42,563
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import algebra.module.basic import algebra.ring.equiv import algebra.ring.prod import data.set.finite import group_theory.submonoid.centralizer import group_theory.submonoid.membership /-! # Bundled subsemirings We define bundled subsemirings and some standard constructions: `complete_lattice` structure, `subtype` and `inclusion` ring homomorphisms, subsemiring `map`, `comap` and range (`srange`) of a `ring_hom` etc. -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [non_assoc_semiring R] (M : submonoid R) section subsemiring_class /-- `subsemiring_class S R` states that `S` is a type of subsets `s ⊆ R` that are both a multiplicative and an additive submonoid. -/ class subsemiring_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R] extends submonoid_class S R := (add_mem : ∀ {s : S} {a b : R}, a ∈ s → b ∈ s → a + b ∈ s) (zero_mem : ∀ (s : S), (0 : R) ∈ s) @[priority 100] -- See note [lower instance priority] instance subsemiring_class.add_submonoid_class (S : Type*) (R : out_param $ Type u) [non_assoc_semiring R] [set_like S R] [h : subsemiring_class S R] : add_submonoid_class S R := { .. h } variables [set_like S R] [hSR : subsemiring_class S R] (s : S) include hSR lemma coe_nat_mem (n : ℕ) : (n : R) ∈ s := by simp only [← nsmul_one, nsmul_mem, one_mem] namespace subsemiring_class /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ @[priority 75] -- Prefer subclasses of `non_assoc_semiring` over subclasses of `subsemiring_class`. instance to_non_assoc_semiring : non_assoc_semiring s := subtype.coe_injective.non_assoc_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. submonoid_class.subtype s, .. add_submonoid_class.subtype s } @[simp] theorem coe_subtype : (subtype s : s → R) = coe := rfl omit hSR /-- A subsemiring of a `semiring` is a `semiring`. -/ @[priority 75] -- Prefer subclasses of `semiring` over subclasses of `subsemiring_class`. instance to_semiring {R} [semiring R] [set_like S R] [subsemiring_class S R] : semiring s := subtype.coe_injective.semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[simp, norm_cast] lemma coe_pow {R} [semiring R] [set_like S R] [subsemiring_class S R] (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] [set_like S R] [subsemiring_class S R] : comm_semiring s := subtype.coe_injective.comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] [set_like S R] [subsemiring_class S R] : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] [set_like S R] [subsemiring_class S R] : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] [set_like S R] [subsemiring_class S R] : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-! Note: currently, there is no `linear_ordered_comm_semiring`. -/ end subsemiring_class end subsemiring_class variables [non_assoc_semiring S] [non_assoc_semiring T] set_option old_structure_cmd true /-- A subsemiring of a semiring `R` is a subset `s` that is both a multiplicative and an additive submonoid. -/ structure subsemiring (R : Type u) [non_assoc_semiring R] extends submonoid R, add_submonoid R /-- Reinterpret a `subsemiring` as a `submonoid`. -/ add_decl_doc subsemiring.to_submonoid /-- Reinterpret a `subsemiring` as an `add_submonoid`. -/ add_decl_doc subsemiring.to_add_submonoid namespace subsemiring instance : set_like (subsemiring R) R := { coe := subsemiring.carrier, coe_injective' := λ p q h, by cases p; cases q; congr' } instance : subsemiring_class (subsemiring R) R := { zero_mem := zero_mem', add_mem := add_mem', one_mem := one_mem', mul_mem := mul_mem' } @[simp] lemma mem_carrier {s : subsemiring R} {x : R} : x ∈ s.carrier ↔ x ∈ s := iff.rfl /-- Two subsemirings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subsemiring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := set_like.ext h /-- Copy of a subsemiring with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : subsemiring R := { carrier := s, ..S.to_add_submonoid.copy s hs, ..S.to_submonoid.copy s hs } @[simp] lemma coe_copy (S : subsemiring R) (s : set R) (hs : s = ↑S) : (S.copy s hs : set R) = s := rfl lemma copy_eq (S : subsemiring R) (s : set R) (hs : s = ↑S) : S.copy s hs = S := set_like.coe_injective hs lemma to_submonoid_injective : function.injective (to_submonoid : subsemiring R → submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_submonoid_strict_mono : strict_mono (to_submonoid : subsemiring R → submonoid R) := λ _ _, id @[mono] lemma to_submonoid_mono : monotone (to_submonoid : subsemiring R → submonoid R) := to_submonoid_strict_mono.monotone lemma to_add_submonoid_injective : function.injective (to_add_submonoid : subsemiring R → add_submonoid R) | r s h := ext (set_like.ext_iff.mp h : _) @[mono] lemma to_add_submonoid_strict_mono : strict_mono (to_add_submonoid : subsemiring R → add_submonoid R) := λ _ _, id @[mono] lemma to_add_submonoid_mono : monotone (to_add_submonoid : subsemiring R → add_submonoid R) := to_add_submonoid_strict_mono.monotone /-- Construct a `subsemiring R` from a set `s`, a submonoid `sm`, and an additive submonoid `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (hm : ↑sm = s) (sa : add_submonoid R) (ha : ↑sa = s) : subsemiring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) {x : R} : x ∈ subsemiring.mk' s sm hm sa ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa = s) : (subsemiring.mk' s sm hm sa ha).to_submonoid = sm := set_like.coe_injective hm.symm @[simp] lemma mk'_to_add_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_submonoid R} (ha : ↑sa =s) : (subsemiring.mk' s sm hm sa ha).to_add_submonoid = sa := set_like.coe_injective ha.symm end subsemiring namespace subsemiring variables (s : subsemiring R) /-- A subsemiring contains the semiring's 1. -/ protected theorem one_mem : (1 : R) ∈ s := one_mem s /-- A subsemiring contains the semiring's 0. -/ protected theorem zero_mem : (0 : R) ∈ s := zero_mem s /-- A subsemiring is closed under multiplication. -/ protected theorem mul_mem {x y : R} : x ∈ s → y ∈ s → x * y ∈ s := mul_mem /-- A subsemiring is closed under addition. -/ protected theorem add_mem {x y : R} : x ∈ s → y ∈ s → x + y ∈ s := add_mem /-- Product of a list of elements in a `subsemiring` is in the `subsemiring`. -/ lemma list_prod_mem {R : Type*} [semiring R] (s : subsemiring R) {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := list_prod_mem /-- Sum of a list of elements in a `subsemiring` is in the `subsemiring`. -/ protected lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := list_sum_mem /-- Product of a multiset of elements in a `subsemiring` of a `comm_semiring` is in the `subsemiring`. -/ protected lemma multiset_prod_mem {R} [comm_semiring R] (s : subsemiring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := multiset_prod_mem m /-- Sum of a multiset of elements in a `subsemiring` of a `semiring` is in the `add_subsemiring`. -/ protected lemma multiset_sum_mem (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := multiset_sum_mem m /-- Product of elements of a subsemiring of a `comm_semiring` indexed by a `finset` is in the subsemiring. -/ protected lemma prod_mem {R : Type*} [comm_semiring R] (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := prod_mem h /-- Sum of elements in an `subsemiring` of an `semiring` indexed by a `finset` is in the `add_subsemiring`. -/ protected lemma sum_mem (s : subsemiring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := sum_mem h /-- A subsemiring of a `non_assoc_semiring` inherits a `non_assoc_semiring` structure -/ instance to_non_assoc_semiring : non_assoc_semiring s := { mul_zero := λ x, subtype.eq $ mul_zero x, zero_mul := λ x, subtype.eq $ zero_mul x, right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_mul_one_class, .. s.to_add_submonoid.to_add_comm_monoid } @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = (1 : R) := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = (0 : R) := rfl @[simp, norm_cast] lemma coe_add (x y : s) : ((x + y : s) : R) = (x + y : R) := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : ((x * y : s) : R) = (x * y : R) := rfl instance nontrivial [nontrivial R] : nontrivial s := nontrivial_of_ne 0 1 $ λ H, zero_ne_one (congr_arg subtype.val H) protected lemma pow_mem {R : Type*} [semiring R] (s : subsemiring R) {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := pow_mem hx n instance no_zero_divisors [no_zero_divisors R] : no_zero_divisors s := { eq_zero_or_eq_zero_of_mul_eq_zero := λ x y h, or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ subtype.ext_iff.mp h) (λ h, or.inl $ subtype.eq h) (λ h, or.inr $ subtype.eq h) } /-- A subsemiring of a `semiring` is a `semiring`. -/ instance to_semiring {R} [semiring R] (s : subsemiring R) : semiring s := { ..s.to_non_assoc_semiring, ..s.to_submonoid.to_monoid } @[simp, norm_cast] lemma coe_pow {R} [semiring R] (s : subsemiring R) (x : s) (n : ℕ) : ((x^n : s) : R) = (x^n : R) := begin induction n with n ih, { simp, }, { simp [pow_succ, ih], }, end /-- A subsemiring of a `comm_semiring` is a `comm_semiring`. -/ instance to_comm_semiring {R} [comm_semiring R] (s : subsemiring R) : comm_semiring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..s.to_semiring} /-- The natural ring hom from a subsemiring of semiring `R` to `R`. -/ def subtype : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_submonoid.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-- A subsemiring of an `ordered_semiring` is an `ordered_semiring`. -/ instance to_ordered_semiring {R} [ordered_semiring R] (s : subsemiring R) : ordered_semiring s := subtype.coe_injective.ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of an `ordered_comm_semiring` is an `ordered_comm_semiring`. -/ instance to_ordered_comm_semiring {R} [ordered_comm_semiring R] (s : subsemiring R) : ordered_comm_semiring s := subtype.coe_injective.ordered_comm_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-- A subsemiring of a `linear_ordered_semiring` is a `linear_ordered_semiring`. -/ instance to_linear_ordered_semiring {R} [linear_ordered_semiring R] (s : subsemiring R) : linear_ordered_semiring s := subtype.coe_injective.linear_ordered_semiring coe rfl rfl (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) /-! Note: currently, there is no `linear_ordered_comm_semiring`. -/ protected lemma nsmul_mem {x : R} (hx : x ∈ s) (n : ℕ) : n • x ∈ s := nsmul_mem hx n @[simp] lemma mem_to_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subsemiring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_submonoid {s : subsemiring R} {x : R} : x ∈ s.to_add_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_submonoid (s : subsemiring R) : (s.to_add_submonoid : set R) = s := rfl /-- The subsemiring `R` of the semiring `R`. -/ instance : has_top (subsemiring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_submonoid R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subsemiring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subsemiring R) : set R) = set.univ := rfl /-- The preimage of a subsemiring along a ring homomorphism is a subsemiring. -/ def comap (f : R →+* S) (s : subsemiring S) : subsemiring R := { carrier := f ⁻¹' s, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_submonoid.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subsemiring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subsemiring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subsemiring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-- The image of a subsemiring along a ring homomorphism is a subsemiring. -/ def map (f : R →+* S) (s : subsemiring R) : subsemiring S := { carrier := f '' s, .. s.to_submonoid.map (f : R →* S), .. s.to_add_submonoid.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subsemiring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subsemiring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex @[simp] lemma map_id : s.map (ring_hom.id R) = s := set_like.coe_injective $ set.image_id _ lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := set_like.coe_injective $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subsemiring R} {t : subsemiring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap /-- A subsemiring is isomorphic to its image under an injective function -/ noncomputable def equiv_map_of_injective (f : R →+* S) (hf : function.injective f) : s ≃+* s.map f := { map_mul' := λ _ _, subtype.ext (f.map_mul _ _), map_add' := λ _ _, subtype.ext (f.map_add _ _), ..equiv.set.image f s hf } @[simp] lemma coe_equiv_map_of_injective_apply (f : R →+* S) (hf : function.injective f) (x : s) : (equiv_map_of_injective s f hf x : S) = f x := rfl end subsemiring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-- The range of a ring homomorphism is a subsemiring. See Note [range copy pattern]. -/ def srange : subsemiring S := ((⊤ : subsemiring R).map f).copy (set.range f) set.image_univ.symm @[simp] lemma coe_srange : (f.srange : set S) = set.range f := rfl @[simp] lemma mem_srange {f : R →+* S} {y : S} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl lemma srange_eq_map (f : R →+* S) : f.srange = (⊤ : subsemiring R).map f := by { ext, simp } lemma mem_srange_self (f : R →+* S) (x : R) : f x ∈ f.srange := mem_srange.mpr ⟨x, rfl⟩ lemma map_srange : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemiring R).map_map g f /-- The range of a morphism of semirings is a fintype, if the domain is a fintype. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype S`.-/ instance fintype_srange [fintype R] [decidable_eq S] (f : R →+* S) : fintype (srange f) := set.fintype_range f end ring_hom namespace subsemiring instance : has_bot (subsemiring R) := ⟨(nat.cast_ring_hom R).srange⟩ instance : inhabited (subsemiring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subsemiring R) : set R) = set.range (coe : ℕ → R) := (nat.cast_ring_hom R).coe_srange lemma mem_bot {x : R} : x ∈ (⊥ : subsemiring R) ↔ ∃ n : ℕ, ↑n=x := ring_hom.mem_srange /-- The inf of two subsemirings is their intersection. -/ instance : has_inf (subsemiring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_submonoid ⊓ t.to_add_submonoid }⟩ @[simp] lemma coe_inf (p p' : subsemiring R) : ((p ⊓ p' : subsemiring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subsemiring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subsemiring R) := ⟨λ s, subsemiring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subsemiring.to_submonoid t) (by simp) (⨅ t ∈ s, subsemiring.to_add_submonoid t) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subsemiring R)) : ((Inf S : subsemiring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subsemiring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_Inter₂ @[simp] lemma Inf_to_submonoid (s : set (subsemiring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subsemiring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_submonoid (s : set (subsemiring R)) : (Inf s).to_add_submonoid = ⨅ t ∈ s, subsemiring.to_add_submonoid t := mk'_to_add_submonoid _ _ /-- Subsemirings of a semiring form a complete lattice. -/ instance : complete_lattice (subsemiring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ coe_nat_mem s n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subsemiring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from set_like.coe_subset_coe) is_glb_binfi)} lemma eq_top_iff' (A : subsemiring R) : A = ⊤ ↔ ∀ x : R, x ∈ A := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ section center /-- The center of a semiring `R` is the set of elements that commute with everything in `R` -/ def center (R) [semiring R] : subsemiring R := { carrier := set.center R, zero_mem' := set.zero_mem_center R, add_mem' := λ a b, set.add_mem_center, .. submonoid.center R } lemma coe_center (R) [semiring R] : ↑(center R) = set.center R := rfl @[simp] lemma center_to_submonoid (R) [semiring R] : (center R).to_submonoid = submonoid.center R := rfl lemma mem_center_iff {R} [semiring R] {z : R} : z ∈ center R ↔ ∀ g, g * z = z * g := iff.rfl instance decidable_mem_center {R} [semiring R] [decidable_eq R] [fintype R] : decidable_pred (∈ center R) := λ _, decidable_of_iff' _ mem_center_iff @[simp] lemma center_eq_top (R) [comm_semiring R] : center R = ⊤ := set_like.coe_injective (set.center_eq_univ R) /-- The center is commutative. -/ instance {R} [semiring R] : comm_semiring (center R) := { ..submonoid.center.comm_monoid, ..(center R).to_semiring} end center section centralizer /-- The centralizer of a set as subsemiring. -/ def centralizer {R} [semiring R] (s : set R) : subsemiring R := { carrier := s.centralizer, zero_mem' := set.zero_mem_centralizer _, add_mem' := λ x y hx hy, set.add_mem_centralizer hx hy, ..submonoid.centralizer s } @[simp, norm_cast] lemma coe_centralizer {R} [semiring R] (s : set R) : (centralizer s : set R) = s.centralizer := rfl lemma centralizer_to_submonoid {R} [semiring R] (s : set R) : (centralizer s).to_submonoid = submonoid.centralizer s := rfl lemma mem_centralizer_iff {R} [semiring R] {s : set R} {z : R} : z ∈ centralizer s ↔ ∀ g ∈ s, g * z = z * g := iff.rfl lemma centralizer_le {R} [semiring R] (s t : set R) (h : s ⊆ t) : centralizer t ≤ centralizer s := set.centralizer_subset h @[simp] lemma centralizer_univ {R} [semiring R] : centralizer set.univ = center R := set_like.ext' (set.centralizer_univ R) end centralizer /-- The `subsemiring` generated by a set. -/ def closure (s : set R) : subsemiring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subsemiring R, s ⊆ S → x ∈ S := mem_Inf /-- The subsemiring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx lemma not_mem_of_not_mem_closure {s : set R} {P : R} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) /-- A subsemiring `S` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subsemiring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subsemiring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subsemiring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ lemma mem_map_equiv {f : R ≃+* S} {K : subsemiring R} {x : S} : x ∈ K.map (f : R →+* S) ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x lemma map_equiv_eq_comap_symm (f : R ≃+* S) (K : subsemiring R) : K.map (f : R →+* S) = K.comap f.symm := set_like.coe_injective (f.to_equiv.image_eq_preimage K) lemma comap_equiv_eq_map_symm (f : R ≃+* S) (K : subsemiring S) : K.comap (f : R →+* S) = K.map f.symm := (map_equiv_eq_comap_symm f.symm K).symm end subsemiring namespace submonoid /-- The additive closure of a submonoid is a subsemiring. -/ def subsemiring_closure (M : submonoid R) : subsemiring R := { one_mem' := add_submonoid.mem_closure.mpr (λ y hy, hy M.one_mem), mul_mem' := λ x y, mul_mem_class.mul_mem_add_closure, ..add_submonoid.closure (M : set R)} lemma subsemiring_closure_coe : (M.subsemiring_closure : set R) = add_submonoid.closure (M : set R) := rfl lemma subsemiring_closure_to_add_submonoid : M.subsemiring_closure.to_add_submonoid = add_submonoid.closure (M : set R) := rfl /-- The `subsemiring` generated by a multiplicative submonoid coincides with the `subsemiring.closure` of the submonoid itself . -/ lemma subsemiring_closure_eq_closure : M.subsemiring_closure = subsemiring.closure (M : set R) := begin ext, refine ⟨λ hx, _, λ hx, (subsemiring.mem_closure.mp hx) M.subsemiring_closure (λ s sM, _)⟩; rintros - ⟨H1, rfl⟩; rintros - ⟨H2, rfl⟩, { exact add_submonoid.mem_closure.mp hx H1.to_add_submonoid H2 }, { exact H2 sM } end end submonoid namespace subsemiring @[simp] lemma closure_submonoid_closure (s : set R) : closure ↑(submonoid.closure s) = closure s := le_antisymm (closure_le.mpr (λ y hy, (submonoid.mem_closure.mp hy) (closure s).to_submonoid subset_closure)) (closure_mono (submonoid.subset_closure)) /-- The elements of the subsemiring closure of `M` are exactly the elements of the additive closure of a multiplicative submonoid `M`. -/ lemma coe_closure_eq (s : set R) : (closure s : set R) = add_submonoid.closure (submonoid.closure s : set R) := by simp [← submonoid.subsemiring_closure_to_add_submonoid, submonoid.subsemiring_closure_eq_closure] lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_submonoid.closure (submonoid.closure s : set R) := set.ext_iff.mp (coe_closure_eq s) x @[simp] lemma closure_add_submonoid_closure {s : set R} : closure ↑(add_submonoid.closure s) = closure s := begin ext x, refine ⟨λ hx, _, λ hx, closure_mono add_submonoid.subset_closure hx⟩, rintros - ⟨H, rfl⟩, rintros - ⟨J, rfl⟩, refine (add_submonoid.mem_closure.mp (mem_closure_iff.mp hx)) H.to_add_submonoid (λ y hy, _), refine (submonoid.mem_closure.mp hy) H.to_submonoid (λ z hz, _), exact (add_submonoid.mem_closure.mp hz) H.to_add_submonoid (λ w hw, J hw), end /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, Hmul, H1, Hadd, H0⟩).2 Hs h /-- An induction principle for closure membership for predicates with two arguments. -/ @[elab_as_eliminator] lemma closure_induction₂ {s : set R} {p : R → R → Prop} {x} {y : R} (hx : x ∈ closure s) (hy : y ∈ closure s) (Hs : ∀ (x ∈ s) (y ∈ s), p x y) (H0_left : ∀ x, p 0 x) (H0_right : ∀ x, p x 0) (H1_left : ∀ x, p 1 x) (H1_right : ∀ x, p x 1) (Hadd_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ + x₂) y) (Hadd_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ + y₂)) (Hmul_left : ∀ x₁ x₂ y, p x₁ y → p x₂ y → p (x₁ * x₂) y) (Hmul_right : ∀ x y₁ y₂, p x y₁ → p x y₂ → p x (y₁ * y₂)) : p x y := closure_induction hx (λ x₁ x₁s, closure_induction hy (Hs x₁ x₁s) (H0_right x₁) (H1_right x₁) (Hadd_right x₁) (Hmul_right x₁)) (H0_left y) (H1_left y) (λ z z', Hadd_left z z' y) (λ z z', Hmul_left z z' y) lemma mem_closure_iff_exists_list {R} [semiring R] {s : set R} {x} : x ∈ closure s ↔ ∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s) ∧ (L.map list.prod).sum = x := ⟨λ hx, add_submonoid.closure_induction (mem_closure_iff.1 hx) (λ x hx, suffices ∃ t : list R, (∀ y ∈ t, y ∈ s) ∧ t.prod = x, from let ⟨t, ht1, ht2⟩ := this in ⟨[t], list.forall_mem_singleton.2 ht1, by rw [list.map_singleton, list.sum_singleton, ht2]⟩, submonoid.closure_induction hx (λ x hx, ⟨[x], list.forall_mem_singleton.2 hx, one_mul x⟩) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨t, ht1, ht2⟩ ⟨u, hu1, hu2⟩, ⟨t ++ u, list.forall_mem_append.2 ⟨ht1, hu1⟩, by rw [list.prod_append, ht2, hu2]⟩)) ⟨[], list.forall_mem_nil _, rfl⟩ (λ x y ⟨L, HL1, HL2⟩ ⟨M, HM1, HM2⟩, ⟨L ++ M, list.forall_mem_append.2 ⟨HL1, HM1⟩, by rw [list.map_append, list.sum_append, HL2, HM2]⟩), λ ⟨L, HL1, HL2⟩, HL2 ▸ list_sum_mem (λ r hr, let ⟨t, ht1, ht2⟩ := list.mem_map.1 hr in ht2 ▸ list_prod_mem _ (λ y hy, subset_closure $ HL1 t ht1 y hy))⟩ variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subsemiring `S` equals `S`. -/ lemma closure_eq (s : subsemiring R) : closure (s : set R) = s := (subsemiring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subsemiring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subsemiring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subsemiring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subsemiring.gi R).gc.l_Sup lemma map_sup (s t : subsemiring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subsemiring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subsemiring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subsemiring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subsemiring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subsemiring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subsemiring`s `s`, `t` of semirings `R`, `S` respectively, `s.prod t` is `s × t` as a subsemiring of `R × S`. -/ def prod (s : subsemiring R) (t : subsemiring S) : subsemiring (R × S) := { carrier := (s : set R) ×ˢ (t : set S), .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_submonoid.prod t.to_add_submonoid} @[norm_cast] lemma coe_prod (s : subsemiring R) (t : subsemiring S) : (s.prod t : set (R × S)) = (s : set R) ×ˢ (t : set S) := rfl lemma mem_prod {s : subsemiring R} {t : subsemiring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subsemiring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subsemiring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subsemiring R) : monotone (λ t : subsemiring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subsemiring S) : monotone (λ s : subsemiring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subsemiring R) : s.prod (⊤ : subsemiring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subsemiring S) : (⊤ : subsemiring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subsemiring R).prod (⊤ : subsemiring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subsemirings is isomorphic to their product as monoids. -/ def prod_equiv (s : subsemiring R) (t : subsemiring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (set_like.le_def.1 $ le_supr S i) hi⟩, let U : subsemiring R := subsemiring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (⨆ i, (S i).to_add_submonoid) (add_submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subsemiring R} (hS : directed (≤) S) : ((⨆ i, S i : subsemiring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subsemiring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subsemiring namespace ring_hom variables [non_assoc_semiring T] {s : subsemiring R} open subsemiring /-- Restriction of a ring homomorphism to a subsemiring of the domain. -/ def srestrict (f : R →+* S) (s : subsemiring R) : s →+* S := f.comp s.subtype @[simp] lemma srestrict_apply (f : R →+* S) (x : s) : f.srestrict s x = f x := rfl /-- Restriction of a ring homomorphism to a subsemiring of the codomain. -/ def cod_srestrict (f : R →+* S) (s : subsemiring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ n, ⟨f n, h n⟩, .. (f : R →* S).cod_mrestrict s.to_submonoid h, .. (f : R →+ S).cod_mrestrict s.to_add_submonoid h } /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def srange_restrict (f : R →+* S) : R →+* f.srange := f.cod_srestrict f.srange f.mem_srange_self @[simp] lemma coe_srange_restrict (f : R →+* S) (x : R) : (f.srange_restrict x : S) = f x := rfl lemma srange_restrict_surjective (f : R →+* S) : function.surjective f.srange_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_srange.mp hy in ⟨x, subtype.ext hx⟩ lemma srange_top_iff_surjective {f : R →+* S} : f.srange = (⊤ : subsemiring S) ↔ function.surjective f := set_like.ext'_iff.trans $ iff.trans (by rw [coe_srange, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma srange_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.srange = (⊤ : subsemiring S) := srange_top_iff_surjective.2 hf /-- The subsemiring of elements `x : R` such that `f x = g x` -/ def eq_slocus (f g : R →+* S) : subsemiring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_mlocus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subsemiring closure. -/ lemma eq_on_sclosure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_slocus g, from closure_le.2 h lemma eq_of_eq_on_stop {f g : R →+* S} (h : set.eq_on f g (⊤ : subsemiring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_sdense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_stop $ hs ▸ eq_on_sclosure h lemma sclosure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, set_like.mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subsemiring generated by a set equals the subsemiring generated by the image of the set. -/ lemma map_sclosure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (sclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subsemiring open ring_hom /-- The ring homomorphism associated to an inclusion of subsemirings. -/ def inclusion {S T : subsemiring R} (h : S ≤ T) : S →+* T := S.subtype.cod_srestrict _ (λ x, h x.2) @[simp] lemma srange_subtype (s : subsemiring R) : s.subtype.srange = s := set_like.coe_injective $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subsemiring R) (t : subsemiring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, set_like.mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨set_like.mem_coe.2 $ one_mem ⊥, hp.2⟩) end subsemiring namespace ring_equiv variables {s t : subsemiring R} /-- Makes the identity isomorphism from a proof two subsemirings of a multiplicative monoid are equal. -/ def subsemiring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.srange`. -/ def sof_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.srange := { to_fun := λ x, f.srange_restrict x, inv_fun := λ x, (g ∘ f.srange.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.srange_restrict } @[simp] lemma sof_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(sof_left_inverse h x) = f x := rfl @[simp] lemma sof_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.srange) : (sof_left_inverse h).symm x = g x := rfl /-- Given an equivalence `e : R ≃+* S` of semirings and a subsemiring `s` of `R`, `subsemiring_map e s` is the induced equivalence between `s` and `s.map e` -/ @[simps] def subsemiring_map (e : R ≃+* S) (s : subsemiring R) : s ≃+* s.map e.to_ring_hom := { ..e.to_add_equiv.add_submonoid_map s.to_add_submonoid, ..e.to_mul_equiv.submonoid_map s.to_submonoid } end ring_equiv /-! ### Actions by `subsemiring`s These are just copies of the definitions about `submonoid` starting from `submonoid.mul_action`. The only new result is `subsemiring.module`. When `R` is commutative, `algebra.of_subsemiring` provides a stronger result than those found in this file, which uses the same scalar action. -/ section actions namespace subsemiring variables {R' α β : Type*} section non_assoc_semiring variables [non_assoc_semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_scalar R' α] (S : subsemiring R') : has_scalar S α := S.to_submonoid.has_scalar lemma smul_def [has_scalar R' α] {S : subsemiring R'} (g : S) (m : α) : g • m = (g : R') • m := rfl instance smul_comm_class_left [has_scalar R' β] [has_scalar α β] [smul_comm_class R' α β] (S : subsemiring R') : smul_comm_class S α β := S.to_submonoid.smul_comm_class_left instance smul_comm_class_right [has_scalar α β] [has_scalar R' β] [smul_comm_class α R' β] (S : subsemiring R') : smul_comm_class α S β := S.to_submonoid.smul_comm_class_right /-- Note that this provides `is_scalar_tower S R R` which is needed by `smul_mul_assoc`. -/ instance [has_scalar α β] [has_scalar R' α] [has_scalar R' β] [is_scalar_tower R' α β] (S : subsemiring R') : is_scalar_tower S α β := S.to_submonoid.is_scalar_tower instance [has_scalar R' α] [has_faithful_scalar R' α] (S : subsemiring R') : has_faithful_scalar S α := S.to_submonoid.has_faithful_scalar /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [smul_with_zero R' α] (S : subsemiring R') : smul_with_zero S α := smul_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom.to_zero_hom end non_assoc_semiring variables [semiring R'] /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [mul_action R' α] (S : subsemiring R') : mul_action S α := S.to_submonoid.mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_monoid α] [distrib_mul_action R' α] (S : subsemiring R') : distrib_mul_action S α := S.to_submonoid.distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [monoid α] [mul_distrib_mul_action R' α] (S : subsemiring R') : mul_distrib_mul_action S α := S.to_submonoid.mul_distrib_mul_action /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [has_zero α] [mul_action_with_zero R' α] (S : subsemiring R') : mul_action_with_zero S α := mul_action_with_zero.comp_hom _ S.subtype.to_monoid_with_zero_hom /-- The action by a subsemiring is the action by the underlying semiring. -/ instance [add_comm_monoid α] [module R' α] (S : subsemiring R') : module S α := { smul := (•), .. module.comp_hom _ S.subtype } /-- If all the elements of a set `s` commute, then `closure s` is a commutative monoid. -/ def closure_comm_semiring_of_comm {s : set R'} (hcomm : ∀ (a ∈ s) (b ∈ s), a * b = b * a) : comm_semiring (closure s) := { mul_comm := λ x y, begin ext, simp only [subsemiring.coe_mul], refine closure_induction₂ x.prop y.prop hcomm (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [zero_mul, mul_zero]) (λ x, by simp only [one_mul, mul_one]) (λ x, by simp only [one_mul, mul_one]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by simp only [add_mul, mul_add, h₁, h₂]) (λ x y z h₁ h₂, by rw [mul_assoc, h₂, ←mul_assoc, h₁, mul_assoc]) (λ x y z h₁ h₂, by rw [←mul_assoc, h₁, mul_assoc, h₂, ←mul_assoc]) end, ..(closure s).to_semiring } end subsemiring end actions -- While this definition is not about `subsemiring`s, this is the earliest we have -- both `ordered_semiring` and `submonoid` available. /-- Submonoid of positive elements of an ordered semiring. -/ def pos_submonoid (R : Type*) [ordered_semiring R] [nontrivial R] : submonoid R := { carrier := {x | 0 < x}, one_mem' := show (0 : R) < 1, from zero_lt_one, mul_mem' := λ x y (hx : 0 < x) (hy : 0 < y), mul_pos hx hy } @[simp] lemma mem_pos_monoid {R : Type*} [ordered_semiring R] [nontrivial R] (u : Rˣ) : ↑u ∈ pos_submonoid R ↔ (0 : R) < u := iff.rfl
67842cf9bba265acb07ed4cba2264d2a8be1e179
94e33a31faa76775069b071adea97e86e218a8ee
/src/logic/encodable/basic.lean
aed8d48bed5b749d883a6ab12a04c044cf10a810
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
18,899
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, Mario Carneiro -/ import logic.equiv.nat import order.directed import order.rel_iso /-! # Encodable types This file defines encodable (constructively countable) types as a typeclass. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. The difference with `denumerable` is that finite types are encodable. For infinite types, `encodable` and `denumerable` agree. ## Main declarations * `encodable α`: States that there exists an explicit encoding function `encode : α → ℕ` with a partial inverse `decode : ℕ → option α`. * `decode₂`: Version of `decode` that is equal to `none` outside of the range of `encode`. Useful as we do not require this in the definition of `decode`. * `ulower α`: Any encodable type has an equivalent type living in the lowest universe, namely a subtype of `ℕ`. `ulower α` finds it. ## Implementation notes The point of asking for an explicit partial inverse `decode : ℕ → option α` to `encode : α → ℕ` is to make the range of `encode` decidable even when the finiteness of `α` is not. -/ open option list nat function /-- Constructively countable type. Made from an explicit injection `encode : α → ℕ` and a partial inverse `decode : ℕ → option α`. Note that finite types *are* countable. See `denumerable` if you wish to enforce infiniteness. -/ class encodable (α : Type*) := (encode : α → ℕ) (decode [] : ℕ → option α) (encodek : ∀ a, decode (encode a) = some a) attribute [simp] encodable.encodek namespace encodable variables {α : Type*} {β : Type*} universe u theorem encode_injective [encodable α] : function.injective (@encode α _) | x y e := option.some.inj $ by rw [← encodek, e, encodek] @[simp] lemma encode_inj [encodable α] {a b : α} : encode a = encode b ↔ a = b := encode_injective.eq_iff lemma surjective_decode_iget (α : Type*) [encodable α] [inhabited α] : surjective (λ n, (encodable.decode α n).iget) := λ x, ⟨encodable.encode x, by simp_rw [encodable.encodek]⟩ /-- An encodable type has decidable equality. Not set as an instance because this is usually not the best way to infer decidability. -/ def decidable_eq_of_encodable (α) [encodable α] : decidable_eq α | a b := decidable_of_iff _ encode_inj /-- If `α` is encodable and there is an injection `f : β → α`, then `β` is encodable as well. -/ def of_left_injection [encodable α] (f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β := ⟨λ b, encode (f b), λ n, (decode α n).bind finv, λ b, by simp [encodable.encodek, linv]⟩ /-- If `α` is encodable and `f : β → α` is invertible, then `β` is encodable as well. -/ def of_left_inverse [encodable α] (f : β → α) (finv : α → β) (linv : ∀ b, finv (f b) = b) : encodable β := of_left_injection f (some ∘ finv) (λ b, congr_arg some (linv b)) /-- Encodability is preserved by equivalence. -/ def of_equiv (α) [encodable α] (e : β ≃ α) : encodable β := of_left_inverse e e.symm e.left_inv @[simp] theorem encode_of_equiv {α β} [encodable α] (e : β ≃ α) (b : β) : @encode _ (of_equiv _ e) b = encode (e b) := rfl @[simp] theorem decode_of_equiv {α β} [encodable α] (e : β ≃ α) (n : ℕ) : @decode _ (of_equiv _ e) n = (decode α n).map e.symm := rfl instance _root_.nat.encodable : encodable ℕ := ⟨id, some, λ a, rfl⟩ @[simp] theorem encode_nat (n : ℕ) : encode n = n := rfl @[simp] theorem decode_nat (n : ℕ) : decode ℕ n = some n := rfl @[priority 100] instance _root_.is_empty.to_encodable [is_empty α] : encodable α := ⟨is_empty_elim, λ n, none, is_empty_elim⟩ instance _root_.punit.encodable : encodable punit := ⟨λ_, 0, λ n, nat.cases_on n (some punit.star) (λ _, none), λ _, by simp⟩ @[simp] theorem encode_star : encode punit.star = 0 := rfl @[simp] theorem decode_unit_zero : decode punit 0 = some punit.star := rfl @[simp] theorem decode_unit_succ (n) : decode punit (succ n) = none := rfl /-- If `α` is encodable, then so is `option α`. -/ instance _root_.option.encodable {α : Type*} [h : encodable α] : encodable (option α) := ⟨λ o, option.cases_on o nat.zero (λ a, succ (encode a)), λ n, nat.cases_on n (some none) (λ m, (decode α m).map some), λ o, by cases o; dsimp; simp [encodek, nat.succ_ne_zero]⟩ @[simp] theorem encode_none [encodable α] : encode (@none α) = 0 := rfl @[simp] theorem encode_some [encodable α] (a : α) : encode (some a) = succ (encode a) := rfl @[simp] theorem decode_option_zero [encodable α] : decode (option α) 0 = some none := rfl @[simp] theorem decode_option_succ [encodable α] (n) : decode (option α) (succ n) = (decode α n).map some := rfl /-- Failsafe variant of `decode`. `decode₂ α n` returns the preimage of `n` under `encode` if it exists, and returns `none` if it doesn't. This requirement could be imposed directly on `decode` but is not to help make the definition easier to use. -/ def decode₂ (α) [encodable α] (n : ℕ) : option α := (decode α n).bind (option.guard (λ a, encode a = n)) theorem mem_decode₂' [encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ a ∈ decode α n ∧ encode a = n := by simp [decode₂]; exact ⟨λ ⟨_, h₁, rfl, h₂⟩, ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨_, h₁, rfl, h₂⟩⟩ theorem mem_decode₂ [encodable α] {n : ℕ} {a : α} : a ∈ decode₂ α n ↔ encode a = n := mem_decode₂'.trans (and_iff_right_of_imp $ λ e, e ▸ encodek _) theorem decode₂_eq_some [encodable α] {n : ℕ} {a : α} : decode₂ α n = some a ↔ encode a = n := mem_decode₂ @[simp] lemma decode₂_encode [encodable α] (a : α) : decode₂ α (encode a) = some a := by { ext, simp [mem_decode₂, eq_comm] } theorem decode₂_ne_none_iff [encodable α] {n : ℕ} : decode₂ α n ≠ none ↔ n ∈ set.range (encode : α → ℕ) := by simp_rw [set.range, set.mem_set_of_eq, ne.def, option.eq_none_iff_forall_not_mem, encodable.mem_decode₂, not_forall, not_not] theorem decode₂_is_partial_inv [encodable α] : is_partial_inv encode (decode₂ α) := λ a n, mem_decode₂ theorem decode₂_inj [encodable α] {n : ℕ} {a₁ a₂ : α} (h₁ : a₁ ∈ decode₂ α n) (h₂ : a₂ ∈ decode₂ α n) : a₁ = a₂ := encode_injective $ (mem_decode₂.1 h₁).trans (mem_decode₂.1 h₂).symm theorem encodek₂ [encodable α] (a : α) : decode₂ α (encode a) = some a := mem_decode₂.2 rfl /-- The encoding function has decidable range. -/ def decidable_range_encode (α : Type*) [encodable α] : decidable_pred (∈ set.range (@encode α _)) := λ x, decidable_of_iff (option.is_some (decode₂ α x)) ⟨λ h, ⟨option.get h, by rw [← decode₂_is_partial_inv (option.get h), option.some_get]⟩, λ ⟨n, hn⟩, by rw [← hn, encodek₂]; exact rfl⟩ /-- An encodable type is equivalent to the range of its encoding function. -/ def equiv_range_encode (α : Type*) [encodable α] : α ≃ set.range (@encode α _) := { to_fun := λ a : α, ⟨encode a, set.mem_range_self _⟩, inv_fun := λ n, option.get (show is_some (decode₂ α n.1), by cases n.2 with x hx; rw [← hx, encodek₂]; exact rfl), left_inv := λ a, by dsimp; rw [← option.some_inj, option.some_get, encodek₂], right_inv := λ ⟨n, x, hx⟩, begin apply subtype.eq, dsimp, conv {to_rhs, rw ← hx}, rw [encode_injective.eq_iff, ← option.some_inj, option.some_get, ← hx, encodek₂], end } /-- A type with unique element is encodable. This is not an instance to avoid diamonds. -/ def _root_.unique.encodable [unique α] : encodable α := ⟨λ _, 0, λ _, some default, unique.forall_iff.2 rfl⟩ section sum variables [encodable α] [encodable β] /-- Explicit encoding function for the sum of two encodable types. -/ def encode_sum : α ⊕ β → ℕ | (sum.inl a) := bit0 $ encode a | (sum.inr b) := bit1 $ encode b /-- Explicit decoding function for the sum of two encodable types. -/ def decode_sum (n : ℕ) : option (α ⊕ β) := match bodd_div2 n with | (ff, m) := (decode α m).map sum.inl | (tt, m) := (decode β m).map sum.inr end /-- If `α` and `β` are encodable, then so is their sum. -/ instance _root_.sum.encodable : encodable (α ⊕ β) := ⟨encode_sum, decode_sum, λ s, by cases s; simp [encode_sum, decode_sum, encodek]; refl⟩ @[simp] theorem encode_inl (a : α) : @encode (α ⊕ β) _ (sum.inl a) = bit0 (encode a) := rfl @[simp] theorem encode_inr (b : β) : @encode (α ⊕ β) _ (sum.inr b) = bit1 (encode b) := rfl @[simp] theorem decode_sum_val (n : ℕ) : decode (α ⊕ β) n = decode_sum n := rfl end sum instance _root_.bool.encodable : encodable bool := of_equiv (unit ⊕ unit) equiv.bool_equiv_punit_sum_punit @[simp] theorem encode_tt : encode tt = 1 := rfl @[simp] theorem encode_ff : encode ff = 0 := rfl @[simp] theorem decode_zero : decode bool 0 = some ff := rfl @[simp] theorem decode_one : decode bool 1 = some tt := rfl theorem decode_ge_two (n) (h : 2 ≤ n) : decode bool n = none := begin suffices : decode_sum n = none, { change (decode_sum n).map _ = none, rw this, refl }, have : 1 ≤ div2 n, { rw [div2_val, nat.le_div_iff_mul_le], exacts [h, dec_trivial] }, cases exists_eq_succ_of_ne_zero (ne_of_gt this) with m e, simp [decode_sum]; cases bodd n; simp [decode_sum]; rw e; refl end noncomputable instance _root_.Prop.encodable : encodable Prop := of_equiv bool equiv.Prop_equiv_bool section sigma variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)] /-- Explicit encoding function for `sigma γ` -/ def encode_sigma : sigma γ → ℕ | ⟨a, b⟩ := mkpair (encode a) (encode b) /-- Explicit decoding function for `sigma γ` -/ def decode_sigma (n : ℕ) : option (sigma γ) := let (n₁, n₂) := unpair n in (decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a instance _root_.sigma.encodable : encodable (sigma γ) := ⟨encode_sigma, decode_sigma, λ ⟨a, b⟩, by simp [encode_sigma, decode_sigma, unpair_mkpair, encodek]⟩ @[simp] theorem decode_sigma_val (n : ℕ) : decode (sigma γ) n = (decode α n.unpair.1).bind (λ a, (decode (γ a) n.unpair.2).map $ sigma.mk a) := show decode_sigma._match_1 _ = _, by cases n.unpair; refl @[simp] theorem encode_sigma_val (a b) : @encode (sigma γ) _ ⟨a, b⟩ = mkpair (encode a) (encode b) := rfl end sigma section prod variables [encodable α] [encodable β] /-- If `α` and `β` are encodable, then so is their product. -/ instance _root_.prod.encodable : encodable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem decode_prod_val (n : ℕ) : decode (α × β) n = (decode α n.unpair.1).bind (λ a, (decode β n.unpair.2).map $ prod.mk a) := show (decode (sigma (λ _, β)) n).map (equiv.sigma_equiv_prod α β) = _, by simp; cases decode α n.unpair.1; simp; cases decode β n.unpair.2; refl @[simp] theorem encode_prod_val (a b) : @encode (α × β) _ (a, b) = mkpair (encode a) (encode b) := rfl end prod section subtype open subtype decidable variables {P : α → Prop} [encA : encodable α] [decP : decidable_pred P] include encA /-- Explicit encoding function for a decidable subtype of an encodable type -/ def encode_subtype : {a : α // P a} → ℕ | ⟨v, h⟩ := encode v include decP /-- Explicit decoding function for a decidable subtype of an encodable type -/ def decode_subtype (v : ℕ) : option {a : α // P a} := (decode α v).bind $ λ a, if h : P a then some ⟨a, h⟩ else none /-- A decidable subtype of an encodable type is encodable. -/ instance _root_.subtype.encodable : encodable {a : α // P a} := ⟨encode_subtype, decode_subtype, λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩ lemma subtype.encode_eq (a : subtype P) : encode a = encode a.val := by cases a; refl end subtype instance _root_.fin.encodable (n) : encodable (fin n) := subtype.encodable instance _root_.int.encodable : encodable ℤ := of_equiv _ equiv.int_equiv_nat instance _root_.pnat.encodable : encodable ℕ+ := of_equiv _ equiv.pnat_equiv_nat /-- The lift of an encodable type is encodable. -/ instance _root_.ulift.encodable [encodable α] : encodable (ulift α) := of_equiv _ equiv.ulift /-- The lift of an encodable type is encodable. -/ instance _root_.plift.encodable [encodable α] : encodable (plift α) := of_equiv _ equiv.plift /-- If `β` is encodable and there is an injection `f : α → β`, then `α` is encodable as well. -/ noncomputable def of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α := of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl) end encodable section ulower local attribute [instance, priority 100] encodable.decidable_range_encode /-- `ulower α : Type` is an equivalent type in the lowest universe, given `encodable α`. -/ @[derive decidable_eq, derive encodable] def ulower (α : Type*) [encodable α] : Type := set.range (encodable.encode : α → ℕ) end ulower namespace ulower variables (α : Type*) [encodable α] /-- The equivalence between the encodable type `α` and `ulower α : Type`. -/ def equiv : α ≃ ulower α := encodable.equiv_range_encode α variables {α} /-- Lowers an `a : α` into `ulower α`. -/ def down (a : α) : ulower α := equiv α a instance [inhabited α] : inhabited (ulower α) := ⟨down default⟩ /-- Lifts an `a : ulower α` into `α`. -/ def up (a : ulower α) : α := (equiv α).symm a @[simp] lemma down_up {a : ulower α} : down a.up = a := equiv.right_inv _ _ @[simp] lemma up_down {a : α} : (down a).up = a := equiv.left_inv _ _ @[simp] lemma up_eq_up {a b : ulower α} : a.up = b.up ↔ a = b := equiv.apply_eq_iff_eq _ @[simp] lemma down_eq_down {a b : α} : down a = down b ↔ a = b := equiv.apply_eq_iff_eq _ @[ext] protected lemma ext {a b : ulower α} : a.up = b.up → a = b := up_eq_up.1 end ulower /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable section find_a variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p] private def good : option α → Prop | (some a) := p a | none := false private def decidable_good : decidable_pred (good p) | n := by cases n; unfold good; apply_instance local attribute [instance] decidable_good open encodable variable {p} /-- Constructive choice function for a decidable subtype of an encodable type. -/ def choose_x (h : ∃ x, p x) : {a : α // p a} := have ∃ n, good p (decode α n), from let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩, match _, nat.find_spec this : ∀ o, good p o → {a // p a} with | some a, h := ⟨a, h⟩ end /-- Constructive choice function for a decidable predicate over an encodable type. -/ def choose (h : ∃ x, p x) : α := (choose_x h).1 lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2 end find_a /-- A constructive version of `classical.axiom_of_choice` for `encodable` types. -/ theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop} [Π a, encodable (β a)] [∀ x y, decidable (R x y)] (H : ∀ x, ∃ y, R x y) : ∃ f : Π a, β a, ∀ x, R x (f x) := ⟨λ x, choose (H x), λ x, choose_spec (H x)⟩ /-- A constructive version of `classical.skolem` for `encodable` types. -/ theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop} [c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] : (∀ x, ∃ y, P x y) ↔ ∃ f : Π a, β a, (∀ x, P x (f x)) := ⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩ /- There is a total ordering on the elements of an encodable type, induced by the map to ℕ. -/ /-- The `encode` function, viewed as an embedding. -/ def encode' (α) [encodable α] : α ↪ ℕ := ⟨encodable.encode, encodable.encode_injective⟩ instance {α} [encodable α] : is_trans _ (encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_trans instance {α} [encodable α] : is_antisymm _ (encodable.encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_antisymm instance {α} [encodable α] : is_total _ (encodable.encode' α ⁻¹'o (≤)) := (rel_embedding.preimage _ _).is_total end encodable namespace directed open encodable variables {α : Type*} {β : Type*} [encodable α] [inhabited α] /-- Given a `directed r` function `f : α → β` defined on an encodable inhabited type, construct a noncomputable sequence such that `r (f (x n)) (f (x (n + 1)))` and `r (f a) (f (x (encode a + 1))`. -/ protected noncomputable def sequence {r : β → β → Prop} (f : α → β) (hf : directed r f) : ℕ → α | 0 := default | (n + 1) := let p := sequence n in match decode α n with | none := classical.some (hf p p) | (some a) := classical.some (hf p a) end lemma sequence_mono_nat {r : β → β → Prop} {f : α → β} (hf : directed r f) (n : ℕ) : r (f (hf.sequence f n)) (f (hf.sequence f (n+1))) := begin dsimp [directed.sequence], generalize eq : hf.sequence f n = p, cases h : decode α n with a, { exact (classical.some_spec (hf p p)).1 }, { exact (classical.some_spec (hf p a)).1 } end lemma rel_sequence {r : β → β → Prop} {f : α → β} (hf : directed r f) (a : α) : r (f a) (f (hf.sequence f (encode a + 1))) := begin simp only [directed.sequence, encodek], exact (classical.some_spec (hf _ a)).2 end variables [preorder β] {f : α → β} (hf : directed (≤) f) lemma sequence_mono : monotone (f ∘ (hf.sequence f)) := monotone_nat_of_le_succ $ hf.sequence_mono_nat lemma le_sequence (a : α) : f a ≤ f (hf.sequence f (encode a + 1)) := hf.rel_sequence a end directed section quotient open encodable quotient variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α] /-- Representative of an equivalence class. This is a computable version of `quot.out` for a setoid on an encodable type. -/ def quotient.rep (q : quotient s) : α := choose (exists_rep q) theorem quotient.rep_spec (q : quotient s) : ⟦q.rep⟧ = q := choose_spec (exists_rep q) /-- The quotient of an encodable space by a decidable equivalence relation is encodable. -/ def encodable_quotient : encodable (quotient s) := ⟨λ q, encode q.rep, λ n, quotient.mk <$> decode α n, by rintros ⟨l⟩; rw encodek; exact congr_arg some ⟦l⟧.rep_spec⟩ end quotient
2d10c8de4a2df4b0ddd5470cc417374cc771d6c2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/lie/classical.lean
41deb49cc1a8e41d957993a37308643ff032e359
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
13,935
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.invertible import algebra.lie.skew_adjoint import algebra.lie.abelian import linear_algebra.matrix.trace /-! # Classical Lie algebras This file is the place to find definitions and basic properties of the classical Lie algebras: * Aₗ = sl(l+1) * Bₗ ≃ so(l+1, l) ≃ so(2l+1) * Cₗ = sp(l) * Dₗ ≃ so(l, l) ≃ so(2l) ## Main definitions * `lie_algebra.special_linear.sl` * `lie_algebra.symplectic.sp` * `lie_algebra.orthogonal.so` * `lie_algebra.orthogonal.so'` * `lie_algebra.orthogonal.so_indefinite_equiv` * `lie_algebra.orthogonal.type_D` * `lie_algebra.orthogonal.type_B` * `lie_algebra.orthogonal.type_D_equiv_so'` * `lie_algebra.orthogonal.type_B_equiv_so'` ## Implementation notes ### Matrices or endomorphisms Given a finite type and a commutative ring, the corresponding square matrices are equivalent to the endomorphisms of the corresponding finite-rank free module as Lie algebras, see `lie_equiv_matrix'`. We can thus define the classical Lie algebras as Lie subalgebras either of matrices or of endomorphisms. We have opted for the former. At the time of writing (August 2020) it is unclear which approach should be preferred so the choice should be assumed to be somewhat arbitrary. ### Diagonal quadratic form or diagonal Cartan subalgebra For the algebras of type `B` and `D`, there are two natural definitions. For example since the the `2l × 2l` matrix: $$ J = \left[\begin{array}{cc} 0_l & 1_l\\ 1_l & 0_l \end{array}\right] $$ defines a symmetric bilinear form equivalent to that defined by the identity matrix `I`, we can define the algebras of type `D` to be the Lie subalgebra of skew-adjoint matrices either for `J` or for `I`. Both definitions have their advantages (in particular the `J`-skew-adjoint matrices define a Lie algebra for which the diagonal matrices form a Cartan subalgebra) and so we provide both. We thus also provide equivalences `type_D_equiv_so'`, `so_indefinite_equiv` which show the two definitions are equivalent. Similarly for the algebras of type `B`. ## Tags classical lie algebra, special linear, symplectic, orthogonal -/ universes u₁ u₂ namespace lie_algebra open_locale matrix variables (n p q l : Type*) (R : Type u₂) variables [fintype n] [fintype l] [fintype p] [fintype q] variables [decidable_eq n] [decidable_eq p] [decidable_eq q] [decidable_eq l] variables [comm_ring R] @[simp] lemma matrix_trace_commutator_zero (X Y : matrix n n R) : matrix.trace n R R ⁅X, Y⁆ = 0 := calc _ = matrix.trace n R R (X ⬝ Y) - matrix.trace n R R (Y ⬝ X) : linear_map.map_sub _ _ _ ... = matrix.trace n R R (X ⬝ Y) - matrix.trace n R R (X ⬝ Y) : congr_arg (λ x, _ - x) (matrix.trace_mul_comm X Y) ... = 0 : sub_self _ namespace special_linear /-- The special linear Lie algebra: square matrices of trace zero. -/ def sl : lie_subalgebra R (matrix n n R) := { lie_mem' := λ X Y _ _, linear_map.mem_ker.2 $ matrix_trace_commutator_zero _ _ _ _, ..linear_map.ker (matrix.trace n R R) } lemma sl_bracket (A B : sl n R) : ⁅A, B⁆.val = A.val ⬝ B.val - B.val ⬝ A.val := rfl section elementary_basis variables {n} (i j : n) /-- It is useful to define these matrices for explicit calculations in sl n R. -/ abbreviation E : matrix n n R := λ i' j', if i = i' ∧ j = j' then 1 else 0 @[simp] lemma E_apply_one : E R i j i j = 1 := if_pos (and.intro rfl rfl) @[simp] lemma E_apply_zero (i' j' : n) (h : ¬(i = i' ∧ j = j')) : E R i j i' j' = 0 := if_neg h @[simp] lemma E_diag_zero (h : j ≠ i) : matrix.diag n R R (E R i j) = 0 := funext $ λ k, if_neg $ λ ⟨e₁, e₂⟩, h (e₂.trans e₁.symm) lemma E_trace_zero (h : j ≠ i) : matrix.trace n R R (E R i j) = 0 := by simp [h] /-- When j ≠ i, the elementary matrices are elements of sl n R, in fact they are part of a natural basis of sl n R. -/ def Eb (h : j ≠ i) : sl n R := ⟨E R i j, show E R i j ∈ linear_map.ker (matrix.trace n R R), from E_trace_zero R i j h⟩ @[simp] lemma Eb_val (h : j ≠ i) : (Eb R i j h).val = E R i j := rfl end elementary_basis lemma sl_non_abelian [nontrivial R] (h : 1 < fintype.card n) : ¬is_lie_abelian ↥(sl n R) := begin rcases fintype.exists_pair_of_one_lt_card h with ⟨j, i, hij⟩, let A := Eb R i j hij, let B := Eb R j i hij.symm, intros c, have c' : A.val ⬝ B.val = B.val ⬝ A.val, by { rw [← sub_eq_zero, ← sl_bracket, c.trivial], refl }, have : (1 : R) = 0 := by simpa [matrix.mul_apply, hij] using (congr_fun (congr_fun c' i) i), exact one_ne_zero this, end end special_linear namespace symplectic /-- The matrix defining the canonical skew-symmetric bilinear form. -/ def J : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 (-1) 1 0 /-- The symplectic Lie algebra: skew-adjoint matrices with respect to the canonical skew-symmetric bilinear form. -/ def sp : lie_subalgebra R (matrix (l ⊕ l) (l ⊕ l) R) := skew_adjoint_matrices_lie_subalgebra (J l R) end symplectic namespace orthogonal /-- The definite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the identity matrix. -/ def so : lie_subalgebra R (matrix n n R) := skew_adjoint_matrices_lie_subalgebra (1 : matrix n n R) @[simp] lemma mem_so (A : matrix n n R) : A ∈ so n R ↔ Aᵀ = -A := begin erw mem_skew_adjoint_matrices_submodule, simp only [matrix.is_skew_adjoint, matrix.is_adjoint_pair, matrix.mul_one, matrix.one_mul], end /-- The indefinite diagonal matrix with `p` 1s and `q` -1s. -/ def indefinite_diagonal : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, -1) /-- The indefinite orthogonal Lie subalgebra: skew-adjoint matrices with respect to the symmetric bilinear form defined by the indefinite diagonal matrix. -/ def so' : lie_subalgebra R (matrix (p ⊕ q) (p ⊕ q) R) := skew_adjoint_matrices_lie_subalgebra $ indefinite_diagonal p q R /-- A matrix for transforming the indefinite diagonal bilinear form into the definite one, provided the parameter `i` is a square root of -1. -/ def Pso (i : R) : matrix (p ⊕ q) (p ⊕ q) R := matrix.diagonal $ sum.elim (λ _, 1) (λ _, i) lemma Pso_inv {i : R} (hi : i*i = -1) : (Pso p q R i) * (Pso p q R (-i)) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end lemma is_unit_Pso {i : R} (hi : i*i = -1) : is_unit (Pso p q R i) := ⟨{ val := Pso p q R i, inv := Pso p q R (-i), val_inv := Pso_inv p q R hi, inv_val := by { apply matrix.nonsing_inv_left_right, exact Pso_inv p q R hi, }, }, rfl⟩ lemma indefinite_diagonal_transform {i : R} (hi : i*i = -1) : (Pso p q R i)ᵀ ⬝ (indefinite_diagonal p q R) ⬝ (Pso p q R i) = 1 := begin ext x y, rcases x; rcases y, { -- x y : p by_cases h : x = y; simp [Pso, indefinite_diagonal, h], }, { -- x : p, y : q simp [Pso, indefinite_diagonal], }, { -- x : q, y : p simp [Pso, indefinite_diagonal], }, { -- x y : q by_cases h : x = y; simp [Pso, indefinite_diagonal, h, hi], }, end /-- An equivalence between the indefinite and definite orthogonal Lie algebras, over a ring containing a square root of -1. -/ noncomputable def so_indefinite_equiv {i : R} (hi : i*i = -1) : so' p q R ≃ₗ⁅R⁆ so (p ⊕ q) R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (indefinite_diagonal p q R) (Pso p q R i) (is_unit_Pso p q R hi)).trans, apply lie_equiv.of_eq, ext A, rw indefinite_diagonal_transform p q R hi, refl, end lemma so_indefinite_equiv_apply {i : R} (hi : i*i = -1) (A : so' p q R) : (so_indefinite_equiv p q R hi A : matrix (p ⊕ q) (p ⊕ q) R) = (Pso p q R i)⁻¹ ⬝ (A : matrix (p ⊕ q) (p ⊕ q) R) ⬝ (Pso p q R i) := by erw [lie_equiv.trans_apply, lie_equiv.of_eq_apply, skew_adjoint_matrices_lie_subalgebra_equiv_apply] /-- A matrix defining a canonical even-rank symmetric bilinear form. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 0 1 ] [ 1 0 ] -/ def JD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 1 1 0 /-- The classical Lie algebra of type D as a Lie subalgebra of matrices associated to the matrix `JD`. -/ def type_D := skew_adjoint_matrices_lie_subalgebra (JD l R) /-- A matrix transforming the bilinear form defined by the matrix `JD` into a split-signature diagonal matrix. It looks like this as a `2l x 2l` matrix of `l x l` blocks: [ 1 -1 ] [ 1 1 ] -/ def PD : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 1 (-1) 1 1 /-- The split-signature diagonal matrix. -/ def S := indefinite_diagonal l l R lemma S_as_blocks : S l R = matrix.from_blocks 1 0 0 (-1) := begin rw [← matrix.diagonal_one, matrix.diagonal_neg, matrix.from_blocks_diagonal], refl, end lemma JD_transform : (PD l R)ᵀ ⬝ (JD l R) ⬝ (PD l R) = (2 : R) • (S l R) := begin have h : (PD l R)ᵀ ⬝ (JD l R) = matrix.from_blocks 1 1 1 (-1) := by { simp [PD, JD, matrix.from_blocks_transpose, matrix.from_blocks_multiply], }, erw [h, S_as_blocks, matrix.from_blocks_multiply, matrix.from_blocks_smul], congr; simp [two_smul], end lemma PD_inv [invertible (2 : R)] : (PD l R) * (⅟(2 : R) • (PD l R)ᵀ) = 1 := begin have h : ⅟(2 : R) • (1 : matrix l l R) + ⅟(2 : R) • 1 = 1 := by rw [← smul_add, ← (two_smul R _), smul_smul, inv_of_mul_self, one_smul], erw [matrix.from_blocks_transpose, matrix.from_blocks_smul, matrix.mul_eq_mul, matrix.from_blocks_multiply], simp [h], end lemma is_unit_PD [invertible (2 : R)] : is_unit (PD l R) := ⟨{ val := PD l R, inv := ⅟(2 : R) • (PD l R)ᵀ, val_inv := PD_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PD_inv l R, }, }, rfl⟩ /-- An equivalence between two possible definitions of the classical Lie algebra of type D. -/ noncomputable def type_D_equiv_so' [invertible (2 : R)] : type_D l R ≃ₗ⁅R⁆ so' l l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JD l R) (PD l R) (is_unit_PD l R)).trans, apply lie_equiv.of_eq, ext A, rw [JD_transform, ← coe_unit_of_invertible (2 : R), ←units.smul_def, lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], refl, end /-- A matrix defining a canonical odd-rank symmetric bilinear form. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 2 0 0 ] [ 0 0 1 ] [ 0 1 0 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def JB := matrix.from_blocks ((2 : R) • 1 : matrix unit unit R) 0 0 (JD l R) /-- The classical Lie algebra of type B as a Lie subalgebra of matrices associated to the matrix `JB`. -/ def type_B := skew_adjoint_matrices_lie_subalgebra (JB l R) /-- A matrix transforming the bilinear form defined by the matrix `JB` into an almost-split-signature diagonal matrix. It looks like this as a `(2l+1) x (2l+1)` matrix of blocks: [ 1 0 0 ] [ 0 1 -1 ] [ 0 1 1 ] where sizes of the blocks are: [`1 x 1` `1 x l` `1 x l`] [`l x 1` `l x l` `l x l`] [`l x 1` `l x l` `l x l`] -/ def PB := matrix.from_blocks (1 : matrix unit unit R) 0 0 (PD l R) lemma PB_inv [invertible (2 : R)] : (PB l R) * (matrix.from_blocks 1 0 0 (PD l R)⁻¹) = 1 := begin simp [PB, matrix.from_blocks_multiply, (PD l R).mul_nonsing_inv, is_unit_PD, ← (PD l R).is_unit_iff_is_unit_det] end lemma is_unit_PB [invertible (2 : R)] : is_unit (PB l R) := ⟨{ val := PB l R, inv := matrix.from_blocks 1 0 0 (PD l R)⁻¹, val_inv := PB_inv l R, inv_val := by { apply matrix.nonsing_inv_left_right, exact PB_inv l R, }, }, rfl⟩ lemma JB_transform : (PB l R)ᵀ ⬝ (JB l R) ⬝ (PB l R) = (2 : R) • matrix.from_blocks 1 0 0 (S l R) := by simp [PB, JB, JD_transform, matrix.from_blocks_transpose, matrix.from_blocks_multiply, matrix.from_blocks_smul] lemma indefinite_diagonal_assoc : indefinite_diagonal (unit ⊕ l) l R = matrix.reindex_lie_equiv (equiv.sum_assoc unit l l).symm (matrix.from_blocks 1 0 0 (indefinite_diagonal l l R)) := begin ext i j, rcases i with ⟨⟨i₁ | i₂⟩ | i₃⟩; rcases j with ⟨⟨j₁ | j₂⟩ | j₃⟩; simp only [indefinite_diagonal, matrix.diagonal, equiv.sum_assoc_apply_in1, matrix.reindex_lie_equiv_apply, matrix.minor_apply, equiv.symm_symm, matrix.reindex_apply, sum.elim_inl, if_true, eq_self_iff_true, matrix.one_apply_eq, matrix.from_blocks_apply₁₁, dmatrix.zero_apply, equiv.sum_assoc_apply_in2, if_false, matrix.from_blocks_apply₁₂, matrix.from_blocks_apply₂₁, matrix.from_blocks_apply₂₂, equiv.sum_assoc_apply_in3, sum.elim_inr]; congr, end /-- An equivalence between two possible definitions of the classical Lie algebra of type B. -/ noncomputable def type_B_equiv_so' [invertible (2 : R)] : type_B l R ≃ₗ⁅R⁆ so' (unit ⊕ l) l R := begin apply (skew_adjoint_matrices_lie_subalgebra_equiv (JB l R) (PB l R) (is_unit_PB l R)).trans, symmetry, apply (skew_adjoint_matrices_lie_subalgebra_equiv_transpose (indefinite_diagonal (unit ⊕ l) l R) (matrix.reindex_alg_equiv _ (equiv.sum_assoc punit l l)) (matrix.transpose_reindex _ _)).trans, apply lie_equiv.of_eq, ext A, rw [JB_transform, ← coe_unit_of_invertible (2 : R), ←units.smul_def, lie_subalgebra.mem_coe, lie_subalgebra.mem_coe, mem_skew_adjoint_matrices_lie_subalgebra_unit_smul], simpa [indefinite_diagonal_assoc], end end orthogonal end lie_algebra
8b15c7c70efbc8557e6faaa08116b4f30724502a
bb31430994044506fa42fd667e2d556327e18dfe
/src/linear_algebra/pi_tensor_product.lean
d50bc7c91cf76ed37b93588755399f5f07def82b
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
24,378
lean
/- Copyright (c) 2020 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Eric Wieser -/ import group_theory.congruence import linear_algebra.multilinear.tensor_product /-! # Tensor product of an indexed family of modules over commutative semirings We define the tensor product of an indexed family `s : ι → Type*` of modules over commutative semirings. We denote this space by `⨂[R] i, s i` and define it as `free_add_monoid (R × Π i, s i)` quotiented by the appropriate equivalence relation. The treatment follows very closely that of the binary tensor product in `linear_algebra/tensor_product.lean`. ## Main definitions * `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. * `tprod R f` with `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`. This is bundled as a multilinear map from `Π i, s i` to `⨂[R] i, s i`. * `lift_add_hom` constructs an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. * `lift φ` with `φ : multilinear_map R s E` is the corresponding linear map `(⨂[R] i, s i) →ₗ[R] E`. This is bundled as a linear equivalence. * `pi_tensor_product.reindex e` re-indexes the components of `⨂[R] i : ι, M` along `e : ι ≃ ι₂`. * `pi_tensor_product.tmul_equiv` equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product`. ## Notations * `⨂[R] i, s i` is defined as localized notation in locale `tensor_product` * `⨂ₜ[R] i, f i` with `f : Π i, f i` is defined globally as the tensor product of all the `f i`'s. ## Implementation notes * We define it via `free_add_monoid (R × Π i, s i)` with the `R` representing a "hidden" tensor factor, rather than `free_add_monoid (Π i, s i)` to ensure that, if `ι` is an empty type, the space is isomorphic to the base ring `R`. * We have not restricted the index type `ι` to be a `fintype`, as nothing we do here strictly requires it. However, problems may arise in the case where `ι` is infinite; use at your own caution. ## TODO * Define tensor powers, symmetric subspace, etc. * API for the various ways `ι` can be split into subsets; connect this with the binary tensor product. * Include connection with holors. * Port more of the API from the binary tensor product over to this case. ## Tags multilinear, tensor, tensor product -/ open function section semiring variables {ι ι₂ ι₃ : Type*} [decidable_eq ι] [decidable_eq ι₂] [decidable_eq ι₃] variables {R : Type*} [comm_semiring R] variables {R₁ R₂ : Type*} variables {s : ι → Type*} [∀ i, add_comm_monoid (s i)] [∀ i, module R (s i)] variables {M : Type*} [add_comm_monoid M] [module R M] variables {E : Type*} [add_comm_monoid E] [module R E] variables {F : Type*} [add_comm_monoid F] namespace pi_tensor_product include R variables (R) (s) /-- The relation on `free_add_monoid (R × Π i, s i)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (R × Π i, s i) → free_add_monoid (R × Π i, s i) → Prop | of_zero : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), eqv (free_add_monoid.of (r, f)) 0 | of_zero_scalar : ∀ (f : Π i, s i), eqv (free_add_monoid.of (0, f)) 0 | of_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), eqv (free_add_monoid.of (r, update f i m₁) + free_add_monoid.of (r, update f i m₂)) (free_add_monoid.of (r, update f i (m₁ + m₂))) | of_add_scalar : ∀ (r r' : R) (f : Π i, s i), eqv (free_add_monoid.of (r, f) + free_add_monoid.of (r', f)) (free_add_monoid.of (r + r', f)) | of_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R), eqv (free_add_monoid.of (r, update f i (r' • (f i)))) (free_add_monoid.of (r' * r, f)) | add_comm : ∀ x y, eqv (x + y) (y + x) end pi_tensor_product variables (R) (s) /-- `pi_tensor_product R s` with `R` a commutative semiring and `s : ι → Type*` is the tensor product of all the `s i`'s. This is denoted by `⨂[R] i, s i`. -/ def pi_tensor_product : Type* := (add_con_gen (pi_tensor_product.eqv R s)).quotient variables {R} /- This enables the notation `⨂[R] i : ι, s i` for the pi tensor product, given `s : ι → Type*`. -/ localized "notation (name := pi_tensor_product) `⨂[`:100 R `] ` binders `, ` r:(scoped:67 f, pi_tensor_product R f) := r" in tensor_product open_locale tensor_product namespace pi_tensor_product section module instance : add_comm_monoid (⨂[R] i, s i) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (pi_tensor_product.eqv R s)).add_monoid } instance : inhabited (⨂[R] i, s i) := ⟨0⟩ variables (R) {s} /-- `tprod_coeff R r f` with `r : R` and `f : Π i, s i` is the tensor product of the vectors `f i` over all `i : ι`, multiplied by the coefficient `r`. Note that this is meant as an auxiliary definition for this file alone, and that one should use `tprod` defined below for most purposes. -/ def tprod_coeff (r : R) (f : Π i, s i) : ⨂[R] i, s i := add_con.mk' _ $ free_add_monoid.of (r, f) variables {R} lemma zero_tprod_coeff (f : Π i, s i) : tprod_coeff R 0 f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_scalar _ lemma zero_tprod_coeff' (z : R) (f : Π i, s i) (i : ι) (hf: f i = 0) : tprod_coeff R z f = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero _ _ i hf lemma add_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i) : tprod_coeff R z (update f i m₁) + tprod_coeff R z (update f i m₂) = tprod_coeff R z (update f i (m₁ + m₂)) := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add z f i m₁ m₂) lemma add_tprod_coeff' (z₁ z₂ : R) (f : Π i, s i) : tprod_coeff R z₁ f + tprod_coeff R z₂ f = tprod_coeff R (z₁ + z₂) f := quotient.sound' $ add_con_gen.rel.of _ _ (eqv.of_add_scalar z₁ z₂ f) lemma smul_tprod_coeff_aux (z : R) (f : Π i, s i) (i : ι) (r : R) : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r * z) f := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _ _ lemma smul_tprod_coeff (z : R) (f : Π i, s i) (i : ι) (r : R₁) [has_smul R₁ R] [is_scalar_tower R₁ R R] [has_smul R₁ (s i)] [is_scalar_tower R₁ R (s i)] : tprod_coeff R z (update f i (r • f i)) = tprod_coeff R (r • z) f := begin have h₁ : r • z = (r • (1 : R)) * z := by rw [smul_mul_assoc, one_mul], have h₂ : r • (f i) = (r • (1 : R)) • f i := (smul_one_smul _ _ _).symm, rw [h₁, h₂], exact smul_tprod_coeff_aux z f i _, end /-- Construct an `add_monoid_hom` from `(⨂[R] i, s i)` to some space `F` from a function `φ : (R × Π i, s i) → F` with the appropriate properties. -/ def lift_add_hom (φ : (R × Π i, s i) → F) (C0 : ∀ (r : R) (f : Π i, s i) (i : ι) (hf : f i = 0), φ (r, f) = 0) (C0' : ∀ (f : Π i, s i), φ (0, f) = 0) (C_add : ∀ (r : R) (f : Π i, s i) (i : ι) (m₁ m₂ : s i), φ (r, update f i m₁) + φ (r, update f i m₂) = φ (r, update f i (m₁ + m₂))) (C_add_scalar : ∀ (r r' : R) (f : Π i, s i), φ (r , f) + φ (r', f) = φ (r + r', f)) (C_smul : ∀ (r : R) (f : Π i, s i) (i : ι) (r' : R), φ (r, update f i (r' • (f i))) = φ (r' * r, f)) : (⨂[R] i, s i) →+ F := (add_con_gen (pi_tensor_product.eqv R s)).lift (free_add_monoid.lift φ) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero r' f i hf) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0 r' f i hf] | _, _, (eqv.of_zero_scalar f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C0'] | _, _, (eqv.of_add z f i m₁ m₂) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_add] | _, _, (eqv.of_add_scalar z₁ z₂ f) := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_add_scalar] | _, _, (eqv.of_smul z f i r') := (add_con.ker_rel _).2 $ by simp [free_add_monoid.lift_eval_of, C_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end @[elab_as_eliminator] protected theorem induction_on' {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (tprod_coeff R r f)) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin have C0 : C 0, { have h₁ := @C1 0 0, rwa [zero_tprod_coeff] at h₁ }, refine add_con.induction_on z (λ x, free_add_monoid.rec_on x C0 _), simp_rw add_con.coe_add, refine λ f y ih, Cp _ ih, convert @C1 f.1 f.2, simp only [prod.mk.eta], end section distrib_mul_action variables [monoid R₁] [distrib_mul_action R₁ R] [smul_comm_class R₁ R R] variables [monoid R₂] [distrib_mul_action R₂ R] [smul_comm_class R₂ R R] -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance has_smul' : has_smul R₁ (⨂[R] i, s i) := ⟨λ r, lift_add_hom (λ f : R × Π i, s i, tprod_coeff R (r • f.1) f.2) (λ r' f i hf, by simp_rw [zero_tprod_coeff' _ f i hf]) (λ f, by simp [zero_tprod_coeff]) (λ r' f i m₁ m₂, by simp [add_tprod_coeff]) (λ r' r'' f, by simp [add_tprod_coeff', mul_add]) (λ z f i r', by simp [smul_tprod_coeff, mul_smul_comm])⟩ instance : has_smul R (⨂[R] i, s i) := pi_tensor_product.has_smul' lemma smul_tprod_coeff' (r : R₁) (z : R) (f : Π i, s i) : r • (tprod_coeff R z f) = tprod_coeff R (r • z) f := rfl protected theorem smul_add (r : R₁) (x y : ⨂[R] i, s i) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ instance distrib_mul_action' : distrib_mul_action R₁ (⨂[R] i, s i) := { smul := (•), smul_add := λ r x y, add_monoid_hom.map_add _ _ _, mul_smul := λ r r' x, pi_tensor_product.induction_on' x (λ r'' f, by simp [smul_tprod_coeff', smul_smul]) (λ x y ihx ihy, by simp_rw [pi_tensor_product.smul_add, ihx, ihy]), one_smul := λ x, pi_tensor_product.induction_on' x (λ f, by simp [smul_tprod_coeff' _ _]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy]), smul_zero := λ r, add_monoid_hom.map_zero _ } instance smul_comm_class' [smul_comm_class R₁ R₂ R] : smul_comm_class R₁ R₂ (⨂[R] i, s i) := ⟨λ r' r'' x, pi_tensor_product.induction_on' x (λ xr xf, by simp only [smul_tprod_coeff', smul_comm]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy])⟩ instance is_scalar_tower' [has_smul R₁ R₂] [is_scalar_tower R₁ R₂ R] : is_scalar_tower R₁ R₂ (⨂[R] i, s i) := ⟨λ r' r'' x, pi_tensor_product.induction_on' x (λ xr xf, by simp only [smul_tprod_coeff', smul_assoc]) (λ z y ihz ihy, by simp_rw [pi_tensor_product.smul_add, ihz, ihy])⟩ end distrib_mul_action -- Most of the time we want the instance below this one, which is easier for typeclass resolution -- to find. instance module' [semiring R₁] [module R₁ R] [smul_comm_class R₁ R R] : module R₁ (⨂[R] i, s i) := { smul := (•), add_smul := λ r r' x, pi_tensor_product.induction_on' x (λ r f, by simp [smul_tprod_coeff' _ _, add_smul, add_tprod_coeff']) (λ x y ihx ihy, by simp [pi_tensor_product.smul_add, ihx, ihy, add_add_add_comm]), zero_smul := λ x, pi_tensor_product.induction_on' x (λ r f, by { simp_rw [smul_tprod_coeff' _ _, zero_smul], exact zero_tprod_coeff _ }) (λ x y ihx ihy, by rw [pi_tensor_product.smul_add, ihx, ihy, add_zero]), ..pi_tensor_product.distrib_mul_action' } -- shortcut instances instance : module R (⨂[R] i, s i) := pi_tensor_product.module' instance : smul_comm_class R R (⨂[R] i, s i) := pi_tensor_product.smul_comm_class' instance : is_scalar_tower R R (⨂[R] i, s i) := pi_tensor_product.is_scalar_tower' variables {R} variables (R) /-- The canonical `multilinear_map R s (⨂[R] i, s i)`. -/ def tprod : multilinear_map R s (⨂[R] i, s i) := { to_fun := tprod_coeff R 1, map_add' := λ f i x y, (add_tprod_coeff (1 : R) f i x y).symm, map_smul' := λ f i r x, by simp_rw [smul_tprod_coeff', ←smul_tprod_coeff (1 : R) _ i, update_idem, update_same] } variables {R} notation `⨂ₜ[`:100 R`] ` binders `, ` r:(scoped:67 f, tprod R f) := r @[simp] lemma tprod_coeff_eq_smul_tprod (z : R) (f : Π i, s i) : tprod_coeff R z f = z • tprod R f := begin have : z = z • (1 : R) := by simp only [mul_one, algebra.id.smul_eq_mul], conv_lhs { rw this }, rw ←smul_tprod_coeff', refl, end @[elab_as_eliminator] protected theorem induction_on {C : (⨂[R] i, s i) → Prop} (z : ⨂[R] i, s i) (C1 : ∀ {r : R} {f : Π i, s i}, C (r • (tprod R f))) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := begin simp_rw ←tprod_coeff_eq_smul_tprod at C1, exact pi_tensor_product.induction_on' z @C1 @Cp, end @[ext] theorem ext {φ₁ φ₂ : (⨂[R] i, s i) →ₗ[R] E} (H : φ₁.comp_multilinear_map (tprod R) = φ₂.comp_multilinear_map (tprod R)) : φ₁ = φ₂ := begin refine linear_map.ext _, refine λ z, (pi_tensor_product.induction_on' z _ (λ x y hx hy, by rw [φ₁.map_add, φ₂.map_add, hx, hy])), { intros r f, rw [tprod_coeff_eq_smul_tprod, φ₁.map_smul, φ₂.map_smul], apply _root_.congr_arg, exact multilinear_map.congr_fun H f } end end module section multilinear open multilinear_map variables {s} /-- Auxiliary function to constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear map R s E` with the property that its composition with the canonical `multilinear_map R s (⨂[R] i, s i)` is the given multilinear map. -/ def lift_aux (φ : multilinear_map R s E) : (⨂[R] i, s i) →+ E := lift_add_hom (λ (p : R × Π i, s i), p.1 • (φ p.2)) (λ z f i hf, by rw [map_coord_zero φ i hf, smul_zero]) (λ f, by rw [zero_smul]) (λ z f i m₁ m₂, by rw [←smul_add, φ.map_add]) (λ z₁ z₂ f, by rw [←add_smul]) (λ z f i r, by simp [φ.map_smul, smul_smul, mul_comm]) lemma lift_aux_tprod (φ : multilinear_map R s E) (f : Π i, s i) : lift_aux φ (tprod R f) = φ f := by simp only [lift_aux, lift_add_hom, tprod, multilinear_map.coe_mk, tprod_coeff, free_add_monoid.lift_eval_of, one_smul, add_con.lift_mk'] lemma lift_aux_tprod_coeff (φ : multilinear_map R s E) (z : R) (f : Π i, s i) : lift_aux φ (tprod_coeff R z f) = z • φ f := by simp [lift_aux, lift_add_hom, tprod_coeff, free_add_monoid.lift_eval_of] lemma lift_aux.smul {φ : multilinear_map R s E} (r : R) (x : ⨂[R] i, s i) : lift_aux φ (r • x) = r • lift_aux φ x := begin refine pi_tensor_product.induction_on' x _ _, { intros z f, rw [smul_tprod_coeff' r z f, lift_aux_tprod_coeff, lift_aux_tprod_coeff, smul_assoc] }, { intros z y ihz ihy, rw [smul_add, (lift_aux φ).map_add, ihz, ihy, (lift_aux φ).map_add, smul_add] } end /-- Constructing a linear map `(⨂[R] i, s i) → E` given a `multilinear_map R s E` with the property that its composition with the canonical `multilinear_map R s E` is the given multilinear map `φ`. -/ def lift : (multilinear_map R s E) ≃ₗ[R] ((⨂[R] i, s i) →ₗ[R] E) := { to_fun := λ φ, { map_smul' := lift_aux.smul, .. lift_aux φ }, inv_fun := λ φ', φ'.comp_multilinear_map (tprod R), left_inv := λ φ, by { ext, simp [lift_aux_tprod, linear_map.comp_multilinear_map] }, right_inv := λ φ, by { ext, simp [lift_aux_tprod] }, map_add' := λ φ₁ φ₂, by { ext, simp [lift_aux_tprod] }, map_smul' := λ r φ₂, by { ext, simp [lift_aux_tprod] } } variables {φ : multilinear_map R s E} @[simp] lemma lift.tprod (f : Π i, s i) : lift φ (tprod R f) = φ f := lift_aux_tprod φ f theorem lift.unique' {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : φ'.comp_multilinear_map (tprod R) = φ) : φ' = lift φ := ext $ H.symm ▸ (lift.symm_apply_apply φ).symm theorem lift.unique {φ' : (⨂[R] i, s i) →ₗ[R] E} (H : ∀ f, φ' (tprod R f) = φ f) : φ' = lift φ := lift.unique' (multilinear_map.ext H) @[simp] theorem lift_symm (φ' : (⨂[R] i, s i) →ₗ[R] E) : lift.symm φ' = φ'.comp_multilinear_map (tprod R) := rfl @[simp] theorem lift_tprod : lift (tprod R : multilinear_map R s _) = linear_map.id := eq.symm $ lift.unique' rfl section variables (R M) /-- Re-index the components of the tensor power by `e`. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def reindex (e : ι ≃ ι₂) : ⨂[R] i : ι, M ≃ₗ[R] ⨂[R] i : ι₂, M := linear_equiv.of_linear (lift (dom_dom_congr e.symm (tprod R : multilinear_map R _ (⨂[R] i : ι₂, M)))) (lift (dom_dom_congr e (tprod R : multilinear_map R _ (⨂[R] i : ι, M)))) (by { ext, simp only [linear_map.comp_apply, linear_map.id_apply, lift_tprod, linear_map.comp_multilinear_map_apply, lift.tprod, dom_dom_congr_apply, equiv.apply_symm_apply] }) (by { ext, simp only [linear_map.comp_apply, linear_map.id_apply, lift_tprod, linear_map.comp_multilinear_map_apply, lift.tprod, dom_dom_congr_apply, equiv.symm_apply_apply] }) end @[simp] lemma reindex_tprod (e : ι ≃ ι₂) (f : Π i, M) : reindex R M e (tprod R f) = tprod R (λ i, f (e.symm i)) := lift_aux_tprod _ f @[simp] lemma reindex_comp_tprod (e : ι ≃ ι₂) : (reindex R M e : ⨂[R] i : ι, M →ₗ[R] ⨂[R] i : ι₂, M).comp_multilinear_map (tprod R) = (tprod R : multilinear_map R (λ i, M) _).dom_dom_congr e.symm := multilinear_map.ext $ reindex_tprod e @[simp] lemma lift_comp_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _ : ι₂, M) E) : (lift φ) ∘ₗ ↑(reindex R M e) = lift (φ.dom_dom_congr e.symm) := by { ext, simp, } @[simp] lemma lift_reindex (e : ι ≃ ι₂) (φ : multilinear_map R (λ _, M) E) (x : ⨂[R] i, M) : lift φ (reindex R M e x) = lift (φ.dom_dom_congr e.symm) x := linear_map.congr_fun (lift_comp_reindex e φ) x @[simp] lemma reindex_trans (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) : (reindex R M e).trans (reindex R M e') = reindex R M (e.trans e') := begin apply linear_equiv.to_linear_map_injective, ext f, simp only [linear_equiv.trans_apply, linear_equiv.coe_coe, reindex_tprod, linear_map.coe_comp_multilinear_map, function.comp_app, multilinear_map.dom_dom_congr_apply, reindex_comp_tprod], congr, end @[simp] lemma reindex_reindex (e : ι ≃ ι₂) (e' : ι₂ ≃ ι₃) (x : ⨂[R] i, M) : reindex R M e' (reindex R M e x) = reindex R M (e.trans e') x := linear_equiv.congr_fun (reindex_trans e e' : _ = reindex R M (e.trans e')) x @[simp] lemma reindex_symm (e : ι ≃ ι₂) : (reindex R M e).symm = reindex R M e.symm := rfl @[simp] lemma reindex_refl : reindex R M (equiv.refl ι) = linear_equiv.refl R _ := begin apply linear_equiv.to_linear_map_injective, ext1, rw [reindex_comp_tprod, linear_equiv.refl_to_linear_map, equiv.refl_symm], refl, end variables (ι) /-- The tensor product over an empty index type `ι` is isomorphic to the base ring. -/ @[simps symm_apply] def is_empty_equiv [is_empty ι] : ⨂[R] i : ι, M ≃ₗ[R] R := { to_fun := lift (const_of_is_empty R _ 1), inv_fun := λ r, r • tprod R (@is_empty_elim _ _ _), left_inv := λ x, by { apply x.induction_on, { intros r f, have := subsingleton.elim f is_empty_elim, simp [this], }, { simp only, intros x y hx hy, simp [add_smul, hx, hy] }}, right_inv := λ t, by simp only [mul_one, algebra.id.smul_eq_mul, const_of_is_empty_apply, linear_map.map_smul, pi_tensor_product.lift.tprod], map_add' := linear_map.map_add _, map_smul' := linear_map.map_smul _, } @[simp] lemma is_empty_equiv_apply_tprod [is_empty ι] (f : ι → M) : is_empty_equiv ι (tprod R f) = 1 := lift.tprod _ variables {ι} /-- The tensor product over an single index is isomorphic to the module -/ @[simps symm_apply] def subsingleton_equiv [subsingleton ι] (i₀ : ι) : ⨂[R] i : ι, M ≃ₗ[R] M := { to_fun := lift (multilinear_map.of_subsingleton R M i₀), inv_fun := λ m, tprod R (λ v, m), left_inv := λ x, by { dsimp only, have : ∀ (f : ι → M) (z : M), (λ i : ι, z) = update f i₀ z, { intros f z, ext i, rw [subsingleton.elim i i₀, function.update_same] }, apply x.induction_on, { intros r f, simp only [linear_map.map_smul, lift.tprod, of_subsingleton_apply, function.eval, this f, multilinear_map.map_smul, update_eq_self], }, { intros x y hx hy, simp only [multilinear_map.map_add, this 0 (_ + _), linear_map.map_add, ←this 0 (lift _ _), hx, hy] } }, right_inv := λ t, by simp only [of_subsingleton_apply, lift.tprod, function.eval_apply], map_add' := linear_map.map_add _, map_smul' := linear_map.map_smul _, } @[simp] lemma subsingleton_equiv_apply_tprod [subsingleton ι] (i : ι) (f : ι → M) : subsingleton_equiv i (tprod R f) = f i := lift.tprod _ section tmul /-- Collapse a `tensor_product` of `pi_tensor_product`s. -/ private def tmul : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) →ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := tensor_product.lift { to_fun := λ a, pi_tensor_product.lift $ pi_tensor_product.lift (multilinear_map.curry_sum_equiv R _ _ M _ (tprod R)) a, map_add' := λ a b, by simp only [linear_equiv.map_add, linear_map.map_add], map_smul' := λ r a, by simp only [linear_equiv.map_smul, linear_map.map_smul, ring_hom.id_apply], } private lemma tmul_apply (a : ι → M) (b : ι₂ → M) : tmul ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := begin erw [tensor_product.lift.tmul, pi_tensor_product.lift.tprod, pi_tensor_product.lift.tprod], refl end /-- Expand `pi_tensor_product` into a `tensor_product` of two factors. -/ private def tmul_symm : ⨂[R] i : ι ⊕ ι₂, M →ₗ[R] (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) := -- by using tactic mode, we avoid the need for a lot of `@`s and `_`s pi_tensor_product.lift $ by apply multilinear_map.dom_coprod; [exact tprod R, exact tprod R] private lemma tmul_symm_apply (a : ι ⊕ ι₂ → M) : tmul_symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := pi_tensor_product.lift.tprod _ variables (R M) local attribute [ext] tensor_product.ext /-- Equivalence between a `tensor_product` of `pi_tensor_product`s and a single `pi_tensor_product` indexed by a `sum` type. For simplicity, this is defined only for homogeneously- (rather than dependently-) typed components. -/ def tmul_equiv : (⨂[R] i : ι, M) ⊗[R] (⨂[R] i : ι₂, M) ≃ₗ[R] ⨂[R] i : ι ⊕ ι₂, M := linear_equiv.of_linear tmul tmul_symm (by { ext x, show tmul (tmul_symm (tprod R x)) = tprod R x, -- Speed up the call to `simp`. simp only [tmul_symm_apply, tmul_apply, sum.elim_comp_inl_inr], }) (by { ext x y, show tmul_symm (tmul (tprod R x ⊗ₜ[R] tprod R y)) = tprod R x ⊗ₜ[R] tprod R y, simp only [tmul_apply, tmul_symm_apply, sum.elim_inl, sum.elim_inr], }) @[simp] lemma tmul_equiv_apply (a : ι → M) (b : ι₂ → M) : tmul_equiv R M ((⨂ₜ[R] i, a i) ⊗ₜ[R] (⨂ₜ[R] i, b i)) = ⨂ₜ[R] i, sum.elim a b i := tmul_apply a b @[simp] lemma tmul_equiv_symm_apply (a : ι ⊕ ι₂ → M) : (tmul_equiv R M).symm (⨂ₜ[R] i, a i) = (⨂ₜ[R] i, a (sum.inl i)) ⊗ₜ[R] (⨂ₜ[R] i, a (sum.inr i)) := tmul_symm_apply a end tmul end multilinear end pi_tensor_product end semiring section ring namespace pi_tensor_product open pi_tensor_product open_locale tensor_product variables {ι : Type*} [decidable_eq ι] {R : Type*} [comm_ring R] variables {s : ι → Type*} [∀ i, add_comm_group (s i)] [∀ i, module R (s i)] /- Unlike for the binary tensor product, we require `R` to be a `comm_ring` here, otherwise this is false in the case where `ι` is empty. -/ instance : add_comm_group (⨂[R] i, s i) := module.add_comm_monoid_to_add_comm_group R end pi_tensor_product end ring
49f9f98a493e241210d26dc2934c737066e3ab88
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/zmod_as_fin2.lean
8c830ec67f475098e56d069b4fce06fd57131dc4
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
8,564
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.int.modeq data.int.basic data.nat.modeq data.fintype data.nat.prime data.nat.gcd lemma int.coe_nat_ne_zero_of_pos {n : ℕ} (hn : 0 < n) : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 hn)).symm lemma int.coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := int.coe_nat_le.2 (nat.zero_le _) class pos_nat (n : ℕ) := (pos : 0 < n) instance succ_pos_nat (n : ℕ) : pos_nat (nat.succ n) := ⟨nat.succ_pos _⟩ attribute [class] nat.prime instance pos_nat_of_prime (p : ℕ) [hp : nat.prime p] : pos_nat p := ⟨hp.pos⟩ open nat nat.modeq int def Zmod := fin namespace Zmod instance {n : ℕ} : has_neg (Zmod n) := ⟨λ a, ⟨nat_mod (-(a.1 : ℤ)) n, begin cases n with n, { exact (nat.not_lt_zero _ a.2).elim }, { have h : (nat.succ n : ℤ) ≠ 0 := dec_trivial, rw [← int.coe_nat_lt, nat_mod, to_nat_of_nonneg (int.mod_nonneg _ h)], exact int.mod_lt _ h } end⟩⟩ instance (n : ℕ) : add_comm_semigroup (Zmod n) := { add := @has_add.add (fin n) fin.has_add, add_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (show ((a + b) % n + c) ≡ (a + (b + c) % n) [MOD n], from calc ((a + b) % n + c) ≡ a + b + c [MOD n] : modeq_add (nat.mod_mod _ _) rfl ... ≡ a + (b + c) [MOD n] : by rw add_assoc ... ≡ (a + (b + c) % n) [MOD n] : modeq_add rfl (nat.mod_mod _ _).symm), add_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a + b) % n = (b + a) % n, by rw add_comm) } instance (n : ℕ) : comm_semigroup (Zmod n) := { mul := @has_mul.mul (fin n) fin.has_mul, mul_assoc := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc ((a * b) % n * c) ≡ a * b * c [MOD n] : modeq_mul (nat.mod_mod _ _) rfl ... ≡ a * (b * c) [MOD n] : by rw mul_assoc ... ≡ a * (b * c % n) [MOD n] : modeq_mul rfl (nat.mod_mod _ _).symm), mul_comm := λ ⟨a, _⟩ ⟨b, _⟩, fin.eq_of_veq (show (a * b) % n = (b * a) % n, by rw mul_comm) } instance (n : ℕ) [h0 : pos_nat n] : has_one (Zmod n) := ⟨⟨1 % n, nat.mod_lt _ h0.pos⟩⟩ instance (n : ℕ) [h0 : pos_nat n] : has_zero (Zmod n) := ⟨⟨0, h0.pos⟩⟩ private lemma one_mul_aux (n : ℕ) [h0 : pos_nat n] : ∀ a : Zmod n, (1 : Zmod n) * a = a := λ ⟨a, ha⟩, fin.eq_of_veq (show (1 % n * a) % n = a, begin resetI, clear _fun_match, cases n with n, { simp }, { cases n with n, { rw [nat.mod_self, zero_mul]; exact (nat.eq_zero_of_le_zero (le_of_lt_succ ha)).symm }, { have h : 1 < n + 2 := dec_trivial, have ha : a < succ (succ n) := ha, rw [nat.mod_eq_of_lt h, one_mul, nat.mod_eq_of_lt ha] } } end) lemma left_distrib_aux (n : ℕ) : ∀ a b c : Zmod n, a * (b + c) = a * b + a * c := λ ⟨a, ha⟩ ⟨b, hb⟩ ⟨c, hc⟩, fin.eq_of_veq (calc a * ((b + c) % n) ≡ a * (b + c) [MOD n] : modeq_mul rfl (nat.mod_mod _ _) ... ≡ a * b + a * c [MOD n] : by rw mul_add ... ≡ (a * b) % n + (a * c) % n [MOD n] : modeq_add (nat.mod_mod _ _).symm (nat.mod_mod _ _).symm) instance (n : ℕ) : distrib (Zmod n) := { left_distrib := left_distrib_aux n, right_distrib := λ a b c, by rw [mul_comm, left_distrib_aux, mul_comm _ b, mul_comm]; refl, ..Zmod.add_comm_semigroup n, ..Zmod.comm_semigroup n } instance (n : ℕ) [h0 : pos_nat n] : comm_ring (Zmod n) := { zero_add := λ ⟨a, ha⟩, fin.eq_of_veq (show (0 + a) % n = a, by rw zero_add; exact nat.mod_eq_of_lt ha), add_zero := λ ⟨a, ha⟩, fin.eq_of_veq (nat.mod_eq_of_lt ha), add_left_neg := λ ⟨a, ha⟩, fin.eq_of_veq (show (((-a : ℤ) % n).to_nat + a) % n = 0, from int.coe_nat_inj begin have hn : (n : ℤ) ≠ 0 := (ne_of_lt (int.coe_nat_lt.2 h0.pos)).symm, rw [int.coe_nat_mod, int.coe_nat_add, to_nat_of_nonneg (int.mod_nonneg _ hn), add_comm], simp, end), one_mul := one_mul_aux n, mul_one := λ a, by rw mul_comm; exact one_mul_aux n a, ..Zmod.has_zero n, ..Zmod.has_one n, ..Zmod.has_neg, ..Zmod.distrib n, ..Zmod.add_comm_semigroup n, ..Zmod.comm_semigroup n } @[simp] lemma val_zero (n : ℕ) [pos_nat n] : (0 : Zmod n).val = 0 := rfl lemma add_val {n : ℕ} : ∀ a b : Zmod n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma mul_val {n : ℕ} : ∀ a b : Zmod n, (a + b).val = (a.val + b.val) % n | ⟨_, _⟩ ⟨_, _⟩ := rfl lemma cast_val_nat {n : ℕ} [pos_nat n] (a : ℕ) : (a : Zmod n).val = a % n := begin induction a with a ih, { rw [nat.zero_mod]; refl }, { rw [succ_eq_add_one, nat.cast_add, add_val, ih], show (a % n + ((0 + (1 % n)) % n)) % n = (a + 1) % n, rw [zero_add, nat.mod_mod], exact nat.modeq.modeq_add (nat.mod_mod a n) (nat.mod_mod 1 n) } end lemma mk_eq_cast {a n : ℕ} (h : a < n) [pos_nat n] : (⟨a, h⟩ : Zmod n) = (a : Zmod n) := fin.eq_of_veq (by rw [cast_val_nat, nat.mod_eq_of_lt h]) @[simp] lemma cast_self_eq_zero (n : ℕ) [pos_nat n] : (n : Zmod n) = 0 := fin.eq_of_veq (show (n : Zmod n).val = 0, by simp [cast_val_nat]) lemma cast_val_of_lt {a n : ℕ} (h : a < n) [pos_nat n] : (a : Zmod n).val = a := by rw [cast_val_nat, nat.mod_eq_of_lt h] @[simp] lemma cast_nat_mod (n : ℕ) [pos_nat n] (a : ℕ) : ((a % n : ℕ) : Zmod n) = a := by conv {to_rhs, rw ← nat.mod_add_div a n}; simp #print cast_nat_mod @[simp] lemma cast_int_mod (n : ℕ) [pos_nat n] (a : ℤ) : ((a % n : ℤ) : Zmod n) = a := by conv {to_rhs, rw ← int.mod_add_div a n}; simp lemma cast_val_int (n : ℕ) [h0 : pos_nat n] (a : ℤ) : (a : Zmod n).val = (a % n).nat_abs := have h : nat_abs (a % n) < n := int.coe_nat_lt.1 begin rw [nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_of_pos h0.pos))], conv {to_rhs, rw ← abs_of_nonneg (int.coe_nat_nonneg n)}, exact int.mod_lt _ (int.coe_nat_ne_zero_of_pos h0.pos) end, int.coe_nat_inj $ by conv {to_lhs, rw [← cast_int_mod n a, ← nat_abs_of_nonneg (mod_nonneg _ (int.coe_nat_ne_zero_of_pos h0.pos)), int.cast_coe_nat, cast_val_of_lt h] } instance Zmod_one.subsingleton : subsingleton (Zmod 1) := ⟨λ a b, fin.eq_of_veq (by rw [eq_zero_of_le_zero (le_of_lt_succ a.2), eq_zero_of_le_zero (le_of_lt_succ b.2)])⟩ instance Zmod_zero.subsingleton : subsingleton (Zmod 0) := ⟨λ a, (nat.not_lt_zero _ a.2).elim⟩ lemma eq_iff_modeq_nat {n : ℕ} [pos_nat n] {a b : ℕ} : (a : Zmod n) = b ↔ a ≡ b [MOD n] := ⟨λ h, by have := fin.veq_of_eq h; rwa [cast_val_nat, cast_val_nat] at this, λ h, fin.eq_of_veq $ by rwa [cast_val_nat, cast_val_nat]⟩ lemma eq_iff_modeq_int {n : ℕ} [h0 : pos_nat n] {a b : ℤ} : (a : Zmod n) = b ↔ a ≡ b [ZMOD n] := ⟨λ h, by have := fin.veq_of_eq h; rwa [cast_val_int, cast_val_int, ← int.coe_nat_eq_coe_nat_iff, nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_of_pos h0.pos)), nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_of_pos h0.pos))] at this, λ h : a % n = b % n, by rw [← cast_int_mod n a, ← cast_int_mod n b, h]⟩ instance (n : ℕ) : fintype (Zmod n) := fin.fintype _ lemma card_Zmod : ∀ n, fintype.card (Zmod n) = n := fintype.card_fin instance (n : ℕ) [pos_nat n] : has_inv (Zmod n) := ⟨λ a, gcd_a a.1 n⟩ lemma gcd_a_modeq (a b : ℕ) : (a : ℤ) * gcd_a a b ≡ nat.gcd a b [ZMOD b] := by rw [← add_zero ((a : ℤ) * _), gcd_eq_gcd_ab]; exact int.modeq.modeq_add rfl (int.modeq.modeq_zero_iff.2 (dvd_mul_right _ _)).symm lemma mul_inv_eq_gcd (n a : ℕ) [pos_nat n]: (a : Zmod n) * a⁻¹ = nat.gcd a n := by rw [← int.cast_coe_nat (nat.gcd _ _), nat.gcd_comm, nat.gcd_rec, ← eq_iff_modeq_int.2 (gcd_a_modeq _ _)]; simp [has_inv.inv, cast_val_nat] private lemma mul_inv_cancel_aux {p : ℕ} [hp : prime p] : ∀ a : Zmod p, a ≠ 0 → a * a⁻¹ = 1 := λ ⟨a, hap⟩ ha0, begin rw [mk_eq_cast, ne.def, ← nat.cast_zero, eq_iff_modeq_nat, modeq_zero_iff] at ha0, have : nat.gcd p a = 1 := (prime.coprime_iff_not_dvd hp).2 ha0, rw [mk_eq_cast hap, mul_inv_eq_gcd, gcd_comm, this, nat.cast_one], end instance {p : ℕ} [hp : prime p] : discrete_field (Zmod p) := { zero_ne_one := fin.ne_of_vne $ show 0 ≠ 1 % p, by rw nat.mod_eq_of_lt hp.gt_one; exact zero_ne_one, mul_inv_cancel := mul_inv_cancel_aux, inv_mul_cancel := λ a, by rw mul_comm; exact mul_inv_cancel_aux _, has_decidable_eq := by apply_instance, inv_zero := show (gcd_a 0 p : Zmod p) = 0, by unfold gcd_a xgcd xgcd_aux; refl, ..Zmod.comm_ring p, ..Zmod.has_inv p } end Zmod
efe070bfc74fe46fe30c5a443d28b4cc1283685f
1fbca480c1574e809ae95a3eda58188ff42a5e41
/src/util/meta/tactic/search.lean
f9c58ab977d6265bb39c72374c2c1dc834e74256
[]
no_license
unitb/lean-lib
560eea0acf02b1fd4bcaac9986d3d7f1a4290e7e
439b80e606b4ebe4909a08b1d77f4f5c0ee3dee9
refs/heads/master
1,610,706,025,400
1,570,144,245,000
1,570,144,245,000
99,579,229
5
0
null
null
null
null
UTF-8
Lean
false
false
1,817
lean
import meta.expr open tactic environment meta def search_some (s : expr → tactic bool) (hide_prefixed : bool := tt) : tactic unit := do env ← get_env, env.fold (pure ()) $ λ d acc, do acc, try $ do declaration.thm n _ ty _ ← pure d | skip, when (¬ hide_prefixed ∨ n.last.front ≠ '_') $ do occ ← s ty, when occ $ do ty ← pp ty, trace $ to_fmt n ++ ": " ++ ty meta def search_about (s : name) : tactic unit := do s ← resolve_constant s, search_some $ λ ty, return $ ty.fold ff (λ e _ acc, acc ∨ e.is_constant_of s) meta def match_head (pat : pattern) : expr → tactic bool | ty := tt <$ match_pattern pat ty <|> match ty with | (expr.pi n bi t e) := do l ← mk_local' n bi t, match_head (e.instantiate_var l) | _ := pure ff end meta def match_asm (pat : pattern) : expr → tactic bool | ty := match ty with | (expr.pi n bi t e) := do l ← mk_local' n bi t, tt <$ match_pattern pat t <|> match_asm (e.instantiate_var l) | _ := pure ff end meta def search (p : pexpr) : tactic unit := do new_p ← pexpr_to_pattern p, search_some $ λ ty, match_head new_p ty meta def search_asm (p : pexpr) : tactic unit := do new_p ← pexpr_to_pattern p, search_some $ λ ty, match_asm new_p ty def m_or {m : Type* → Type*} [monad m] (x y : m bool) : m bool := do b ← x, if b then pure tt else y infixl ` || ` := m_or meta def search_rw (p : pexpr) : tactic unit := do left_p ← pexpr_to_pattern ``(%%p = _), right_p ← pexpr_to_pattern ``(_ = %%p), search_some $ λ ty, match_head left_p ty || match_head right_p ty -- run_cmd search_about `has_add -- run_cmd search ``(_ = _) -- run_cmd search_asm ``(_ ≤ 0) -- run_cmd search_rw ``(_ + (_ + _))
0e595cc3b9b3f784c491713323ae397d712ca14d
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/ScopedEnvExtension.lean
475da37e77403ea72e1fddd39756bb78092b39b5
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
8,494
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment import Lean.Data.NameTrie import Lean.Attributes namespace Lean namespace ScopedEnvExtension inductive Entry (α : Type) where | global : α → Entry α | scoped : Name → α → Entry α structure State (σ : Type) where state : σ activeScopes : NameSet := {} structure ScopedEntries (β : Type) where map : SMap Name (PArray β) := {} deriving Inhabited structure StateStack (α : Type) (β : Type) (σ : Type) where stateStack : List (State σ) := {} scopedEntries : ScopedEntries β := {} newEntries : List (Entry α) := [] deriving Inhabited structure Descr (α : Type) (β : Type) (σ : Type) where name : Name mkInitial : IO σ ofOLeanEntry : σ → α → ImportM β toOLeanEntry : β → α addEntry : σ → β → σ finalizeImport : σ → σ := id instance [Inhabited α] : Inhabited (Descr α β σ) where default := { name := default mkInitial := default ofOLeanEntry := default toOLeanEntry := default addEntry := fun s _ => s } def mkInitial (descr : Descr α β σ) : IO (StateStack α β σ) := return { stateStack := [ { state := (← descr.mkInitial ) } ] } def ScopedEntries.insert (scopedEntries : ScopedEntries β) (ns : Name) (b : β) : ScopedEntries β := match scopedEntries.map.find? ns with | none => { map := scopedEntries.map.insert ns <| ({} : PArray β).push b } | some bs => { map := scopedEntries.map.insert ns <| bs.push b } def addImportedFn (descr : Descr α β σ) (as : Array (Array (Entry α))) : ImportM (StateStack α β σ) := do let mut s ← descr.mkInitial let mut scopedEntries : ScopedEntries β := {} for a in as do for e in a do match e with | Entry.global a => let b ← descr.ofOLeanEntry s a s := descr.addEntry s b | Entry.scoped ns a => let b ← descr.ofOLeanEntry s a scopedEntries := scopedEntries.insert ns b s := descr.finalizeImport s return { stateStack := [ { state := s } ], scopedEntries := scopedEntries } def addEntryFn (descr : Descr α β σ) (s : StateStack α β σ) (e : Entry β) : StateStack α β σ := match s with | { stateStack := stateStack, scopedEntries := scopedEntries, newEntries := newEntries } => match e with | Entry.global b => { scopedEntries := scopedEntries newEntries := (Entry.global (descr.toOLeanEntry b)) :: newEntries stateStack := stateStack.map fun s => { s with state := descr.addEntry s.state b } } | Entry.«scoped» ns b => { scopedEntries := scopedEntries.insert ns b newEntries := (Entry.«scoped» ns (descr.toOLeanEntry b)) :: newEntries stateStack := stateStack.map fun s => if s.activeScopes.contains ns then { s with state := descr.addEntry s.state b } else s } def exportEntriesFn (s : StateStack α β σ) : Array (Entry α) := s.newEntries.toArray.reverse end ScopedEnvExtension open ScopedEnvExtension structure ScopedEnvExtension (α : Type) (β : Type) (σ : Type) where descr : Descr α β σ ext : PersistentEnvExtension (Entry α) (Entry β) (StateStack α β σ) deriving Inhabited builtin_initialize scopedEnvExtensionsRef : IO.Ref (Array (ScopedEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) ← IO.mkRef #[] unsafe def registerScopedEnvExtensionUnsafe (descr : Descr α β σ) : IO (ScopedEnvExtension α β σ) := do let ext ← registerPersistentEnvExtension { name := descr.name mkInitial := mkInitial descr addImportedFn := addImportedFn descr addEntryFn := addEntryFn descr exportEntriesFn := exportEntriesFn statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length } let ext := { descr := descr, ext := ext : ScopedEnvExtension α β σ } scopedEnvExtensionsRef.modify fun exts => exts.push (unsafeCast ext) return ext @[implementedBy registerScopedEnvExtensionUnsafe] opaque registerScopedEnvExtension (descr : Descr α β σ) : IO (ScopedEnvExtension α β σ) def ScopedEnvExtension.pushScope (ext : ScopedEnvExtension α β σ) (env : Environment) : Environment := let s := ext.ext.getState env match s.stateStack with | [] => env | state :: stack => ext.ext.setState env { s with stateStack := state :: state :: stack } def ScopedEnvExtension.popScope (ext : ScopedEnvExtension α β σ) (env : Environment) : Environment := let s := ext.ext.getState env match s.stateStack with | _ :: state₂ :: stack => ext.ext.setState env { s with stateStack := state₂ :: stack } | _ => env def ScopedEnvExtension.addEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (b : β) : Environment := ext.ext.addEntry env (Entry.global b) def ScopedEnvExtension.addScopedEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (namespaceName : Name) (b : β) : Environment := ext.ext.addEntry env (Entry.«scoped» namespaceName b) def ScopedEnvExtension.addLocalEntry (ext : ScopedEnvExtension α β σ) (env : Environment) (b : β) : Environment := let s := ext.ext.getState env match s.stateStack with | [] => env | top :: states => let top := { top with state := ext.descr.addEntry top.state b } ext.ext.setState env { s with stateStack := top :: states } def ScopedEnvExtension.add [Monad m] [MonadResolveName m] [MonadEnv m] (ext : ScopedEnvExtension α β σ) (b : β) (kind := AttributeKind.global) : m Unit := do match kind with | AttributeKind.global => modifyEnv (ext.addEntry · b) | AttributeKind.local => modifyEnv (ext.addLocalEntry · b) | AttributeKind.scoped => modifyEnv (ext.addScopedEntry · (← getCurrNamespace) b) def ScopedEnvExtension.getState [Inhabited σ] (ext : ScopedEnvExtension α β σ) (env : Environment) : σ := match ext.ext.getState env |>.stateStack with | top :: _ => top.state | _ => unreachable! def ScopedEnvExtension.activateScoped (ext : ScopedEnvExtension α β σ) (env : Environment) (namespaceName : Name) : Environment := let s := ext.ext.getState env match s.stateStack with | top :: stack => if top.activeScopes.contains namespaceName then env else let activeScopes := top.activeScopes.insert namespaceName let top := match s.scopedEntries.map.find? namespaceName with | none => { top with activeScopes := activeScopes } | some bs => Id.run do let mut state := top.state for b in bs do state := ext.descr.addEntry state b { state := state, activeScopes := activeScopes } ext.ext.setState env { s with stateStack := top :: stack } | _ => env def ScopedEnvExtension.modifyState (ext : ScopedEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment := let s := ext.ext.getState env match s.stateStack with | top :: stack => ext.ext.setState env { s with stateStack := { top with state := f top.state } :: stack } | _ => env def pushScope [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv ext.pushScope def popScope [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv ext.popScope def activateScoped [Monad m] [MonadEnv m] [MonadLiftT (ST IO.RealWorld) m] (namespaceName : Name) : m Unit := do for ext in (← scopedEnvExtensionsRef.get) do modifyEnv (ext.activateScoped · namespaceName) abbrev SimpleScopedEnvExtension (α : Type) (σ : Type) := ScopedEnvExtension α α σ structure SimpleScopedEnvExtension.Descr (α : Type) (σ : Type) where name : Name addEntry : σ → α → σ initial : σ finalizeImport : σ → σ := id def registerSimpleScopedEnvExtension (descr : SimpleScopedEnvExtension.Descr α σ) : IO (SimpleScopedEnvExtension α σ) := do registerScopedEnvExtension { name := descr.name mkInitial := return descr.initial addEntry := descr.addEntry toOLeanEntry := id ofOLeanEntry := fun _ a => return a finalizeImport := descr.finalizeImport } end Lean
89d4366ebea6cefdff75c765fac94379badb6332
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Data/PrefixTree.lean
e02b3011f8c0c724a303f6ddbcc00bc23722c34e
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
3,841
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.RBMap namespace Lean open Std /- Similar to trie, but for arbitrary keys -/ inductive PrefixTreeNode (α : Type u) (β : Type v) where | Node : Option β → RBNode α (fun _ => PrefixTreeNode α β) → PrefixTreeNode α β instance : Inhabited (PrefixTreeNode α β) where default := PrefixTreeNode.Node none RBNode.leaf namespace PrefixTreeNode def empty : PrefixTreeNode α β := PrefixTreeNode.Node none RBNode.leaf @[specialize] partial def insert (t : PrefixTreeNode α β) (lt : α → α → Bool) (k : List α) (val : β) : PrefixTreeNode α β := let rec insertEmpty (k : List α) : PrefixTreeNode α β := match k with | [] => PrefixTreeNode.Node (some val) RBNode.leaf | k :: ks => let t := insertEmpty ks PrefixTreeNode.Node none (RBNode.singleton k t) let rec loop | PrefixTreeNode.Node v m, [] => PrefixTreeNode.Node (some val) m -- overrides old value | PrefixTreeNode.Node v m, k :: ks => let t := match RBNode.find lt m k with | none => insertEmpty ks | some t => loop t ks PrefixTreeNode.Node v (RBNode.insert lt m k t) loop t k @[specialize] partial def find? (t : PrefixTreeNode α β) (lt : α → α → Bool) (k : List α) : Option β := let rec loop | PrefixTreeNode.Node val m, [] => val | PrefixTreeNode.Node val m, k :: ks => match RBNode.find lt m k with | none => none | some t => loop t ks loop t k @[specialize] partial def foldMatchingM [Monad m] (t : PrefixTreeNode α β) (lt : α → α → Bool) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := let rec fold : PrefixTreeNode α β → σ → m σ | PrefixTreeNode.Node b? n, d => do let d ← match b? with | none => pure d | some b => f b d n.foldM (init := d) fun d _ t => fold t d let rec find : List α → PrefixTreeNode α β → σ → m σ | [], t, d => fold t d | k::ks, PrefixTreeNode.Node _ m, d => match RBNode.find lt m k with | none => pure init | some t => find ks t d find k t init inductive WellFormed (lt : α → α → Bool) : PrefixTreeNode α β → Prop where | emptyWff : WellFormed lt empty | insertWff {t : PrefixTreeNode α β} {k : List α} {val : β} : WellFormed lt t → WellFormed lt (insert t lt k val) end PrefixTreeNode def PrefixTree (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) := { t : PrefixTreeNode α β // t.WellFormed lt } open PrefixTreeNode def PrefixTree.empty : PrefixTree α β p := ⟨PrefixTreeNode.empty, WellFormed.emptyWff⟩ instance : Inhabited (PrefixTree α β p) where default := PrefixTree.empty instance : EmptyCollection (PrefixTree α β p) where emptyCollection := PrefixTree.empty @[inline] def PrefixTree.insert (t : PrefixTree α β p) (k : List α) (v : β) : PrefixTree α β p := ⟨t.val.insert p k v, WellFormed.insertWff t.property⟩ @[inline] def PrefixTree.find? (t : PrefixTree α β p) (k : List α) : Option β := t.val.find? p k @[inline] def PrefixTree.foldMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (init : σ) (f : β → σ → m σ) : m σ := t.val.foldMatchingM p k init f @[inline] def PrefixTree.foldM [Monad m] (t : PrefixTree α β p) (init : σ) (f : β → σ → m σ) : m σ := t.foldMatchingM [] init f @[inline] def PrefixTree.forMatchingM [Monad m] (t : PrefixTree α β p) (k : List α) (f : β → m Unit) : m Unit := t.val.foldMatchingM p k () (fun b _ => f b) @[inline] def PrefixTree.forM [Monad m] (t : PrefixTree α β p) (f : β → m Unit) : m Unit := t.forMatchingM [] f end Lean
2390e475251c3b60d9d240e82e5801afe79800f2
4727251e0cd73359b15b664c3170e5d754078599
/src/set_theory/ordinal/principal.lean
b2c7bbd834b5bfcb6d6d53dbbc0669332eaea547
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
16,438
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 set_theory.ordinal.fixed_point /-! ### Principal ordinals We define principal or indecomposable ordinals, and we prove the standard properties about them. ### Main definitions and results * `principal`: A principal or indecomposable ordinal under some binary operation. We include 0 and any other typically excluded edge cases for simplicity. * `unbounded_principal`: Principal ordinals are unbounded. * `principal_add_iff_zero_or_omega_opow`: The main characterization theorem for additive principal ordinals. * `principal_mul_iff_le_two_or_omega_opow_opow`: The main characterization theorem for multiplicative principal ordinals. ### Todo * Prove that exponential principal ordinals are 0, 1, 2, ω, or epsilon numbers, i.e. fixed points of `λ x, ω ^ x`. -/ universe u noncomputable theory namespace ordinal local infixr ^ := @pow ordinal ordinal ordinal.has_pow /-! ### Principal ordinals -/ /-- An ordinal `o` is said to be principal or indecomposable under an operation when the set of ordinals less than it is closed under that operation. In standard mathematical usage, this term is almost exclusively used for additive and multiplicative principal ordinals. For simplicity, we break usual convention and regard 0 as principal. -/ def principal (op : ordinal → ordinal → ordinal) (o : ordinal) : Prop := ∀ ⦃a b⦄, a < o → b < o → op a b < o theorem principal_iff_principal_swap {op : ordinal → ordinal → ordinal} {o : ordinal} : principal op o ↔ principal (function.swap op) o := by split; exact λ h a b ha hb, h hb ha theorem principal_zero {op : ordinal → ordinal → ordinal} : principal op 0 := λ a _ h, (ordinal.not_lt_zero a h).elim @[simp] theorem principal_one_iff {op : ordinal → ordinal → ordinal} : principal op 1 ↔ op 0 0 = 0 := begin refine ⟨λ h, _, λ h a b ha hb, _⟩, { rwa ←lt_one_iff_zero, exact h zero_lt_one zero_lt_one }, { rwa [lt_one_iff_zero, ha, hb] at * } end theorem principal.iterate_lt {op : ordinal → ordinal → ordinal} {a o : ordinal} (hao : a < o) (ho : principal op o) (n : ℕ) : (op a)^[n] a < o := begin induction n with n hn, { rwa function.iterate_zero }, { rw function.iterate_succ', exact ho hao hn } end theorem op_eq_self_of_principal {op : ordinal → ordinal → ordinal} {a o : ordinal.{u}} (hao : a < o) (H : is_normal (op a)) (ho : principal op o) (ho' : is_limit o) : op a o = o := begin refine le_antisymm _ (H.self_le _), rw [←is_normal.bsup_eq.{u u} H ho', bsup_le_iff], exact λ b hbo, (ho hao hbo).le end theorem nfp_le_of_principal {op : ordinal → ordinal → ordinal} {a o : ordinal} (hao : a < o) (ho : principal op o) : nfp (op a) a ≤ o := nfp_le $ λ n, (ho.iterate_lt hao n).le /-! ### Principal ordinals are unbounded -/ /-- The least strict upper bound of `op` applied to all pairs of ordinals less than `o`. This is essentially a two-argument version of `ordinal.blsub`. -/ def blsub₂ (op : ordinal → ordinal → ordinal) (o : ordinal) : ordinal := lsub (λ x : o.out.α × o.out.α, op (typein (<) x.1) (typein (<) x.2)) theorem lt_blsub₂ (op : ordinal → ordinal → ordinal) {o : ordinal} {a b : ordinal} (ha : a < o) (hb : b < o) : op a b < blsub₂ op o := begin convert lt_lsub _ (prod.mk (enum (<) a (by rwa type_lt)) (enum (<) b (by rwa type_lt))), simp only [typein_enum] end theorem principal_nfp_blsub₂ (op : ordinal → ordinal → ordinal) (o : ordinal) : principal op (nfp (blsub₂.{u u} op) o) := λ a b ha hb, begin rw lt_nfp at *, cases ha with m hm, cases hb with n hn, cases le_total ((blsub₂.{u u} op)^[m] o) ((blsub₂.{u u} op)^[n] o) with h h, { use n + 1, rw function.iterate_succ', exact lt_blsub₂ op (hm.trans_le h) hn }, { use m + 1, rw function.iterate_succ', exact lt_blsub₂ op hm (hn.trans_le h) }, end theorem unbounded_principal (op : ordinal → ordinal → ordinal) : set.unbounded (<) {o | principal op o} := λ o, ⟨_, principal_nfp_blsub₂ op o, (le_nfp _ o).not_lt⟩ /-! #### Additive principal ordinals -/ theorem principal_add_one : principal (+) 1 := principal_one_iff.2 $ zero_add 0 theorem principal_add_of_le_one {o : ordinal} (ho : o ≤ 1) : principal (+) o := begin rcases le_one_iff.1 ho with rfl | rfl, { exact principal_zero }, { exact principal_add_one } end theorem principal_add_is_limit {o : ordinal} (ho₁ : 1 < o) (ho : principal (+) o) : o.is_limit := begin refine ⟨λ ho₀, _, λ a hao, _⟩, { rw ho₀ at ho₁, exact not_lt_of_gt ordinal.zero_lt_one ho₁ }, { cases eq_or_ne a 0 with ha ha, { rw [ha, succ_zero], exact ho₁ }, { refine lt_of_le_of_lt _ (ho hao hao), rwa [succ_eq_add_one, add_le_add_iff_left, one_le_iff_ne_zero] } } end theorem principal_add_iff_add_left_eq_self {o : ordinal} : principal (+) o ↔ ∀ a < o, a + o = o := begin refine ⟨λ ho a hao, _, λ h a b hao hbo, _⟩, { cases lt_or_le 1 o with ho₁ ho₁, { exact op_eq_self_of_principal hao (add_is_normal a) ho (principal_add_is_limit ho₁ ho) }, { rcases le_one_iff.1 ho₁ with rfl | rfl, { exact (ordinal.not_lt_zero a hao).elim }, { rw lt_one_iff_zero at hao, rw [hao, zero_add] }}}, { rw ←h a hao, exact (add_is_normal a).strict_mono hbo } end theorem exists_lt_add_of_not_principal_add {a} (ha : ¬ principal (+) a) : ∃ (b c) (hb : b < a) (hc : c < a), b + c = a := begin unfold principal at ha, push_neg at ha, rcases ha with ⟨b, c, hb, hc, H⟩, refine ⟨b, _, hb, lt_of_le_of_ne (sub_le_self a b) (λ hab, _), ordinal.add_sub_cancel_of_le hb.le⟩, rw [←sub_le, hab] at H, exact H.not_lt hc end theorem principal_add_iff_add_lt_ne_self {a} : principal (+) a ↔ ∀ ⦃b c⦄, b < a → c < a → b + c ≠ a := ⟨λ ha b c hb hc, (ha hb hc).ne, λ H, begin by_contra' ha, rcases exists_lt_add_of_not_principal_add ha with ⟨b, c, hb, hc, rfl⟩, exact (H hb hc).irrefl end⟩ theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega := begin rcases lt_omega.1 h with ⟨n, rfl⟩, clear h, induction n with n IH, { rw [nat.cast_zero, zero_add] }, { rwa [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _)] } end theorem principal_add_omega : principal (+) omega := principal_add_iff_add_left_eq_self.2 (λ a, add_omega) theorem add_omega_opow {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b := begin refine le_antisymm _ (le_add_left _ _), revert h, refine limit_rec_on b (λ h, _) (λ b _ h, _) (λ b l IH h, _), { rw [opow_zero, ← succ_zero, lt_succ, ordinal.le_zero] at h, rw [h, zero_add] }, { rw opow_succ at h, rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩, refine le_trans (add_le_add_right (le_of_lt ax) _) _, rw [opow_succ, ← mul_add, add_omega xo] }, { rcases (lt_opow_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩, exact (((add_is_normal a).trans (opow_is_normal one_lt_omega)).limit_le l).2 (λ y yb, (add_le_add_left (opow_le_opow_right omega_pos (le_max_right _ _)) _).trans (le_trans (IH _ (max_lt xb yb) (ax.trans_le $ opow_le_opow_right omega_pos (le_max_left _ _))) (opow_le_opow_right omega_pos $ le_of_lt $ max_lt xb yb))) } end theorem principal_add_omega_opow (o : ordinal) : principal (+) (omega ^ o) := principal_add_iff_add_left_eq_self.2 (λ a, add_omega_opow) /-- The main characterization theorem for additive principal ordinals. -/ theorem principal_add_iff_zero_or_omega_opow {o : ordinal} : principal (+) o ↔ o = 0 ∨ ∃ a, o = omega ^ a := begin rcases eq_or_ne o 0 with rfl | ho, { simp only [principal_zero, or.inl] }, { rw [principal_add_iff_add_left_eq_self], simp only [ho, false_or], refine ⟨λ H, ⟨_, ((lt_or_eq_of_le (opow_log_le_self _ (ordinal.pos_iff_ne_zero.2 ho))) .resolve_left $ λ h, _).symm⟩, λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_opow⟩, have := H _ h, have := lt_opow_succ_log_self one_lt_omega o, rw [opow_succ, lt_mul_of_limit omega_is_limit] at this, rcases this with ⟨a, ao, h'⟩, rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao, revert h', apply not_lt_of_le, suffices e : omega ^ log omega o * ↑n + o = o, { simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o }, induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]}, simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH] } end theorem opow_principal_add_of_principal_add {a} (ha : principal (+) a) (b : ordinal) : principal (+) (a ^ b) := begin rcases principal_add_iff_zero_or_omega_opow.1 ha with rfl | ⟨c, rfl⟩, { rcases eq_or_ne b 0 with rfl | hb, { rw opow_zero, exact principal_add_one }, { rwa zero_opow hb } }, { rw ←opow_mul, exact principal_add_omega_opow _ } end theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c := by rw [← ordinal.add_sub_cancel_of_le h₂, ← add_assoc, add_omega_opow h₁] theorem mul_principal_add_is_principal_add (a : ordinal.{u}) {b : ordinal.{u}} (hb₁ : b ≠ 1) (hb : principal (+) b) : principal (+) (a * b) := begin rcases eq_zero_or_pos a with rfl | ha, { rw zero_mul, exact principal_zero }, { rcases eq_zero_or_pos b with rfl | hb₁', { rw mul_zero, exact principal_zero }, { rw [← succ_le,succ_zero] at hb₁', intros c d hc hd, rw lt_mul_of_limit (principal_add_is_limit (lt_of_le_of_ne hb₁' hb₁.symm) hb) at *, { rcases hc with ⟨x, hx, hx'⟩, rcases hd with ⟨y, hy, hy'⟩, use [x + y, hb hx hy], rw mul_add, exact add_lt_add hx' hy' }, assumption' } } end /-! #### Multiplicative principal ordinals -/ theorem principal_mul_one : principal (*) 1 := by { rw principal_one_iff, exact zero_mul _ } theorem principal_mul_two : principal (*) 2 := λ a b ha hb, begin have h₂ : (1 : ordinal).succ = 2 := rfl, rw [←h₂, ordinal.lt_succ] at *, convert mul_le_mul' ha hb, exact (mul_one 1).symm end theorem principal_mul_of_le_two {o : ordinal} (ho : o ≤ 2) : principal (*) o := begin rcases lt_or_eq_of_le ho with ho | rfl, { have h₂ : (1 : ordinal).succ = 2 := rfl, rw [←h₂, ordinal.lt_succ] at ho, rcases lt_or_eq_of_le ho with ho | rfl, { rw lt_one_iff_zero.1 ho, exact principal_zero }, { exact principal_mul_one } }, { exact principal_mul_two } end theorem principal_add_of_principal_mul {o : ordinal} (ho : principal (*) o) (ho₂ : o ≠ 2) : principal (+) o := begin cases lt_or_gt_of_ne ho₂ with ho₁ ho₂, { change o < succ 1 at ho₁, rw lt_succ at ho₁, exact principal_add_of_le_one ho₁ }, { refine λ a b hao hbo, lt_of_le_of_lt _ (ho (max_lt hao hbo) ho₂), rw mul_two, exact add_le_add (le_max_left a b) (le_max_right a b) } end theorem principal_mul_is_limit {o : ordinal.{u}} (ho₂ : 2 < o) (ho : principal (*) o) : o.is_limit := principal_add_is_limit ((ordinal.lt_succ_self 1).trans ho₂) (principal_add_of_principal_mul ho (ne_of_gt ho₂)) theorem principal_mul_iff_mul_left_eq {o : ordinal} : principal (*) o ↔ ∀ a, 0 < a → a < o → a * o = o := begin refine ⟨λ h a ha₀ hao, _, λ h a b hao hbo, _⟩, { cases le_or_gt o 2 with ho ho, { convert one_mul o, apply le_antisymm, { have : a < succ 1 := hao.trans_le ho, rwa lt_succ at this }, { rwa [←succ_le, succ_zero] at ha₀ } }, { exact op_eq_self_of_principal hao (mul_is_normal ha₀) h (principal_mul_is_limit ho h) } }, { rcases eq_or_ne a 0 with rfl | ha, { rwa zero_mul }, rw ←ordinal.pos_iff_ne_zero at ha, rw ←h a ha hao, exact (mul_is_normal ha).strict_mono hbo } end theorem principal_mul_omega : principal (*) omega := λ a b ha hb, match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by { rw [← nat_cast_mul], apply nat_lt_omega } end theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega := principal_mul_iff_mul_left_eq.1 (principal_mul_omega) a a0 ha theorem mul_lt_omega_opow {a b c : ordinal} (c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c := begin rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l, { exact (lt_irrefl _).elim c0 }, { rw opow_succ at ha, rcases ((mul_is_normal $ opow_pos _ omega_pos).limit_lt omega_is_limit).1 ha with ⟨n, hn, an⟩, apply (mul_le_mul_right' (le_of_lt an) _).trans_lt, rw [opow_succ, mul_assoc, mul_lt_mul_iff_left (opow_pos _ omega_pos)], exact principal_mul_omega hn hb }, { rcases ((opow_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩, refine (mul_le_mul' (le_of_lt ax) (le_of_lt hb)).trans_lt _, rw [← opow_succ, opow_lt_opow_iff_right one_lt_omega], exact l.2 _ hx } end theorem mul_omega_opow_opow {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) : a * omega ^ omega ^ b = omega ^ omega ^ b := begin by_cases b0 : b = 0, {rw [b0, opow_zero, opow_one] at h ⊢, exact mul_omega a0 h}, refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right' (one_le_iff_pos.2 a0) (omega ^ omega ^ b)), rcases (lt_opow_of_limit omega_ne_zero (opow_is_limit_left omega_is_limit b0)).1 h with ⟨x, xb, ax⟩, apply (mul_le_mul_right' (le_of_lt ax) _).trans, rw [← opow_add, add_omega_opow xb] end theorem principal_mul_omega_opow_opow (o : ordinal) : principal (*) (omega ^ omega ^ o) := principal_mul_iff_mul_left_eq.2 (λ a, mul_omega_opow_opow) theorem principal_add_of_principal_mul_opow {o b : ordinal} (hb : 1 < b) (ho : principal (*) (b ^ o)) : principal (+) o := λ x y hx hy, begin have := ho ((opow_lt_opow_iff_right hb).2 hx) ((opow_lt_opow_iff_right hb).2 hy), rwa [←opow_add, opow_lt_opow_iff_right hb] at this end /-- The main characterization theorem for multiplicative principal ordinals. -/ theorem principal_mul_iff_le_two_or_omega_opow_opow {o : ordinal} : principal (*) o ↔ o ≤ 2 ∨ ∃ a, o = omega ^ omega ^ a := begin refine ⟨λ ho, _, _⟩, { cases le_or_lt o 2 with ho₂ ho₂, { exact or.inl ho₂ }, rcases principal_add_iff_zero_or_omega_opow.1 (principal_add_of_principal_mul ho ho₂.ne') with rfl | ⟨a, rfl⟩, { exact (ordinal.not_lt_zero 2 ho₂).elim }, rcases principal_add_iff_zero_or_omega_opow.1 (principal_add_of_principal_mul_opow one_lt_omega ho) with rfl | ⟨b, rfl⟩, { rw opow_zero at ho₂, exact ((lt_succ_self 1).not_le ho₂.le).elim }, exact or.inr ⟨b, rfl⟩ }, { rintro (ho₂ | ⟨a, rfl⟩), { exact principal_mul_of_le_two ho₂ }, { exact principal_mul_omega_opow_opow a } } end theorem mul_omega_dvd {a : ordinal} (a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b | _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha] theorem mul_eq_opow_log_succ {a b : ordinal.{u}} (ha : 0 < a) (hb : principal (*) b) (hb₂ : 2 < b) : a * b = b ^ (log b a).succ := begin apply le_antisymm, { have hbl := principal_mul_is_limit hb₂ hb, rw [←is_normal.bsup_eq.{u u} (mul_is_normal ha) hbl, bsup_le_iff], intros c hcb, have hb₁ : 1 < b := (lt_succ_self 1).trans hb₂, have hbo₀ : b ^ b.log a ≠ 0 := ordinal.pos_iff_ne_zero.1 (opow_pos _ (zero_lt_one.trans hb₁)), apply le_trans (mul_le_mul_right' (le_of_lt (lt_mul_succ_div a hbo₀)) c), rw [mul_assoc, opow_succ], refine mul_le_mul_left' (le_of_lt (hb (hbl.2 _ _) hcb)) _, rw [div_lt hbo₀, ←opow_succ], exact lt_opow_succ_log_self hb₁ _ }, { rw opow_succ, exact mul_le_mul_right' (opow_log_le_self b ha) b } end /-! #### Exponential principal ordinals -/ theorem principal_opow_omega : principal (^) omega := λ a b ha hb, match a, b, lt_omega.1 ha, lt_omega.1 hb with | _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by { simp_rw ←nat_cast_opow, apply nat_lt_omega } end theorem opow_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega := le_antisymm ((opow_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2 (λ b hb, (principal_opow_omega h hb).le)) (right_le_opow _ a1) end ordinal
00538560333d3eb2f0c96631e220db45891e457a
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/witt_vector/init_tail.lean
51d35727805c36877304c4537eef789e5d07dec0
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
6,405
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import ring_theory.witt_vector.basic import ring_theory.witt_vector.is_poly /-! # `init` and `tail` Given a Witt vector `x`, we are sometimes interested in its components before and after an index `n`. This file defines those operations, proves that `init` is polynomial, and shows how that polynomial interacts with `mv_polynomial.bind₁`. ## Main declarations * `witt_vector.init n x`: the first `n` coefficients of `x`, as a Witt vector. All coefficients at indices ≥ `n` are 0. * `witt_vector.tail n x`: the complementary part to `init`. All coefficients at indices < `n` are 0, otherwise they are the same as in `x`. * `witt_vector.coeff_add_of_disjoint`: if `x` and `y` are Witt vectors such that for every `n` the `n`-th coefficient of `x` or of `y` is `0`, then the coefficients of `x + y` are just `x.coeff n + y.coeff n`. ## References * [Hazewinkel, *Witt Vectors*][Haze09] * [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21] -/ variables {p : ℕ} [hp : fact p.prime] (n : ℕ) {R : Type*} [comm_ring R] local notation `𝕎` := witt_vector p -- type as `\bbW` namespace tactic namespace interactive setup_tactic_parser /-- `init_ring` is an auxiliary tactic that discharges goals factoring `init` over ring operations. -/ meta def init_ring (assert : parse (tk "using" >> parser.pexpr)?) : tactic unit := do `[rw ext_iff, intros i, simp only [init, select, coeff_mk], split_ifs with hi; try {refl}], match assert with | none := skip | some e := do `[simp only [add_coeff, mul_coeff, neg_coeff], apply eval₂_hom_congr' (ring_hom.ext_int _ _) _ rfl, rintro ⟨b, k⟩ h -], tactic.replace `h ```(%%e p _ h), `[simp only [finset.mem_range, finset.mem_product, true_and, finset.mem_univ] at h, have hk : k < n, by linarith, fin_cases b; simp only [function.uncurry, matrix.cons_val_zero, matrix.head_cons, coeff_mk, matrix.cons_val_one, coeff_mk, hk, if_true]] end end interactive end tactic namespace witt_vector open mv_polynomial open_locale classical noncomputable theory section /-- `witt_vector.select P x`, for a predicate `P : ℕ → Prop` is the Witt vector whose `n`-th coefficient is `x.coeff n` if `P n` is true, and `0` otherwise. -/ def select (P : ℕ → Prop) (x : 𝕎 R) : 𝕎 R := mk p (λ n, if P n then x.coeff n else 0) section select variables (P : ℕ → Prop) /-- The polynomial that witnesses that `witt_vector.select` is a polynomial function. `select_poly n` is `X n` if `P n` holds, and `0` otherwise. -/ def select_poly (n : ℕ) : mv_polynomial ℕ ℤ := if P n then X n else 0 lemma coeff_select (x : 𝕎 R) (n : ℕ) : (select P x).coeff n = aeval x.coeff (select_poly P n) := begin dsimp [select, select_poly], split_ifs with hi, { rw aeval_X }, { rw alg_hom.map_zero } end @[is_poly] lemma select_is_poly (P : ℕ → Prop) : is_poly p (λ R _Rcr x, by exactI select P x) := begin use (select_poly P), rintro R _Rcr x, funext i, apply coeff_select end include hp lemma select_add_select_not : ∀ (x : 𝕎 R), select P x + select (λ i, ¬ P i) x = x := begin ghost_calc _, intro n, simp only [ring_hom.map_add], suffices : (bind₁ (select_poly P)) (witt_polynomial p ℤ n) + (bind₁ (select_poly (λ i, ¬P i))) (witt_polynomial p ℤ n) = witt_polynomial p ℤ n, { apply_fun (aeval x.coeff) at this, simpa only [alg_hom.map_add, aeval_bind₁, ← coeff_select] }, simp only [witt_polynomial_eq_sum_C_mul_X_pow, select_poly, alg_hom.map_sum, alg_hom.map_pow, alg_hom.map_mul, bind₁_X_right, bind₁_C_right, ← finset.sum_add_distrib, ← mul_add], apply finset.sum_congr rfl, intros, congr' 2, split_ifs; simp only [zero_pow (pow_pos hp.pos _), add_zero, zero_add], end lemma coeff_add_of_disjoint (x y : 𝕎 R) (h : ∀ n, x.coeff n = 0 ∨ y.coeff n = 0) : (x + y).coeff n = x.coeff n + y.coeff n := begin let P : ℕ → Prop := λ n, y.coeff n = 0, haveI : decidable_pred P := classical.dec_pred P, set z := mk p (λ n, if P n then x.coeff n else y.coeff n) with hz, have hx : select P z = x, { ext1 n, rw [select, coeff_mk, coeff_mk], split_ifs with hn, { refl }, { rw (h n).resolve_right hn } }, have hy : select (λ i, ¬ P i) z = y, { ext1 n, rw [select, coeff_mk, coeff_mk], split_ifs with hn, { exact hn.symm }, { refl } }, calc (x + y).coeff n = z.coeff n : by rw [← hx, ← hy, select_add_select_not P z] ... = x.coeff n + y.coeff n : _, dsimp [z], split_ifs with hn, { dsimp [P] at hn, rw [hn, add_zero] }, { rw [(h n).resolve_right hn, zero_add] } end end select /-- `witt_vector.init n x` is the Witt vector of which the first `n` coefficients are those from `x` and all other coefficients are `0`. See `witt_vector.tail` for the complementary part. -/ def init (n : ℕ) : 𝕎 R → 𝕎 R := select (λ i, i < n) /-- `witt_vector.tail n x` is the Witt vector of which the first `n` coefficients are `0` and all other coefficients are those from `x`. See `witt_vector.init` for the complementary part. -/ def tail (n : ℕ) : 𝕎 R → 𝕎 R := select (λ i, n ≤ i) include hp @[simp] lemma init_add_tail (x : 𝕎 R) (n : ℕ) : init n x + tail n x = x := by simp only [init, tail, ← not_lt, select_add_select_not] end @[simp] lemma init_init (x : 𝕎 R) (n : ℕ) : init n (init n x) = init n x := by init_ring include hp lemma init_add (x y : 𝕎 R) (n : ℕ) : init n (x + y) = init n (init n x + init n y) := by init_ring using witt_add_vars lemma init_mul (x y : 𝕎 R) (n : ℕ) : init n (x * y) = init n (init n x * init n y) := by init_ring using witt_mul_vars lemma init_neg (x : 𝕎 R) (n : ℕ) : init n (-x) = init n (-init n x) := by init_ring using witt_neg_vars lemma init_sub (x y : 𝕎 R) (n : ℕ) : init n (x - y) = init n (init n x - init n y) := begin simp only [sub_eq_add_neg], rw [init_add, init_neg], conv_rhs { rw [init_add, init_init] }, end section variables (p) omit hp /-- `witt_vector.init n x` is polynomial in the coefficients of `x`. -/ lemma init_is_poly (n : ℕ) : is_poly p (λ R _Rcr, by exactI init n) := select_is_poly (λ i, i < n) end end witt_vector
84bb63d1808b58bf58e9a18fd0315d42036bce84
34c1747a946aa0941114ffca77a3b7c1e4cfb686
/src/spectrum_of_a_ring/spec_locally_ringed_space.lean
cab1689e80ae2acb9f48f2250830133468e6173d
[]
no_license
martrik/lean-scheme
2b9edd63550c4579a451f793ab289af9fc79a16d
033dc47192ba4c61e4e771701f5e29f8007e6332
refs/heads/master
1,588,866,287,405
1,554,922,682,000
1,554,922,682,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
287
lean
import spectrum_of_a_ring.structure_sheaf import spectrum_of_a_ring.strucutre_sheaf_stalks universe u variables (R : Type u) [comm_ring R] def Spec.locally_ringeed_space : locally_ringed_space (Spec R) := { O := structure_sheaf R, Hstalks := λ P, structure_sheaf.stalk_local P, }
806dbcc071eda2fbcb0e587b43433df64e3431e4
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/library/init/meta/environment.lean
285c5920eea23d0a85fd173226c30a5754cad582
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
4,109
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.declaration init.meta.exceptional meta_constant environment : Type namespace environment /- Create a standard environment using the given trust level -/ meta_constant mk_std : nat → environment /- Create a HoTT environment -/ meta_constant mk_hott : nat → environment /- Return the trust level of the given environment -/ meta_constant trust_lvl : environment → nat /- Return tt iff it is a standard environment -/ meta_constant is_std : environment → bool /- Add a new declaration to the environment -/ meta_constant add : environment → declaration → exceptional environment /- Retrieve a declaration from the environment -/ meta_constant get : environment → name → exceptional declaration /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type) -/ meta_constant add_inductive : environment → name → list name → nat → expr → list (name × expr) → exceptional environment /- Return tt iff the given name is an inductive datatype -/ meta_constant is_inductive : environment → name → bool /- Return tt iff the given name is a constructor -/ meta_constant is_constructor : environment → name → bool /- Return tt iff the given name is a recursor -/ meta_constant is_recursor : environment → name → bool /- Return tt iff the given name is a recursive inductive datatype -/ meta_constant is_recursive : environment → name → bool /- Return the name of the inductive datatype of the given constructor. -/ meta_constant inductive_type_of : environment → name → option name /- Return the constructors of the inductive datatype with the given name -/ meta_constant constructors_of : environment → name → list name /- Return the recursor of the given inductive datatype -/ meta_constant recursor_of : environment → name → option name /- Return the number of parameters of the inductive datatype -/ meta_constant inductive_num_params : environment → name → nat /- Return the number of indices of the inductive datatype -/ meta_constant inductive_num_indices : environment → name → nat /- Return tt iff the inductive datatype recursor supports dependent elimination -/ meta_constant inductive_dep_elim : environment → name → bool /- Fold over declarations in the environment -/ meta_constant fold {A :Type} : environment → A → (declaration → A → A) → A /- (relation_info env n) returns some value if n is marked as a relation in the given environment. the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/ meta_constant relation_info : environment → name → option (nat × nat × nat) /- (refl_for env R) returns the name of the reflexivity theorem for the relation R -/ meta_constant refl_for : environment → name → option name /- (symm_for env R) returns the name of the symmetry theorem for the relation R -/ meta_constant symm_for : environment → name → option name /- (trans_for env R) returns the name of the transitivity theorem for the relation R -/ meta_constant trans_for : environment → name → option name open expr meta_definition is_constructor_app (env : environment) (e : expr) : bool := is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e)) meta_definition is_refl_app (env : environment) (e : expr) : option (name × expr × expr) := match (refl_for env (const_name (get_app_fn e))) with | (some n) := if get_app_num_args e ≥ 2 then some (n, app_arg (app_fn e), app_arg e) else none | none := none end end environment attribute [instance] meta_definition environment.has_to_string : has_to_string environment := has_to_string.mk (λ e, "[environment]") attribute [instance] meta_definition environment.is_inhabited : inhabited environment := inhabited.mk (environment.mk_std 0)
6fcbfdd9332359f23523c012cc8673fc4fccbd16
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/complex/exponential.lean
4bdb7cd7d4d5c2ccf954ba0bd16e757150d5ae99
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
67,133
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.complex.basic import data.nat.choose.sum /-! # Exponential, trigonometric and hyperbolic trigonometric functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := has_abs.abs open is_absolute_value open_locale classical big_operators nat complex_conjugate section open real is_absolute_value finset section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l • ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) • ε < -|f n|, from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul, add_nsmul, one_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_right _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l • ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m le_rfl) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := (nat.rel_of_forall_rel_succ_of_le_of_le (≥) hnm hi.1 hj).le, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], calc f i ≤ a - (nat.pred l) • ε : hi.2 ... = a - l • ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub_comm (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw tsub_eq_iff_eq_add_of_le ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { simp only [nat.succ_add, sum_range_succ_comm, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_rfl) end no_archimedean section variables {α : Type*} [linear_ordered_field α] [archimedean α] lemma is_cau_geo_series {β : Type*} [ring β] [nontrivial β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv, geom_sum_eq hx1'], conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : |x| < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : |r| < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (tsub_eq_iff_eq_add_of_le hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := by rw [sum_sigma', sum_sigma']; exact sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((tsub_lt_tsub_iff_right (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (tsub_eq_iff_eq_add_of_le ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨tsub_add_cancel_of_le hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (lt_tsub_iff_right.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (add_tsub_cancel_right _ _).symm⟩⟩⟩) end section no_archimedean variables {α : Type*} {β : Type*} [linear_ordered_field α] {abv : β → α} section variables [semiring β] [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) end section variables [ring β] [is_absolute_value abv] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) (le_tsub_of_add_le_left (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) K (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = |∑ n in range (max N M + 1), abv (a n)| : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) _ (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq has_abs.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs.nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (abs.nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div, mul_div_assoc, mul_div_right_comm, abs.map_mul, map_div₀, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs.nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs.nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[irreducible, pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := begin rw exp, refine lim_eq_of_equiv_const (λ ε ε0, ⟨1, λ j hj, _⟩), convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end lemma exp_add : exp (x + y) = exp x * exp y := begin have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), { assume j, refine finset.sum_congr rfl (λ m hm, _), rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv, mul_inv], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] }, simp_rw [exp, exp', lim_mul_lim], apply (lim_eq_lim_of_equiv _).symm, simp only [hj], exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y) end lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℂ) α ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] lemma exp_int_mul (z : ℂ) (n : ℤ) : complex.exp (n * z) = (complex.exp z) ^ n := begin cases n, { apply complex.exp_nat_mul }, { simpa [complex.exp_neg, add_comm, ← neg_mul] using complex.exp_nat_mul (-z) (1 + n) }, end @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw (star_ring_end _).map_sum, refine sum_congr rfl (λ n hn, _), rw [map_div₀, map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := conj_eq_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (two_ne_zero' ℂ), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (two_ne_zero' ℂ), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (two_ne_zero' ℂ), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (two_ne_zero' ℂ), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← ring_hom.map_neg, exp_conj, exp_conj, ← ring_hom.map_sub, sinh, map_div₀, conj_bit0, ring_hom.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := conj_eq_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← ring_hom.map_neg, exp_conj, exp_conj, ← ring_hom.map_add, cosh, map_div₀, conj_bit0, ring_hom.map_one] end lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := conj_eq_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] @[simp] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← map_div₀, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := conj_eq_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl @[simp] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (two_ne_zero' ℂ), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] @[simp] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] lemma exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] lemma exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (two_ne_zero' ℂ), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] @[simp] lemma sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, sq, sq] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_sq], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_sq], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (two_ne_zero' ℂ), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (two_ne_zero' ℂ), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] lemma cos_mul_I : cos (x * I) = cosh x := by rw ← cosh_mul_I; ring_nf; simp lemma sin_mul_I : sin (x * I) = sinh x * I := have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp }, by simpa only [neg_mul, div_I, neg_neg] using cancel_factors.cancel_factors_eq_div h I_ne_zero lemma tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← ring_hom.map_mul, ← ring_hom.map_mul, sinh_conj, mul_neg, sinh_neg, sinh_mul_I, mul_neg] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := conj_eq_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← ring_hom.map_mul, ← cosh_mul_I, cosh_conj, mul_neg, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := conj_eq_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← map_div₀, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := conj_eq_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← sq, ← sq] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero, -one_div] lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, sq], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_sq'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] } lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] } @[simp] lemma exp_of_real_mul_I_re (x : ℝ) : (exp (x * I)).re = real.cos x := by simp [exp_mul_I, cos_of_real_re] @[simp] lemma exp_of_real_mul_I_im (x : ℝ) : (exp (x * I)).im = real.sin x := by simp [exp_mul_I, sin_of_real_re] /-- **De Moivre's formula** -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℝ) α ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] @[simp] lemma cos_abs : cos (|x|) = cos x := by cases le_total x 0; simp only [*, _root_.abs_of_nonneg, abs_of_nonpos, cos_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos] lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (sq_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (sq_nonneg _) lemma abs_sin_le_one : |sin x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, sin_sq_le_one] lemma abs_cos_le_one : |cos x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, cos_sq_le_one] lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_sq x lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) : |sin x| = sqrt (1 - cos x ^ 2) := by rw [← sin_sq, sqrt_sq_eq_abs] lemma abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) : |cos x| = sqrt (1 - sin x ^ 2) := by rw [← cos_sq', sqrt_sq_eq_abs] lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' ℂ), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' ℂ), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := of_real_inj.1 $ by simp @[simp] lemma cosh_abs : cosh (|x|) = cosh x := by cases le_total x 0; simp [*, _root_.abs_of_nonneg, abs_of_nonpos] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] @[simp] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp @[simp] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] lemma exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] lemma exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by { rw [← of_real_inj], simp } @[simp] lemma sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_sq] lemma cosh_sq' : cosh x ^ 2 = 1 + sinh x ^ 2 := (cosh_sq x).trans (add_comm _ _) lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_sq] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value lemma sum_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) (n : ℕ) : ∑ i in range n, x ^ i / i! ≤ exp x := calc ∑ i in range n, x ^ i / i! ≤ lim (⟨_, is_cau_seq_re (exp' x)⟩ : cau_seq ℝ has_abs.abs) : begin refine le_lim (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp only [exp', const_apply, mk_to_fun, re_sum], norm_cast, rw [← nat.add_sub_of_le hj, finset.sum_range_add], refine le_add_of_nonneg_right (sum_nonneg (λ i hi, _)), positivity, end ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma quadratic_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : 1 + x + x ^ 2 / 2 ≤ exp x := calc 1 + x + x ^ 2 / 2 = ∑ i in range 3, x ^ i / i! : by simp [finset.sum_range_succ] ... ≤ exp x : sum_le_exp_of_nonneg hx 3 lemma add_one_lt_exp_of_pos {x : ℝ} (hx : 0 < x) : x + 1 < exp x := (by nlinarith : x + 1 < 1 + x + x ^ 2 / 2).trans_le (quadratic_le_exp_of_nonneg hx.le) /-- This is an intermediate result that is later replaced by `real.add_one_le_exp`; use that lemma instead. -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := begin rcases eq_or_lt_of_le hx with rfl | h, { simp }, exact (add_one_lt_exp_of_pos h).le end lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : |exp x| = exp x := abs_of_pos (exp_pos _) @[mono] lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : monotone exp := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := exp_injective.eq_iff' exp_zero @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) lemma sinh_lt_cosh : sinh x < cosh x := lt_of_pow_lt_pow 2 (cosh_pos _).le $ (cosh_sq x).symm ▸ lt_add_one _ end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (tsub_lt_tsub_iff_right (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw tsub_add_cancel_of_le; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [tsub_eq_iff_eq_add_of_le, tsub_add_eq_add_tsub, eq_comm, tsub_eq_iff_eq_add_of_le, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ lt_tsub_iff_right.mp (mem_range.1 hb), nat.le_add_left _ _⟩, by rw add_tsub_cancel_right⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv, mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev, h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : begin refine congr_arg abs (sum_congr rfl (λ m hm, _)), rw [mem_filter, mem_range] at hm, rw [← mul_div_assoc, ← pow_add, add_tsub_cancel_of_le hm.2] end ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [map_mul, map_pow, map_div₀, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, { exact nat.cast_pos.2 (nat.factorial_pos _), }, { rw abv_pow abs, exact (pow_le_one _ (abs.nonneg _) hx), }, { exact pow_nonneg (abs.nonneg _) _ }, end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs.nonneg _) _) end lemma exp_bound' {x : ℂ} {n : ℕ} (hx : abs x / (n.succ) ≤ 1 / 2) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2 := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw [←sub_eq_add_neg], show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2, let k := j - n, have hj : j = n + k := (add_tsub_cancel_of_le hj).symm, rw [hj, sum_range_add_sub_sum_range], calc abs (∑ (i : ℕ) in range k, x ^ (n + i) / ((n + i)! : ℂ)) ≤ ∑ (i : ℕ) in range k, abs (x ^ (n + i) / ((n + i)! : ℂ)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n + i)! : by simp only [complex.abs_cast_nat, map_div₀, abv_pow abs] ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n! * n.succ ^ i) : _ ... = ∑ (i : ℕ) in range k, (abs x) ^ (n) / (n!) * ((abs x)^i / n.succ ^ i) : _ ... ≤ abs x ^ n / (↑n!) * 2 : _, { refine sum_le_sum (λ m hm, div_le_div (pow_nonneg (abs.nonneg x) (n + m)) le_rfl _ _), { exact_mod_cast mul_pos n.factorial_pos (pow_pos n.succ_pos _), }, { exact_mod_cast (nat.factorial_mul_pow_le_factorial), }, }, { refine finset.sum_congr rfl (λ _ _, _), simp only [pow_add, div_eq_inv_mul, mul_inv, mul_left_comm, mul_assoc], }, { rw [←mul_sum], apply mul_le_mul_of_nonneg_left, { simp_rw [←div_pow], rw [geom_sum_eq, div_le_iff_of_neg], { transitivity (-1 : ℝ), { linarith }, { simp only [neg_le_sub_iff_le_add, div_pow, nat.cast_succ, le_add_iff_nonneg_left], exact div_nonneg (pow_nonneg (abs.nonneg x) k) (pow_nonneg (add_nonneg n.cast_nonneg zero_le_one) k) } }, { linarith }, { linarith }, }, { exact div_nonneg (pow_nonneg (abs.nonneg x) n) (nat.cast_nonneg (n!)), }, }, end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (sq_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : |x| ≤ 1) {n : ℕ} (hn : 0 < n) : |exp x - ∑ m in range n, x ^ m / m!|≤ |x| ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end lemma exp_bound' {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) {n : ℕ} (hn : 0 < n) : real.exp x ≤ ∑ m in finset.range n, x ^ m / m! + x ^ n * (n + 1) / (n! * n) := begin have h3 : |x| = x := by simpa, have h4 : |x| ≤ 1 := by rwa h3, have h' := real.exp_bound h4 hn, rw h3 at h', have h'' := (abs_sub_le_iff.1 h').1, have t := sub_le_iff_le_add'.1 h'', simpa [mul_div_assoc] using t end lemma abs_exp_sub_one_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1| ≤ 2 * |x| := begin have : complex.abs x ≤ 1 := by exact_mod_cast hx, exact_mod_cast complex.abs_exp_sub_one_le this, end lemma abs_exp_sub_one_sub_id_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1 - x| ≤ x ^ 2 := begin rw ←_root_.sq_abs, have : complex.abs x ≤ 1 := by exact_mod_cast hx, exact_mod_cast complex.abs_exp_sub_one_sub_id_le this, end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv]; ac_refl theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : |x| ≤ 1) : |exp x - exp_near m x 0| ≤ |x| ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : |1 + x / m * a₂ - a₁| ≤ b₁ - |x| / m * b₂) (h : |exp x - exp_near m x a₂| ≤ |x| ^ m / m! * b₂) : |exp x - exp_near n x a₁| ≤ |x| ^ n / n! * b₁ := begin refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv], ac_refl }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : |x| ≤ 1) (e : |1 - a| ≤ b - |x| / rm * ((rm+1)/rm)) : |exp x - exp_near n x a| ≤ |x| ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : |exp 1 - exp_near m 1 ((a₁ - 1) * rm)| ≤ |1| ^ m / m! * (b₁ * rm)) : |exp 1 - exp_near n 1 a₁| ≤ |1| ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : |exp x - exp_near 0 x a| ≤ |x| ^ 0 / 0! * b) : |exp x - a| ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : |x| ≤ 1) : |cos x - (1 - x ^ 2 / 2)| ≤ |x| ^ 4 * (5 / 96) := calc |cos x - (1 - x ^ 2 / 2)| = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (two_ne_zero' ℂ)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact complex.abs.add_le _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [map_div₀] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : |x| ≤ 1) : |sin x - (x - x ^ 3 / 6)| ≤ |x| ^ 4 * (5 / 96) := calc |sin x - (x - x ^ 3 / 6)| = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (two_ne_zero' ℂ), div_div, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact complex.abs.add_le _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, map_div₀] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : |x| ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [sq, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le_comm.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc |x| ^ 4 ≤ |x| ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le_comm.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ |(1 : ℝ)| ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (le_of_eq abs_one) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by { rw [sq, sq], exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le }) zero_le_two) _ ... < 0 : by norm_num lemma exp_bound_div_one_sub_of_interval' {x : ℝ} (h1 : 0 < x) (h2 : x < 1) : real.exp x < 1 / (1 - x) := have H : 0 < 1 - (1 + x + x ^ 2) * (1 - x) := calc 0 < x ^ 3 : by positivity ... = 1 - (1 + x + x ^ 2) * (1 - x) : by ring, calc exp x ≤ _ : exp_bound' h1.le h2.le zero_lt_three ... ≤ 1 + x + x ^ 2 : by norm_num [finset.sum]; nlinarith ... < 1 / (1 - x) : by rw lt_div_iff; nlinarith lemma exp_bound_div_one_sub_of_interval {x : ℝ} (h1 : 0 ≤ x) (h2 : x < 1) : real.exp x ≤ 1 / (1 - x) := begin rcases eq_or_lt_of_le h1 with rfl | h1, { simp }, { exact (exp_bound_div_one_sub_of_interval' h1 h2).le } end lemma one_sub_lt_exp_minus_of_pos {y : ℝ} (h : 0 < y) : 1 - y < real.exp (-y) := begin cases le_or_lt 1 y with h' h', { linarith [(-y).exp_pos] }, rw [exp_neg, lt_inv _ y.exp_pos, inv_eq_one_div], { exact exp_bound_div_one_sub_of_interval' h h' }, { linarith }, end lemma one_sub_le_exp_minus_of_nonneg {y : ℝ} (h : 0 ≤ y) : 1 - y ≤ real.exp (-y) := begin rcases eq_or_lt_of_le h with rfl | h, { simp }, { exact (one_sub_lt_exp_minus_of_pos h).le } end lemma add_one_lt_exp_of_neg {x : ℝ} (h : x < 0) : x + 1 < real.exp x := begin have h1 : 0 < -x := by linarith, simpa [add_comm] using one_sub_lt_exp_minus_of_pos h1 end lemma add_one_lt_exp_of_nonzero {x : ℝ} (hx : x ≠ 0) : x + 1 < real.exp x := begin cases lt_or_gt_of_ne hx, { exact real.add_one_lt_exp_of_neg h }, exact add_one_lt_exp_of_pos h, end lemma add_one_le_exp (x : ℝ) : x + 1 ≤ real.exp x := begin cases le_or_lt 0 x, { exact real.add_one_le_exp_of_nonneg h }, exact (add_one_lt_exp_of_neg h).le, end lemma one_sub_div_pow_le_exp_neg {n : ℕ} {t : ℝ} (ht' : t ≤ n) : (1 - t / n) ^ n ≤ exp (-t) := begin rcases eq_or_ne n 0 with rfl | hn, { simp, rwa nat.cast_zero at ht' }, convert pow_le_pow_of_le_left _ (add_one_le_exp (-(t / n))) n, { abel }, { rw ←real.exp_nat_mul, congr' 1, field_simp [nat.cast_ne_zero.mpr hn], ring }, { rwa [add_comm, ←sub_eq_add_neg, sub_nonneg, div_le_one], positivity } end end real namespace tactic open positivity real /-- Extension for the `positivity` tactic: `real.exp` is always positive. -/ @[positivity] meta def positivity_exp : expr → tactic strictness | `(real.exp %%a) := positive <$> mk_app `real.exp_pos [a] | e := pp e >>= fail ∘ format.bracket "The expression `" "` isn't of the form `real.exp r`" end tactic namespace complex @[simp] lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, sq, *, sin_of_real_re, cos_of_real_re, mul_re] at * @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) @[simp] lemma abs_exp_of_real_mul_I (x : ℝ) : abs (exp (x * I)) = 1 := by rw [exp_mul_I, abs_cos_add_sin_mul_I] lemma abs_exp (z : ℂ) : abs (exp z) = real.exp z.re := by rw [exp_eq_exp_re_mul_sin_add_cos, map_mul, abs_exp_of_real, abs_cos_add_sin_mul_I, mul_one] lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [abs_exp, abs_exp, real.exp_eq_exp] end complex
faf0ecb85df0fcb14777b58d4302ab09f84cab66
351a46035517d2a1985619b8cabdf263754d343a
/src/ch12.lean
bc77208ec502efe68f91ccb39801d3952447e432
[]
no_license
kaychaks/logic_proof
accc212517b613caca92c10db77e6aaf6b7ccfbc
90f3bf0acbabf558ba2f82dee968255d8bfe2de1
refs/heads/master
1,587,001,734,509
1,548,235,051,000
1,548,235,051,000
165,186,786
0
0
null
null
null
null
UTF-8
Lean
false
false
3,565
lean
section variable {U : Type} variables {A B C : set U} example : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := assume x : U, assume : x ∈ A ∩ C, show x ∈ A ∪ B, from or.inl (and.left this) example : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := assume x, assume h1 : x ∈ -(A ∪ B), show x ∈ -A, from assume : x ∈ A, show false, from h1 (or.inl this) end --- import data.set open set section variable {U : Type} example (A B C : set U) : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := assume x, assume : x ∈ A ∩ C, show x ∈ A ∪ B, from or.inl this.left example (A B : set U) : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := assume x, assume : x ∈ -(A ∪ B), show x ∈ -A, from assume : x ∈ A, show false, from ‹ x ∈ -(A ∪ B) › (or.inl this) /- defining "disjoint" -/ def disj (A B : set U) : Prop := ∀ ⦃x⦄, x ∈ A → x ∈ B → false example (A B : set U) (h : ∀ x, ¬ (x ∈ A ∧ x ∈ B)) : disj A B := assume x, assume h1 : x ∈ A, assume h2 : x ∈ B, have h3 : x ∈ A ∧ x ∈ B, from and.intro h1 h2, show false, from h x h3 -- notice that we do not have to mention x when applying -- h : disj A B example (A B : set U) (h1 : disj A B) (x : U) (h2 : x ∈ A) (h3 : x ∈ B) : false := h1 h2 h3 -- the same is true of ⊆ example (A B : set U) (x : U) (h : A ⊆ B) (h1 : x ∈ A) : x ∈ B := h h1 example (A B C D : set U) (h1 : disj A B) (h2 : C ⊆ A) (h3 : D ⊆ B) : disj C D := assume x, assume : x ∈ C, assume : x ∈ D, show false, from h1 (h2 ‹ x ∈ C › ) (h3 ‹ x ∈ D ›) end --- import data.set open set section variables {I U : Type} variables {A B : I → set U} theorem Inter.intro {x : U} (h : ∀ i, x ∈ A i) : x ∈ ⋂ i, A i := by simp; assumption @[elab_simple] theorem Inter.elim {x : U} (h : x ∈ ⋂ i, A i) (i : I) : x ∈ A i := by simp at h; apply h theorem Union.intro {x : U} (i : I) (h : x ∈ A i) : x ∈ ⋃ i, A i := by {simp, existsi i, exact h} theorem Union.elim {b : Prop} {x : U} (h₁ : x ∈ ⋃ i, A i) (h₂ : ∀ (i : I), x ∈ A i → b) : b := by {simp at h₁, cases h₁ with i h, exact h₂ i h} end -- BEGIN variables {I U : Type} variables (A : I → set U) (B : I → set U) (C : set U) example : (⋂ i, A i) ∩ (⋂ i, B i) ⊆ (⋂ i, A i ∩ B i) := assume x, assume h1 : x ∈ (⋂ i, A i) ∩ (⋂ i, B i), show x ∈ (⋂ i, A i ∩ B i), from have h2 : ∀ i, x ∈ A i ∩ B i, from assume i : I, have x ∈ A i, from Inter.elim (h1.left) i, have x ∈ B i, from Inter.elim (h1.right) i, ⟨ ‹ x ∈ A i › , ‹ x ∈ B i › ⟩, Inter.intro h2 example : C ∩ (⋃i, A i) ⊆ ⋃i, C ∩ A i := assume x, assume h, have h2 : ∀ (i : I), x ∈ A i → x ∈ ⋃i, C ∩ A i, from assume i : I, assume h1, have x ∈ C ∩ A i, from ⟨ h.left , h1 ⟩, Union.intro i ‹ x ∈ C ∩ A i › , Union.elim h.right h2 -- END --- import data.set open set -- BEGIN variable {U : Type} variables A B C : set U -- For this exercise these two facts are useful example (h1 : A ⊆ B) (h2 : B ⊆ C) : A ⊆ C := subset.trans h1 h2 example : A ⊆ A := subset.refl A example (h : A ⊆ B) : powerset A ⊆ powerset B := assume x, assume : x ∈ powerset A, have x ⊆ A, from ‹ x ∈ powerset A ›, have x ⊆ B, from subset.trans ‹ x ⊆ A › h, show x ∈ powerset B, from ‹ x ⊆ B › example (h : powerset A ⊆ powerset B) : A ⊆ B := assume x, assume : x ∈ A, h (subset.refl A) ‹ x ∈ A › -- END
74ea826dbe86c1cde62953f24b02ced4ea708295
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc_heq3.lean
17569f1db6faede269b6b26b1f1a30ee08977584
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
857
lean
set_option blast.strategy "cc" set_option blast.cc.heq true -- make sure heterogeneous congruence lemmas are enabled axiom vector.{l} : Type.{l} → nat → Type.{l} axiom app : Π {A : Type} {n m : nat}, vector A m → vector A n → vector A (m+n) example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) : n1 = n3 → v1 = w1 → w1 == w1' → v2 = w2 → app v1 v2 == app w1' w2 := by blast example (n1 n2 n3 : nat) (v1 w1 : vector nat n1) (w1' : vector nat n3) (v2 w2 : vector nat n2) : n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app v1 v2 == app w1' w2 := by blast example (n1 n2 n3 : nat) (v1 w1 v : vector nat n1) (w1' : vector nat n3) (v2 w2 w : vector nat n2) : n1 == n3 → v1 = w1 → w1 == w1' → v2 == w2 → app w1' w2 == app v w → app v1 v2 = app v w := by blast
5c9a974bcb7169d09c76f56c77215c611251aa40
bb31430994044506fa42fd667e2d556327e18dfe
/src/ring_theory/algebraic.lean
d91e2bb41c483d1867fc1f4e2ec818cdcfd3ab65
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
17,620
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.finite_dimensional import ring_theory.integral_closure import data.polynomial.integral_normalization /-! # Algebraic elements and algebraic extensions An element of an R-algebra is algebraic over R if it is the root of a nonzero polynomial. An R-algebra is algebraic over R if and only if all its elements are algebraic over R. The main result in this file proves transitivity of algebraicity: a tower of algebraic field extensions is algebraic. -/ universes u v w open_locale classical polynomial open polynomial section variables (R : Type u) {A : Type v} [comm_ring R] [ring A] [algebra R A] /-- An element of an R-algebra is algebraic over R if it is a root of a nonzero polynomial with coefficients in R. -/ def is_algebraic (x : A) : Prop := ∃ p : R[X], p ≠ 0 ∧ aeval x p = 0 /-- An element of an R-algebra is transcendental over R if it is not algebraic over R. -/ def transcendental (x : A) : Prop := ¬ is_algebraic R x lemma is_transcendental_of_subsingleton [subsingleton R] (x : A) : transcendental R x := λ ⟨p, h, _⟩, h $ subsingleton.elim p 0 variables {R} /-- A subalgebra is algebraic if all its elements are algebraic. -/ def subalgebra.is_algebraic (S : subalgebra R A) : Prop := ∀ x ∈ S, is_algebraic R x variables (R A) /-- An algebra is algebraic if all its elements are algebraic. -/ def algebra.is_algebraic : Prop := ∀ x : A, is_algebraic R x variables {R A} /-- A subalgebra is algebraic if and only if it is algebraic as an algebra. -/ lemma subalgebra.is_algebraic_iff (S : subalgebra R A) : S.is_algebraic ↔ @algebra.is_algebraic R S _ _ S.algebra := begin delta algebra.is_algebraic subalgebra.is_algebraic, rw subtype.forall', refine forall_congr (λ x, exists_congr (λ p, and_congr iff.rfl _)), have h : function.injective S.val := subtype.val_injective, conv_rhs { rw [← h.eq_iff, alg_hom.map_zero] }, rw [← aeval_alg_hom_apply, S.val_apply] end /-- An algebra is algebraic if and only if it is algebraic as a subalgebra. -/ lemma algebra.is_algebraic_iff : algebra.is_algebraic R A ↔ (⊤ : subalgebra R A).is_algebraic := begin delta algebra.is_algebraic subalgebra.is_algebraic, simp only [algebra.mem_top, forall_prop_of_true, iff_self], end lemma is_algebraic_iff_not_injective {x : A} : is_algebraic R x ↔ ¬ function.injective (polynomial.aeval x : R[X] →ₐ[R] A) := by simp only [is_algebraic, injective_iff_map_eq_zero, not_forall, and.comm, exists_prop] end section zero_ne_one variables (R : Type u) {S : Type*} {A : Type v} [comm_ring R] variables [comm_ring S] [ring A] [algebra R A] [algebra R S] [algebra S A] variables [is_scalar_tower R S A] /-- An integral element of an algebra is algebraic.-/ lemma is_integral.is_algebraic [nontrivial R] {x : A} : is_integral R x → is_algebraic R x := λ ⟨p, hp, hpx⟩, ⟨p, hp.ne_zero, hpx⟩ variables {R} lemma is_algebraic_zero [nontrivial R] : is_algebraic R (0 : A) := ⟨_, X_ne_zero, aeval_X 0⟩ /-- An element of `R` is algebraic, when viewed as an element of the `R`-algebra `A`. -/ lemma is_algebraic_algebra_map [nontrivial R] (x : R) : is_algebraic R (algebra_map R A x) := ⟨_, X_sub_C_ne_zero x, by rw [_root_.map_sub, aeval_X, aeval_C, sub_self]⟩ lemma is_algebraic_one [nontrivial R] : is_algebraic R (1 : A) := by { rw ←_root_.map_one _, exact is_algebraic_algebra_map 1 } lemma is_algebraic_nat [nontrivial R] (n : ℕ) : is_algebraic R (n : A) := by { rw ←map_nat_cast _, exact is_algebraic_algebra_map n } lemma is_algebraic_int [nontrivial R] (n : ℤ) : is_algebraic R (n : A) := by { rw ←_root_.map_int_cast (algebra_map R A), exact is_algebraic_algebra_map n } lemma is_algebraic_rat (R : Type u) {A : Type v} [division_ring A] [field R] [algebra R A] (n : ℚ) : is_algebraic R (n : A) := by { rw ←map_rat_cast (algebra_map R A), exact is_algebraic_algebra_map n } lemma is_algebraic_of_mem_root_set {R : Type u} {A : Type v} [field R] [field A] [algebra R A] {p : R[X]} {x : A} (hx : x ∈ p.root_set A) : is_algebraic R x := ⟨p, ne_zero_of_mem_root_set hx, aeval_eq_zero_of_mem_root_set hx⟩ open is_scalar_tower lemma is_algebraic_algebra_map_of_is_algebraic {a : S} : is_algebraic R a → is_algebraic R (algebra_map S A a) := λ ⟨f, hf₁, hf₂⟩, ⟨f, hf₁, by rw [aeval_algebra_map_apply, hf₂, map_zero]⟩ /-- This is slightly more general than `is_algebraic_algebra_map_of_is_algebraic` in that it allows noncommutative intermediate rings `A`. -/ lemma is_algebraic_alg_hom_of_is_algebraic {B} [ring B] [algebra R B] (f : A →ₐ[R] B) {a : A} (h : is_algebraic R a) : is_algebraic R (f a) := let ⟨p, hp, ha⟩ := h in ⟨p, hp, by rw [aeval_alg_hom, f.comp_apply, ha, map_zero]⟩ /-- Transfer `algebra.is_algebraic` across an `alg_equiv`. -/ lemma _root_.alg_equiv.is_algebraic {B} [ring B] [algebra R B] (e : A ≃ₐ[R] B) (h : algebra.is_algebraic R A) : algebra.is_algebraic R B := λ b, by convert ← is_algebraic_alg_hom_of_is_algebraic e.to_alg_hom (h _); apply e.apply_symm_apply lemma _root_.alg_equiv.is_algebraic_iff {B} [ring B] [algebra R B] (e : A ≃ₐ[R] B) : algebra.is_algebraic R A ↔ algebra.is_algebraic R B := ⟨e.is_algebraic, e.symm.is_algebraic⟩ lemma is_algebraic_algebra_map_iff {a : S} (h : function.injective (algebra_map S A)) : is_algebraic R (algebra_map S A a) ↔ is_algebraic R a := ⟨λ ⟨p, hp0, hp⟩, ⟨p, hp0, h (by rwa [map_zero, ← aeval_algebra_map_apply])⟩, is_algebraic_algebra_map_of_is_algebraic⟩ lemma is_algebraic_of_pow {r : A} {n : ℕ} (hn : 0 < n) (ht : is_algebraic R (r ^ n)) : is_algebraic R r := begin obtain ⟨p, p_nonzero, hp⟩ := ht, refine ⟨polynomial.expand _ n p, _, _⟩, { rwa polynomial.expand_ne_zero hn }, { rwa polynomial.expand_aeval n p r }, end lemma transcendental.pow {r : A} (ht : transcendental R r) {n : ℕ} (hn : 0 < n) : transcendental R (r ^ n) := λ ht', ht $ is_algebraic_of_pow hn ht' end zero_ne_one section field variables {K : Type u} {A : Type v} [field K] [ring A] [algebra K A] /-- An element of an algebra over a field is algebraic if and only if it is integral.-/ lemma is_algebraic_iff_is_integral {x : A} : is_algebraic K x ↔ is_integral K x := begin refine ⟨_, is_integral.is_algebraic K⟩, rintro ⟨p, hp, hpx⟩, refine ⟨_, monic_mul_leading_coeff_inv hp, _⟩, rw [← aeval_def, alg_hom.map_mul, hpx, zero_mul], end protected lemma algebra.is_algebraic_iff_is_integral : algebra.is_algebraic K A ↔ algebra.is_integral K A := ⟨λ h x, is_algebraic_iff_is_integral.mp (h x), λ h x, is_algebraic_iff_is_integral.mpr (h x)⟩ end field namespace algebra variables {K : Type*} {L : Type*} {R : Type*} {S : Type*} {A : Type*} variables [field K] [field L] [comm_ring R] [comm_ring S] [comm_ring A] variables [algebra K L] [algebra L A] [algebra K A] [is_scalar_tower K L A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] /-- If L is an algebraic field extension of K and A is an algebraic algebra over L, then A is algebraic over K. -/ lemma is_algebraic_trans (L_alg : is_algebraic K L) (A_alg : is_algebraic L A) : is_algebraic K A := begin simp only [is_algebraic, is_algebraic_iff_is_integral] at L_alg A_alg ⊢, exact is_integral_trans L_alg A_alg, end variables (K L) /-- If x is algebraic over R, then x is algebraic over S when S is an extension of R, and the map from `R` to `S` is injective. -/ lemma _root_.is_algebraic_of_larger_base_of_injective (hinj : function.injective (algebra_map R S)) {x : A} (A_alg : _root_.is_algebraic R x) : _root_.is_algebraic S x := let ⟨p, hp₁, hp₂⟩ := A_alg in ⟨p.map (algebra_map _ _), by rwa [ne.def, ← degree_eq_bot, degree_map_eq_of_injective hinj, degree_eq_bot], by simpa⟩ /-- If A is an algebraic algebra over R, then A is algebraic over S when S is an extension of R, and the map from `R` to `S` is injective. -/ lemma is_algebraic_of_larger_base_of_injective (hinj : function.injective (algebra_map R S)) (A_alg : is_algebraic R A) : is_algebraic S A := λ x, is_algebraic_of_larger_base_of_injective hinj (A_alg x) /-- If x is a algebraic over K, then x is algebraic over L when L is an extension of K -/ lemma _root_.is_algebraic_of_larger_base {x : A} (A_alg : _root_.is_algebraic K x) : _root_.is_algebraic L x := _root_.is_algebraic_of_larger_base_of_injective (algebra_map K L).injective A_alg /-- If A is an algebraic algebra over K, then A is algebraic over L when L is an extension of K -/ lemma is_algebraic_of_larger_base (A_alg : is_algebraic K A) : is_algebraic L A := is_algebraic_of_larger_base_of_injective (algebra_map K L).injective A_alg variables (K L) /-- A field extension is integral if it is finite. -/ lemma is_integral_of_finite [finite_dimensional K L] : algebra.is_integral K L := λ x, is_integral_of_submodule_noetherian ⊤ (is_noetherian.iff_fg.2 infer_instance) x algebra.mem_top /-- A field extension is algebraic if it is finite. -/ lemma is_algebraic_of_finite [finite : finite_dimensional K L] : is_algebraic K L := algebra.is_algebraic_iff_is_integral.mpr (is_integral_of_finite K L) variables {K L} theorem is_algebraic.alg_hom_bijective (ha : algebra.is_algebraic K L) (f : L →ₐ[K] L) : function.bijective f := begin refine ⟨f.to_ring_hom.injective, λ b, _⟩, obtain ⟨p, hp, he⟩ := ha b, let f' : p.root_set L → p.root_set L := (root_set_maps_to' id f).restrict f _ _, have : function.surjective f' := finite.injective_iff_surjective.1 (λ _ _ h, subtype.eq $ f.to_ring_hom.injective $ subtype.ext_iff.1 h), obtain ⟨a, ha⟩ := this ⟨b, mem_root_set.2 ⟨hp, he⟩⟩, exact ⟨a, subtype.ext_iff.1 ha⟩, end theorem _root_.alg_hom.bijective [finite_dimensional K L] (ϕ : L →ₐ[K] L) : function.bijective ϕ := (algebra.is_algebraic_of_finite K L).alg_hom_bijective ϕ variables (K L) /-- Bijection between algebra equivalences and algebra homomorphisms -/ @[simps] noncomputable def is_algebraic.alg_equiv_equiv_alg_hom (ha : algebra.is_algebraic K L) : (L ≃ₐ[K] L) ≃* (L →ₐ[K] L) := { to_fun := λ ϕ, ϕ.to_alg_hom, inv_fun := λ ϕ, alg_equiv.of_bijective ϕ (ha.alg_hom_bijective ϕ), left_inv := λ _, by {ext, refl}, right_inv := λ _, by {ext, refl}, map_mul' := λ _ _, rfl } /-- Bijection between algebra equivalences and algebra homomorphisms -/ @[reducible] noncomputable def _root_.alg_equiv_equiv_alg_hom [finite_dimensional K L] : (L ≃ₐ[K] L) ≃* (L →ₐ[K] L) := (algebra.is_algebraic_of_finite K L).alg_equiv_equiv_alg_hom K L end algebra variables {R S : Type*} [comm_ring R] [is_domain R] [comm_ring S] lemma exists_integral_multiple [algebra R S] {z : S} (hz : is_algebraic R z) (inj : ∀ x, algebra_map R S x = 0 → x = 0) : ∃ (x : integral_closure R S) (y ≠ (0 : R)), z * algebra_map R S y = x := begin rcases hz with ⟨p, p_ne_zero, px⟩, set a := p.leading_coeff with a_def, have a_ne_zero : a ≠ 0 := mt polynomial.leading_coeff_eq_zero.mp p_ne_zero, have y_integral : is_integral R (algebra_map R S a) := is_integral_algebra_map, have x_integral : is_integral R (z * algebra_map R S a) := ⟨p.integral_normalization, monic_integral_normalization p_ne_zero, integral_normalization_aeval_eq_zero px inj⟩, exact ⟨⟨_, x_integral⟩, a, a_ne_zero, rfl⟩ end /-- A fraction `(a : S) / (b : S)` can be reduced to `(c : S) / (d : R)`, if `S` is the integral closure of `R` in an algebraic extension `L` of `R`. -/ lemma is_integral_closure.exists_smul_eq_mul {L : Type*} [field L] [algebra R S] [algebra S L] [algebra R L] [is_scalar_tower R S L] [is_integral_closure S R L] (h : algebra.is_algebraic R L) (inj : function.injective (algebra_map R L)) (a : S) {b : S} (hb : b ≠ 0) : ∃ (c : S) (d ≠ (0 : R)), d • a = b * c := begin obtain ⟨c, d, d_ne, hx⟩ := exists_integral_multiple (h (algebra_map _ L a / algebra_map _ L b)) ((injective_iff_map_eq_zero _).mp inj), refine ⟨is_integral_closure.mk' S (c : L) c.2, d, d_ne, is_integral_closure.algebra_map_injective S R L _⟩, simp only [algebra.smul_def, ring_hom.map_mul, is_integral_closure.algebra_map_mk', ← hx, ← is_scalar_tower.algebra_map_apply], rw [← mul_assoc _ (_ / _), mul_div_cancel' (algebra_map S L a), mul_comm], exact mt ((injective_iff_map_eq_zero _).mp (is_integral_closure.algebra_map_injective S R L) _) hb end section field variables {K L : Type*} [field K] [field L] [algebra K L] (A : subalgebra K L) lemma inv_eq_of_aeval_div_X_ne_zero {x : L} {p : K[X]} (aeval_ne : aeval x (div_X p) ≠ 0) : x⁻¹ = aeval x (div_X p) / (aeval x p - algebra_map _ _ (p.coeff 0)) := begin rw [inv_eq_iff_inv_eq, inv_div, div_eq_iff, sub_eq_iff_eq_add, mul_comm], conv_lhs { rw ← div_X_mul_X_add p }, rw [alg_hom.map_add, alg_hom.map_mul, aeval_X, aeval_C], exact aeval_ne end lemma inv_eq_of_root_of_coeff_zero_ne_zero {x : L} {p : K[X]} (aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : x⁻¹ = - (aeval x (div_X p) / algebra_map _ _ (p.coeff 0)) := begin convert inv_eq_of_aeval_div_X_ne_zero (mt (λ h, (algebra_map K L).injective _) coeff_zero_ne), { rw [aeval_eq, zero_sub, div_neg] }, rw ring_hom.map_zero, convert aeval_eq, conv_rhs { rw ← div_X_mul_X_add p }, rw [alg_hom.map_add, alg_hom.map_mul, h, zero_mul, zero_add, aeval_C] end lemma subalgebra.inv_mem_of_root_of_coeff_zero_ne_zero {x : A} {p : K[X]} (aeval_eq : aeval x p = 0) (coeff_zero_ne : p.coeff 0 ≠ 0) : (x⁻¹ : L) ∈ A := begin suffices : (x⁻¹ : L) = (-p.coeff 0)⁻¹ • aeval x (div_X p), { rw [this], exact A.smul_mem (aeval x _).2 _ }, have : aeval (x : L) p = 0, by rw [subalgebra.aeval_coe, aeval_eq, subalgebra.coe_zero], rw [inv_eq_of_root_of_coeff_zero_ne_zero this coeff_zero_ne, div_eq_inv_mul, algebra.smul_def, map_inv₀, map_neg, inv_neg, neg_mul, subalgebra.aeval_coe] end lemma subalgebra.inv_mem_of_algebraic {x : A} (hx : is_algebraic K (x : L)) : (x⁻¹ : L) ∈ A := begin obtain ⟨p, ne_zero, aeval_eq⟩ := hx, rw [subalgebra.aeval_coe, subalgebra.coe_eq_zero] at aeval_eq, revert ne_zero aeval_eq, refine p.rec_on_horner _ _ _, { intro h, contradiction }, { intros p a hp ha ih ne_zero aeval_eq, refine A.inv_mem_of_root_of_coeff_zero_ne_zero aeval_eq _, rwa [coeff_add, hp, zero_add, coeff_C, if_pos rfl] }, { intros p hp ih ne_zero aeval_eq, rw [alg_hom.map_mul, aeval_X, mul_eq_zero] at aeval_eq, cases aeval_eq with aeval_eq x_eq, { exact ih hp aeval_eq }, { rw [x_eq, subalgebra.coe_zero, inv_zero], exact A.zero_mem } } end /-- In an algebraic extension L/K, an intermediate subalgebra is a field. -/ lemma subalgebra.is_field_of_algebraic (hKL : algebra.is_algebraic K L) : is_field A := { mul_inv_cancel := λ a ha, ⟨ ⟨a⁻¹, A.inv_mem_of_algebraic (hKL a)⟩, subtype.ext (mul_inv_cancel (mt (subalgebra.coe_eq_zero _).mp ha))⟩, .. show nontrivial A, by apply_instance, .. subalgebra.to_comm_ring A } end field section pi variables (R' : Type u) (S' : Type v) (T' : Type w) /-- This is not an instance as it forms a diamond with `pi.has_smul`. See the `instance_diamonds` test for details. -/ def polynomial.has_smul_pi [semiring R'] [has_smul R' S'] : has_smul (R'[X]) (R' → S') := ⟨λ p f x, eval x p • f x⟩ /-- This is not an instance as it forms a diamond with `pi.has_smul`. See the `instance_diamonds` test for details. -/ noncomputable def polynomial.has_smul_pi' [comm_semiring R'] [semiring S'] [algebra R' S'] [has_smul S' T'] : has_smul (R'[X]) (S' → T') := ⟨λ p f x, aeval x p • f x⟩ variables {R} {S} local attribute [instance] polynomial.has_smul_pi polynomial.has_smul_pi' @[simp] lemma polynomial_smul_apply [semiring R'] [has_smul R' S'] (p : R'[X]) (f : R' → S') (x : R') : (p • f) x = eval x p • f x := rfl @[simp] lemma polynomial_smul_apply' [comm_semiring R'] [semiring S'] [algebra R' S'] [has_smul S' T'] (p : R'[X]) (f : S' → T') (x : S') : (p • f) x = aeval x p • f x := rfl variables [comm_semiring R'] [comm_semiring S'] [comm_semiring T'] [algebra R' S'] [algebra S' T'] /-- This is not an instance for the same reasons as `polynomial.has_smul_pi'`. -/ noncomputable def polynomial.algebra_pi : algebra (R'[X]) (S' → T') := { to_fun := λ p z, algebra_map S' T' (aeval z p), map_one' := funext $ λ z, by simp only [polynomial.aeval_one, pi.one_apply, map_one], map_mul' := λ f g, funext $ λ z, by simp only [pi.mul_apply, map_mul], map_zero' := funext $ λ z, by simp only [polynomial.aeval_zero, pi.zero_apply, map_zero], map_add' := λ f g, funext $ λ z, by simp only [polynomial.aeval_add, pi.add_apply, map_add], commutes' := λ p f, funext $ λ z, mul_comm _ _, smul_def' := λ p f, funext $ λ z, by simp only [algebra.algebra_map_eq_smul_one, polynomial_smul_apply', one_mul, pi.mul_apply, algebra.smul_mul_assoc], ..polynomial.has_smul_pi' R' S' T' } local attribute [instance] polynomial.algebra_pi @[simp] lemma polynomial.algebra_map_pi_eq_aeval : (algebra_map (R'[X]) (S' → T') : R'[X] → (S' → T')) = λ p z, algebra_map _ _ (aeval z p) := rfl @[simp] lemma polynomial.algebra_map_pi_self_eq_eval : (algebra_map (R'[X]) (R' → R') : R'[X] → (R' → R')) = λ p z, eval z p := rfl end pi
311521a47bf331f74ad96e4df4e02bfc1a873294
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/continued_fractions/convergents_equiv.lean
d1a1803aceb7dba144acae613603fd4717b9a798
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
19,973
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.continuants_recurrence import algebra.continued_fractions.terminated_stable import tactic.field_simp import tactic.ring /-! # Equivalence of Recursive and Direct Computations of `gcf` Convergents ## Summary We show the equivalence of two computations of convergents (recurrence relation (`convergents`) vs. direct evaluation (`convergents'`)) for `gcf`s on linear ordered fields. We follow the proof from [hardy2008introduction], Chapter 10. Here's a sketch: Let `c` be a continued fraction `[h; (a₀, b₀), (a₁, b₁), (a₂, b₂),...]`, visually: a₀ h + --------------------------- a₁ b₀ + -------------------- a₂ b₁ + -------------- a₃ b₂ + -------- b₃ + ... One can compute the convergents of `c` in two ways: 1. Directly evaluating the fraction described by `c` up to a given `n` (`convergents'`) 2. Using the recurrence (`convergents`): - `A₋₁ = 1, A₀ = h, Aₙ = bₙ₋₁ * Aₙ₋₁ + aₙ₋₁ * Aₙ₋₂`, and - `B₋₁ = 0, B₀ = 1, Bₙ = bₙ₋₁ * Bₙ₋₁ + aₙ₋₁ * Bₙ₋₂`. To show the equivalence of the computations in the main theorem of this file `convergents_eq_convergents'`, we proceed by induction. The case `n = 0` is trivial. For `n + 1`, we first "squash" the `n + 1`th position of `c` into the `n`th position to obtain another continued fraction `c' := [h; (a₀, b₀),..., (aₙ-₁, bₙ-₁), (aₙ, bₙ + aₙ₊₁ / bₙ₊₁), (aₙ₊₁, bₙ₊₁),...]`. This squashing process is formalised in section `squash`. Note that directly evaluating `c` up to position `n + 1` is equal to evaluating `c'` up to `n`. This is shown in lemma `succ_nth_convergent'_eq_squash_gcf_nth_convergent'`. By the inductive hypothesis, the two computations for the `n`th convergent of `c` coincide. So all that is left to show is that the recurrence relation for `c` at `n + 1` and and `c'` at `n` coincide. This can be shown by another induction. The corresponding lemma in this file is `succ_nth_convergent_eq_squash_gcf_nth_convergent`. ## Main Theorems - `generalized_continued_fraction.convergents_eq_convergents'` shows the equivalence under a strict positivity restriction on the sequence. - `continued_fractions.convergents_eq_convergents'` shows the equivalence for (regular) continued fractions. ## References - https://en.wikipedia.org/wiki/Generalized_continued_fraction - [*Hardy, GH and Wright, EM and Heath-Brown, Roger and Silverman, Joseph*][hardy2008introduction] ## Tags fractions, recurrence, equivalence -/ variables {K : Type*} {n : ℕ} namespace generalized_continued_fraction variables {g : generalized_continued_fraction K} {s : seq $ pair K} section squash /-! We will show the equivalence of the computations by induction. To make the induction work, we need to be able to *squash* the nth and (n + 1)th value of a sequence. This squashing itself and the lemmas about it are not very interesting. As a reader, you hence might want to skip this section. -/ section with_division_ring variable [division_ring K] /-- Given a sequence of gcf.pairs `s = [(a₀, bₒ), (a₁, b₁), ...]`, `squash_seq s n` combines `⟨aₙ, bₙ⟩` and `⟨aₙ₊₁, bₙ₊₁⟩` at position `n` to `⟨aₙ, bₙ + aₙ₊₁ / bₙ₊₁⟩`. For example, `squash_seq s 0 = [(a₀, bₒ + a₁ / b₁), (a₁, b₁),...]`. If `s.terminated_at (n + 1)`, then `squash_seq s n = s`. -/ def squash_seq (s : seq $ pair K) (n : ℕ) : seq (pair K) := match prod.mk (s.nth n) (s.nth (n + 1)) with | ⟨some gp_n, some gp_succ_n⟩ := seq.nats.zip_with -- return the squashed value at position `n`; otherwise, do nothing. (λ n' gp, if n' = n then ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ else gp) s | _ := s end /-! We now prove some simple lemmas about the squashed sequence -/ /-- If the sequence already terminated at position `n + 1`, nothing gets squashed. -/ lemma squash_seq_eq_self_of_terminated (terminated_at_succ_n : s.terminated_at (n + 1)) : squash_seq s n = s := begin change s.nth (n + 1) = none at terminated_at_succ_n, cases s_nth_eq : (s.nth n); simp only [*, squash_seq] end /-- If the sequence has not terminated before position `n + 1`, the value at `n + 1` gets squashed into position `n`. -/ lemma squash_seq_nth_of_not_terminated {gp_n gp_succ_n : pair K} (s_nth_eq : s.nth n = some gp_n) (s_succ_nth_eq : s.nth (n + 1) = some gp_succ_n) : (squash_seq s n).nth n = some ⟨gp_n.a, gp_n.b + gp_succ_n.a / gp_succ_n.b⟩ := by simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth n) s_nth_eq _)] /-- The values before the squashed position stay the same. -/ lemma squash_seq_nth_of_lt {m : ℕ} (m_lt_n : m < n) : (squash_seq s n).nth m = s.nth m := begin cases s_succ_nth_eq : s.nth (n + 1), case option.none { rw (squash_seq_eq_self_of_terminated s_succ_nth_eq) }, case option.some { obtain ⟨gp_n, s_nth_eq⟩ : ∃ gp_n, s.nth n = some gp_n, from s.ge_stable n.le_succ s_succ_nth_eq, obtain ⟨gp_m, s_mth_eq⟩ : ∃ gp_m, s.nth m = some gp_m, from s.ge_stable (le_of_lt m_lt_n) s_nth_eq, simp [*, squash_seq, (seq.zip_with_nth_some (seq.nats_nth m) s_mth_eq _), (ne_of_lt m_lt_n)] } end /-- Squashing at position `n + 1` and taking the tail is the same as squashing the tail of the sequence at position `n`. -/ lemma squash_seq_succ_n_tail_eq_squash_seq_tail_n : (squash_seq s (n + 1)).tail = squash_seq s.tail n := begin cases s_succ_succ_nth_eq : s.nth (n + 2) with gp_succ_succ_n, case option.none { have : squash_seq s (n + 1) = s, from squash_seq_eq_self_of_terminated s_succ_succ_nth_eq, cases s_succ_nth_eq : (s.nth (n + 1)); simp only [squash_seq, seq.nth_tail, s_succ_nth_eq, s_succ_succ_nth_eq] }, case option.some { obtain ⟨gp_succ_n, s_succ_nth_eq⟩ : ∃ gp_succ_n, s.nth (n + 1) = some gp_succ_n, from s.ge_stable (n + 1).le_succ s_succ_succ_nth_eq, -- apply extensionality with `m` and continue by cases `m = n`. ext m, cases decidable.em (m = n) with m_eq_n m_ne_n, { have : s.tail.nth n = some gp_succ_n, from (s.nth_tail n).trans s_succ_nth_eq, simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth n) this), (seq.zip_with_nth_some (seq.nats_nth (n + 1)) s_succ_nth_eq)] }, { have : s.tail.nth m = s.nth (m + 1), from s.nth_tail m, cases s_succ_mth_eq : s.nth (m + 1), all_goals { have s_tail_mth_eq, from this.trans s_succ_mth_eq }, { simp only [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_none' s_succ_mth_eq), (seq.zip_with_nth_none' s_tail_mth_eq)] }, { simp [*, squash_seq, seq.nth_tail, (seq.zip_with_nth_some (seq.nats_nth (m + 1)) s_succ_mth_eq), (seq.zip_with_nth_some (seq.nats_nth m) s_tail_mth_eq)] } } } end /-- The auxiliary function `convergents'_aux` returns the same value for a sequence and the corresponding squashed sequence at the squashed position. -/ lemma succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq : convergents'_aux s (n + 2) = convergents'_aux (squash_seq s n) (n + 1) := begin cases s_succ_nth_eq : (s.nth $ n + 1) with gp_succ_n, case option.none { rw [(squash_seq_eq_self_of_terminated s_succ_nth_eq), (convergents'_aux_stable_step_of_terminated s_succ_nth_eq)] }, case option.some { induction n with m IH generalizing s gp_succ_n, case nat.zero { obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from s.ge_stable zero_le_one s_succ_nth_eq, have : (squash_seq s 0).head = some ⟨gp_head.a, gp_head.b + gp_succ_n.a / gp_succ_n.b⟩, from squash_seq_nth_of_not_terminated s_head_eq s_succ_nth_eq, simp [*, convergents'_aux, seq.head, seq.nth_tail] }, case nat.succ { obtain ⟨gp_head, s_head_eq⟩ : ∃ gp_head, s.head = some gp_head, from s.ge_stable (m + 2).zero_le s_succ_nth_eq, suffices : gp_head.a / (gp_head.b + convergents'_aux s.tail (m + 2)) = convergents'_aux (squash_seq s (m + 1)) (m + 2), by simpa only [convergents'_aux, s_head_eq], have : convergents'_aux s.tail (m + 2) = convergents'_aux (squash_seq s.tail m) (m + 1), by { refine (IH gp_succ_n _), simpa [seq.nth_tail] using s_succ_nth_eq }, have : (squash_seq s (m + 1)).head = some gp_head, from (squash_seq_nth_of_lt m.succ_pos).trans s_head_eq, simp only [*, convergents'_aux, squash_seq_succ_n_tail_eq_squash_seq_tail_n] } } end /-! Let us now lift the squashing operation to gcfs. -/ /-- Given a gcf `g = [h; (a₀, bₒ), (a₁, b₁), ...]`, we have - `squash_nth.gcf g 0 = [h + a₀ / b₀); (a₀, bₒ), ...]`, - `squash_nth.gcf g (n + 1) = ⟨g.h, squash_seq g.s n⟩` -/ def squash_gcf (g : generalized_continued_fraction K) : ℕ → generalized_continued_fraction K | 0 := match g.s.nth 0 with | none := g | some gp := ⟨g.h + gp.a / gp.b, g.s⟩ end | (n + 1) := ⟨g.h, squash_seq g.s n⟩ /-! Again, we derive some simple lemmas that are not really of interest. This time for the squashed gcf. -/ /-- If the gcf already terminated at position `n`, nothing gets squashed. -/ lemma squash_gcf_eq_self_of_terminated (terminated_at_n : terminated_at g n) : squash_gcf g n = g := begin cases n, case nat.zero { change g.s.nth 0 = none at terminated_at_n, simp only [convergents', squash_gcf, convergents'_aux, terminated_at_n] }, case nat.succ { cases g, simp [(squash_seq_eq_self_of_terminated terminated_at_n), squash_gcf] } end /-- The values before the squashed position stay the same. -/ lemma squash_gcf_nth_of_lt {m : ℕ} (m_lt_n : m < n) : (squash_gcf g (n + 1)).s.nth m = g.s.nth m := by simp only [squash_gcf, (squash_seq_nth_of_lt m_lt_n)] /-- `convergents'` returns the same value for a gcf and the corresponding squashed gcf at the squashed position. -/ lemma succ_nth_convergent'_eq_squash_gcf_nth_convergent' : g.convergents' (n + 1) = (squash_gcf g n).convergents' n := begin cases n, case nat.zero { cases g_s_head_eq : (g.s.nth 0); simp [g_s_head_eq, squash_gcf, convergents', convergents'_aux, seq.head] }, case nat.succ { simp only [succ_succ_nth_convergent'_aux_eq_succ_nth_convergent'_aux_squash_seq, convergents', squash_gcf] } end /-- The auxiliary continuants before the squashed position stay the same. -/ lemma continuants_aux_eq_continuants_aux_squash_gcf_of_le {m : ℕ} : m ≤ n → continuants_aux g m = (squash_gcf g n).continuants_aux m := nat.strong_induction_on m (begin clear m, assume m IH m_le_n, cases m with m', { refl }, { cases n with n', { exact (m'.not_succ_le_zero m_le_n).elim }, -- 1 ≰ 0 { cases m' with m'', { refl }, { -- get some inequalities to instantiate the IH for m'' and m'' + 1 have m'_lt_n : m'' + 1 < n' + 1 := m_le_n, have succ_m''th_conts_aux_eq := IH (m'' + 1) (lt_add_one (m'' + 1)) m'_lt_n.le, have : m'' < m'' + 2 := lt_add_of_pos_right m'' zero_lt_two, have m''th_conts_aux_eq := IH m'' this (le_trans this.le m_le_n), have : (squash_gcf g (n' + 1)).s.nth m'' = g.s.nth m'', from squash_gcf_nth_of_lt (nat.succ_lt_succ_iff.mp m'_lt_n), simp [continuants_aux, succ_m''th_conts_aux_eq, m''th_conts_aux_eq, this] } } } end) end with_division_ring /-- The convergents coincide in the expected way at the squashed position if the partial denominator at the squashed position is not zero. -/ lemma succ_nth_convergent_eq_squash_gcf_nth_convergent [field K] (nth_part_denom_ne_zero : ∀ {b : K}, g.partial_denominators.nth n = some b → b ≠ 0) : g.convergents (n + 1) = (squash_gcf g n).convergents n := begin cases decidable.em (g.terminated_at n) with terminated_at_n not_terminated_at_n, { have : squash_gcf g n = g, from squash_gcf_eq_self_of_terminated terminated_at_n, simp only [this, (convergents_stable_of_terminated n.le_succ terminated_at_n)] }, { obtain ⟨⟨a, b⟩, s_nth_eq⟩ : ∃ gp_n, g.s.nth n = some gp_n, from option.ne_none_iff_exists'.mp not_terminated_at_n, have b_ne_zero : b ≠ 0, from nth_part_denom_ne_zero (part_denom_eq_s_b s_nth_eq), cases n with n', case nat.zero { suffices : (b * g.h + a) / b = g.h + a / b, by simpa [squash_gcf, s_nth_eq, convergent_eq_conts_a_div_conts_b, (continuants_recurrence_aux s_nth_eq zeroth_continuant_aux_eq_one_zero first_continuant_aux_eq_h_one)], calc (b * g.h + a) / b = b * g.h / b + a / b : by ring -- requires `field`, not `division_ring` ... = g.h + a / b : by rw (mul_div_cancel_left _ b_ne_zero) }, case nat.succ { obtain ⟨⟨pa, pb⟩, s_n'th_eq⟩ : ∃ gp_n', g.s.nth n' = some gp_n' := g.s.ge_stable n'.le_succ s_nth_eq, -- Notations let g' := squash_gcf g (n' + 1), set pred_conts := g.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq, set ppred_conts := g.continuants_aux n' with n'th_conts_aux_eq, let pA := pred_conts.a, let pB := pred_conts.b, let ppA := ppred_conts.a, let ppB := ppred_conts.b, set pred_conts' := g'.continuants_aux (n' + 1) with succ_n'th_conts_aux_eq', set ppred_conts' := g'.continuants_aux n' with n'th_conts_aux_eq', let pA' := pred_conts'.a, let pB' := pred_conts'.b, let ppA' := ppred_conts'.a, let ppB' := ppred_conts'.b, -- first compute the convergent of the squashed gcf have : g'.convergents (n' + 1) = ((pb + a / b) * pA' + pa * ppA') / ((pb + a / b) * pB' + pa * ppB'), { have : g'.s.nth n' = some ⟨pa, pb + a / b⟩ := squash_seq_nth_of_not_terminated s_n'th_eq s_nth_eq, rw [convergent_eq_conts_a_div_conts_b, continuants_recurrence_aux this n'th_conts_aux_eq'.symm succ_n'th_conts_aux_eq'.symm], }, rw this, -- then compute the convergent of the original gcf by recursively unfolding the continuants -- computation twice have : g.convergents (n' + 2) = (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB), { -- use the recurrence once have : g.continuants_aux (n' + 2) = ⟨pb * pA + pa * ppA, pb * pB + pa * ppB⟩ := continuants_aux_recurrence s_n'th_eq n'th_conts_aux_eq.symm succ_n'th_conts_aux_eq.symm, -- and a second time rw [convergent_eq_conts_a_div_conts_b, continuants_recurrence_aux s_nth_eq succ_n'th_conts_aux_eq.symm this] }, rw this, suffices : ((pb + a / b) * pA + pa * ppA) / ((pb + a / b) * pB + pa * ppB) = (b * (pb * pA + pa * ppA) + a * pA) / (b * (pb * pB + pa * ppB) + a * pB), { obtain ⟨eq1, eq2, eq3, eq4⟩ : pA' = pA ∧ pB' = pB ∧ ppA' = ppA ∧ ppB' = ppB, { simp [*, (continuants_aux_eq_continuants_aux_squash_gcf_of_le $ le_refl $ n' + 1).symm, (continuants_aux_eq_continuants_aux_squash_gcf_of_le n'.le_succ).symm] }, symmetry, simpa only [eq1, eq2, eq3, eq4, mul_div_cancel _ b_ne_zero] }, field_simp, congr' 1; ring } } end end squash /-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of the gcf coincide at position `n` if the sequence of fractions contains strictly positive values only. Requiring positivity of all values is just one possible condition to obtain this result. For example, the dual - sequences with strictly negative values only - would also work. In practice, one most commonly deals with (regular) continued fractions, which satisfy the positivity criterion required here. The analogous result for them (see `continued_fractions.convergents_eq_convergents`) hence follows directly from this theorem. -/ theorem convergents_eq_convergents' [linear_ordered_field K] (s_pos : ∀ {gp : pair K} {m : ℕ}, m < n → g.s.nth m = some gp → 0 < gp.a ∧ 0 < gp.b) : g.convergents n = g.convergents' n := begin induction n with n IH generalizing g, case nat.zero { simp }, case nat.succ { let g' := squash_gcf g n, -- first replace the rhs with the squashed computation suffices : g.convergents (n + 1) = g'.convergents' n, by rwa [succ_nth_convergent'_eq_squash_gcf_nth_convergent'], cases decidable.em (terminated_at g n) with terminated_at_n not_terminated_at_n, { have g'_eq_g : g' = g, from squash_gcf_eq_self_of_terminated terminated_at_n, rw [(convergents_stable_of_terminated n.le_succ terminated_at_n), g'_eq_g, (IH _)], assume _ _ m_lt_n s_mth_eq, exact (s_pos (nat.lt.step m_lt_n) s_mth_eq) }, { suffices : g.convergents (n + 1) = g'.convergents n, by -- invoke the IH for the squashed gcf { rwa ← IH, assume gp' m m_lt_n s_mth_eq', -- case distinction on m + 1 = n or m + 1 < n cases m_lt_n with n succ_m_lt_n, { -- the difficult case at the squashed position: we first obtain the values from -- the sequence obtain ⟨gp_succ_m, s_succ_mth_eq⟩ : ∃ gp_succ_m, g.s.nth (m + 1) = some gp_succ_m, from option.ne_none_iff_exists'.mp not_terminated_at_n, obtain ⟨gp_m, mth_s_eq⟩ : ∃ gp_m, g.s.nth m = some gp_m, from g.s.ge_stable m.le_succ s_succ_mth_eq, -- we then plug them into the recurrence suffices : 0 < gp_m.a ∧ 0 < gp_m.b + gp_succ_m.a / gp_succ_m.b, by { have ot : g'.s.nth m = some ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, from squash_seq_nth_of_not_terminated mth_s_eq s_succ_mth_eq, have : gp' = ⟨gp_m.a, gp_m.b + gp_succ_m.a / gp_succ_m.b⟩, by cc, rwa this }, refine ⟨(s_pos (nat.lt.step m_lt_n) mth_s_eq).left, _⟩, refine add_pos (s_pos (nat.lt.step m_lt_n) mth_s_eq).right _, have : 0 < gp_succ_m.a ∧ 0 < gp_succ_m.b := s_pos (lt_add_one $ m + 1) s_succ_mth_eq, exact (div_pos this.left this.right) }, { -- the easy case: before the squashed position, nothing changes refine s_pos (nat.lt.step $ nat.lt.step succ_m_lt_n) _, exact eq.trans (squash_gcf_nth_of_lt succ_m_lt_n).symm s_mth_eq' } }, -- now the result follows from the fact that the convergents coincide at the squashed position -- as established in `succ_nth_convergent_eq_squash_gcf_nth_convergent`. have : ∀ ⦃b⦄, g.partial_denominators.nth n = some b → b ≠ 0, by { assume b nth_part_denom_eq, obtain ⟨gp, s_nth_eq, ⟨refl⟩⟩ : ∃ gp, g.s.nth n = some gp ∧ gp.b = b, from exists_s_b_of_part_denom nth_part_denom_eq, exact (ne_of_lt (s_pos (lt_add_one n) s_nth_eq).right).symm }, exact succ_nth_convergent_eq_squash_gcf_nth_convergent this } } end end generalized_continued_fraction open generalized_continued_fraction namespace continued_fraction /-- Shows that the recurrence relation (`convergents`) and direct evaluation (`convergents'`) of a (regular) continued fraction coincide. -/ theorem convergents_eq_convergents' [linear_ordered_field K] {c : continued_fraction K} : (↑c : generalized_continued_fraction K).convergents = (↑c : generalized_continued_fraction K).convergents' := begin ext n, apply convergents_eq_convergents', assume gp m m_lt_n s_nth_eq, exact ⟨zero_lt_one.trans_le ((c : simple_continued_fraction K).property m gp.a (part_num_eq_s_a s_nth_eq)).symm.le, c.property m gp.b $ part_denom_eq_s_b s_nth_eq⟩ end end continued_fraction
c4784944be3493734c58d0ab81dd54ee81d55e4a
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/equiv/basic.lean
4e431125bb2084b4aab5c6932ea8a118dbfc4162
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
28,534
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, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function data.set.basic open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem bijective : ∀ f : α ≃ β, bijective f | ⟨f, g, h₁, h₂⟩ := ⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.bijective.1.eq_iff protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply : ∀ (f : α ≃ β) (g : β ≃ γ) (a : α), (f.trans g) a = g (f a) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ a := rfl @[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] lemma inverse_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl theorem apply_eq_iff_eq_inverse_apply : ∀ (f : α ≃ β) (x : α) (y : β), f x = y ↔ x = f.symm y | ⟨f₁, g₁, l₁, r₁⟩ x y := by simp [equiv.symm]; show f₁ x = y ↔ x = g₁ y; from ⟨λ e : f₁ x = y, e ▸ (l₁ x).symm, λ e : x = g₁ y, e.symm ▸ r₁ y⟩ @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; refl @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by cases e; refl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply inverse_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.inverse_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_inverse_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def true_equiv_punit : true ≃ punit := ⟨λ x, (), λ x, trivial, λ ⟨⟩, rfl, λ ⟨⟩, rfl⟩ protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩ section @[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ × β₁) ≃ (α₂ × β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ ⟨a, b⟩, (f₁ a, f₂ b), λ ⟨a, b⟩, (g₁ a, g₂ b), λ ⟨a, b⟩, show (g₁ (f₁ a), g₂ (f₂ b)) = (a, b), by rw [l₁ a, l₂ b], λ ⟨a, b⟩, show (f₁ (g₁ a), f₂ (g₂ b)) = (a, b), by rw [r₁ a, r₂ b]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := by cases e₁; cases e₂; refl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : (α × punit.{u+1}) ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α := calc (punit × α) ≃ (α × punit) : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : (α × pempty) ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : (pempty × α) ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl def bool_equiv_punit_sum_punit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : (α ⊕ pempty) ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : (pempty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) := calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _ ... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _ ... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ (ℕ ⊕ punit.{u+1}) := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.bijective.1.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ section open subtype def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)} | ⟨f, g, l, r⟩ := ⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l], subtype.map g $ assume a ha, ha, assume p, by simp [map_comp, l.comp_eq_id]; rw [map_id]; refl, assume p, by simp [map_comp, r.comp_eq_id]; rw [map_id]; refl⟩ def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- aka coimage -/ def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β) (h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)), quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hs : x ∈ s then sum.inl ⟨_, hs⟩ else sum.inr ⟨_, h.resolve_left hs⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases x ∈ s; simp [union._match_1, union._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union._match_1, union._match_2, h]; simp [show x ∉ s, from λ h', eq_empty_iff_forall_not_mem.1 H _ ⟨h', h⟩]⟩ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by unfold swap_core; split_ifs; cc theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by unfold swap_core; split_ifs; cc theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by unfold swap_core; split_ifs; cc /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π; refl @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *, simp [swap_apply_def, this], split_ifs; simp end) /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by dsimp [set_value]; simp [swap_apply_left] end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
30bfad413d8578a739ae08a02abf4f1ca160f76b
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/calculus/deriv.lean
e33b7ae3be98c491c0fc8c8dd9ac2346221bfa9b
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
86,255
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv import data.polynomial.derivative /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.html). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. - `has_strict_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x` in the sense of strict differentiability, i.e., `f y - f z = (y - z) • f' + o (y - z)` as `y, z → x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - sum of finitely many functions - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - inverse function (assuming that it exists; the inverse function theorem is in `inverse.lean`) - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space big_operators filter ennreal open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝[s] x) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- `f` has the derivative `f'` at the point `x` in the sense of strict differentiability. That is, `f y - f z = (y - z) • f' + o(y - z)` as `y, z → x`. -/ def has_strict_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := fderiv_within 𝕜 f s x 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := fderiv 𝕜 f x 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] lemma has_fderiv_at_filter.has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L → has_deriv_at_filter f (f' 1) x L := has_fderiv_at_filter_iff_has_deriv_at_filter.mp /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := has_fderiv_at_filter_iff_has_deriv_at_filter /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := iff.rfl lemma has_fderiv_within_at.has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x → has_deriv_within_at f (f' 1) s x := has_fderiv_within_at_iff_has_deriv_within_at.mp lemma has_deriv_within_at.has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x → has_fderiv_within_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') s x := has_deriv_within_at_iff_has_fderiv_within_at.mp /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := has_fderiv_at_filter_iff_has_deriv_at_filter lemma has_fderiv_at.has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x → has_deriv_at f (f' 1) x := has_fderiv_at_iff_has_deriv_at.mp lemma has_strict_fderiv_at_iff_has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x ↔ has_strict_deriv_at f (f' 1) x := by simp [has_strict_deriv_at, has_strict_fderiv_at] protected lemma has_strict_fderiv_at.has_strict_deriv_at {f' : 𝕜 →L[𝕜] F} : has_strict_fderiv_at f f' x → has_strict_deriv_at f (f' 1) x := has_strict_fderiv_at_iff_has_strict_deriv_at.mp lemma has_strict_deriv_at_iff_has_strict_fderiv_at : has_strict_deriv_at f f' x ↔ has_strict_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_strict_deriv_at_iff_has_strict_fderiv_at ↔ has_strict_deriv_at.has_strict_fderiv_at _ /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right (1 : 𝕜 →L[𝕜] 𝕜) f') x := iff.rfl alias has_deriv_at_iff_has_fderiv_at ↔ has_deriv_at.has_fderiv_at _ lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma differentiable_within_at_of_deriv_within_ne_zero (h : deriv_within f s x ≠ 0) : differentiable_within_at 𝕜 f s x := not_imp_comm.1 deriv_within_zero_of_not_differentiable_within_at h lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } lemma differentiable_at_of_deriv_ne_zero (h : deriv f x ≠ 0) : differentiable_at 𝕜 f x := not_imp_comm.1 deriv_zero_of_not_differentiable_at h theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝[s] x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_strict_deriv_at.has_deriv_at (h : has_strict_deriv_at f f' x) : has_deriv_at f f' x := h.has_fderiv_at /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ 𝓟 {x}ᶜ) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation_sub f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), refine (eventually_principal.2 $ λ z hz, _).filter_mono inf_le_right, simp only [(∘)], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 hz), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s \ {x}] x) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[s] x) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (𝓝[{x}ᶜ] x) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_within_at_congr_set {s t u : set 𝕜} (hu : u ∈ 𝓝 x) (h : s ∩ u = t ∩ u) : has_deriv_within_at f f' s x ↔ has_deriv_within_at f f' t x := by simp_rw [has_deriv_within_at, nhds_within_eq_nhds_within' hu h] alias has_deriv_within_at_congr_set ↔ has_deriv_within_at.congr_set _ @[simp] lemma has_deriv_within_at_diff_singleton : has_deriv_within_at f f' (s \ {x}) x ↔ has_deriv_within_at f f' s x := by simp only [has_deriv_within_at_iff_tendsto_slope, sdiff_idem] @[simp] lemma has_deriv_within_at_Ioi_iff_Ici [partial_order 𝕜] : has_deriv_within_at f f' (Ioi x) x ↔ has_deriv_within_at f f' (Ici x) x := by rw [← Ici_diff_left, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Ioi_iff_Ici ↔ has_deriv_within_at.Ici_of_Ioi has_deriv_within_at.Ioi_of_Ici @[simp] lemma has_deriv_within_at_Iio_iff_Iic [partial_order 𝕜] : has_deriv_within_at f f' (Iio x) x ↔ has_deriv_within_at f f' (Iic x) x := by rw [← Iic_diff_right, has_deriv_within_at_diff_singleton] alias has_deriv_within_at_Iio_iff_Iic ↔ has_deriv_within_at.Iic_of_Iio has_deriv_within_at.Iio_of_Iic theorem has_deriv_within_at.Ioi_iff_Ioo [linear_order 𝕜] [order_closed_topology 𝕜] {x y : 𝕜} (h : x < y) : has_deriv_within_at f f' (Ioo x y) x ↔ has_deriv_within_at f f' (Ioi x) x := has_deriv_within_at_congr_set (is_open_Iio.mem_nhds h) $ by { rw [Ioi_inter_Iio, inter_eq_left_iff_subset], exact Ioo_subset_Iio_self } alias has_deriv_within_at.Ioi_iff_Ioo ↔ has_deriv_within_at.Ioi_of_Ioo has_deriv_within_at.Ioo_of_Ioi theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at.unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ h₀.has_fderiv_at.unique h₁ lemma has_deriv_within_at_inter' (h : t ∈ 𝓝[s] x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ 𝓝[t] x) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := h.has_fderiv_within_at.has_deriv_within_at lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := h.has_fderiv_at.has_deriv_at lemma differentiable_on.has_deriv_at (h : differentiable_on 𝕜 f s) (hs : s ∈ 𝓝 x) : has_deriv_at f (deriv f x) x := (h.has_fderiv_at hs).has_deriv_at lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := h.differentiable_at.has_deriv_at.unique h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right (1 : 𝕜 →L[𝕜] 𝕜) (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } lemma deriv_within_of_open (hs : is_open s) (hx : x ∈ s) : deriv_within f s x = deriv f x := by { unfold deriv_within, rw fderiv_within_of_open hs hx, refl } section congr /-! ### Congruence properties of derivatives -/ theorem filter.eventually_eq.has_deriv_at_filter_iff (h₀ : f₀ =ᶠ[L] f₁) (hx : f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := h₀.has_fderiv_at_filter_iff hx (by simp [h₁]) lemma has_deriv_at_filter.congr_of_eventually_eq (h : has_deriv_at_filter f f' x L) (hL : f₁ =ᶠ[L] f) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa hL.has_deriv_at_filter_iff hx rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_eventually_eq (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_eventually_eq h h₁ hx lemma has_deriv_within_at.congr_of_eventually_eq_of_mem (h : has_deriv_within_at f f' s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : x ∈ s) : has_deriv_within_at f₁ f' s x := h.congr_of_eventually_eq h₁ (h₁.eq_of_nhds_within hx) lemma has_deriv_at.congr_of_eventually_eq (h : has_deriv_at f f' x) (h₁ : f₁ =ᶠ[𝓝 x] f) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_eventually_eq h h₁ (mem_of_mem_nhds h₁ : _) lemma filter.eventually_eq.deriv_within_eq (hs : unique_diff_within_at 𝕜 s x) (hL : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw hL.fderiv_within_eq hs hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma filter.eventually_eq.deriv_eq (hL : f₁ =ᶠ[𝓝 x] f) : deriv f₁ x = deriv f x := by { unfold deriv, rwa filter.eventually_eq.fderiv_eq } protected lemma filter.eventually_eq.deriv (h : f₁ =ᶠ[𝓝 x] f) : deriv f₁ =ᶠ[𝓝 x] deriv f := h.eventually_eq_nhds.mono $ λ x h, h.deriv_eq end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (has_fderiv_at_filter_id x L).has_deriv_at_filter theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ theorem has_strict_deriv_at_id : has_strict_deriv_at id 1 x := (has_strict_fderiv_at_id x).has_strict_deriv_at lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) = λ _, 1 := deriv_id' lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := (has_deriv_within_at_id x s).deriv_within hxs end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (has_fderiv_at_filter_const c x L).has_deriv_at_filter theorem has_strict_deriv_at_const : has_strict_deriv_at (λ x, c) 0 x := (has_strict_fderiv_at_const c x).has_strict_deriv_at theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := (has_deriv_within_at_const _ _ _).deriv_within hxs end const section continuous_linear_map /-! ### Derivative of continuous linear maps -/ variables (e : 𝕜 →L[𝕜] F) protected lemma continuous_linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.has_fderiv_at_filter.has_deriv_at_filter protected lemma continuous_linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.has_strict_fderiv_at.has_strict_deriv_at protected lemma continuous_linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma continuous_linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma continuous_linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma continuous_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end continuous_linear_map section linear_map /-! ### Derivative of bundled linear maps -/ variables (e : 𝕜 →ₗ[𝕜] F) protected lemma linear_map.has_deriv_at_filter : has_deriv_at_filter e (e 1) x L := e.to_continuous_linear_map₁.has_deriv_at_filter protected lemma linear_map.has_strict_deriv_at : has_strict_deriv_at e (e 1) x := e.to_continuous_linear_map₁.has_strict_deriv_at protected lemma linear_map.has_deriv_at : has_deriv_at e (e 1) x := e.has_deriv_at_filter protected lemma linear_map.has_deriv_within_at : has_deriv_within_at e (e 1) s x := e.has_deriv_at_filter @[simp] protected lemma linear_map.deriv : deriv e x = e 1 := e.has_deriv_at.deriv protected lemma linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within e s x = e 1 := e.has_deriv_within_at.deriv_within hxs end linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := by simpa using (hf.add hg).has_deriv_at_filter theorem has_strict_deriv_at.add (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ y, f y + g y) (f' + g') x := by simpa using (hf.add hg).has_strict_deriv_at theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_add_const hxs] lemma deriv_add_const (c : F) : deriv (λy, f y + c) x = deriv f x := by simp only [deriv, fderiv_add_const] @[simp] lemma deriv_add_const' (c : F) : deriv (λ y, f y + c) = deriv f := funext $ λ x, deriv_add_const c theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c + f y) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_const_add hxs] lemma deriv_const_add (c : F) : deriv (λy, c + f y) x = deriv f x := by simp only [deriv, fderiv_const_add] @[simp] lemma deriv_const_add' (c : F) : deriv (λ y, c + f y) = deriv f := funext $ λ x, deriv_const_add c end add section sum /-! ### Derivative of a finite sum of functions -/ open_locale big_operators variables {ι : Type*} {u : finset ι} {A : ι → (𝕜 → F)} {A' : ι → F} theorem has_deriv_at_filter.sum (h : ∀ i ∈ u, has_deriv_at_filter (A i) (A' i) x L) : has_deriv_at_filter (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x L := by simpa [continuous_linear_map.sum_apply] using (has_fderiv_at_filter.sum h).has_deriv_at_filter theorem has_strict_deriv_at.sum (h : ∀ i ∈ u, has_strict_deriv_at (A i) (A' i) x) : has_strict_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := by simpa [continuous_linear_map.sum_apply] using (has_strict_fderiv_at.sum h).has_strict_deriv_at theorem has_deriv_within_at.sum (h : ∀ i ∈ u, has_deriv_within_at (A i) (A' i) s x) : has_deriv_within_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) s x := has_deriv_at_filter.sum h theorem has_deriv_at.sum (h : ∀ i ∈ u, has_deriv_at (A i) (A' i) x) : has_deriv_at (λ y, ∑ i in u, A i y) (∑ i in u, A' i) x := has_deriv_at_filter.sum h lemma deriv_within_sum (hxs : unique_diff_within_at 𝕜 s x) (h : ∀ i ∈ u, differentiable_within_at 𝕜 (A i) s x) : deriv_within (λ y, ∑ i in u, A i y) s x = ∑ i in u, deriv_within (A i) s x := (has_deriv_within_at.sum (λ i hi, (h i hi).has_deriv_within_at)).deriv_within hxs @[simp] lemma deriv_sum (h : ∀ i ∈ u, differentiable_at 𝕜 (A i) x) : deriv (λ y, ∑ i in u, A i y) x = ∑ i in u, deriv (A i) x := (has_deriv_at.sum (λ i hi, (h i hi).has_deriv_at)).deriv end sum section pi /-! ### Derivatives of functions `f : 𝕜 → Π i, E i` -/ variables {ι : Type*} [fintype ι] {E' : ι → Type*} [Π i, normed_group (E' i)] [Π i, normed_space 𝕜 (E' i)] {φ : 𝕜 → Π i, E' i} {φ' : Π i, E' i} @[simp] lemma has_strict_deriv_at_pi : has_strict_deriv_at φ φ' x ↔ ∀ i, has_strict_deriv_at (λ x, φ x i) (φ' i) x := has_strict_fderiv_at_pi' @[simp] lemma has_deriv_at_filter_pi : has_deriv_at_filter φ φ' x L ↔ ∀ i, has_deriv_at_filter (λ x, φ x i) (φ' i) x L := has_fderiv_at_filter_pi' lemma has_deriv_at_pi : has_deriv_at φ φ' x ↔ ∀ i, has_deriv_at (λ x, φ x i) (φ' i) x:= has_deriv_at_filter_pi lemma has_deriv_within_at_pi : has_deriv_within_at φ φ' s x ↔ ∀ i, has_deriv_within_at (λ x, φ x i) (φ' i) s x:= has_deriv_at_filter_pi lemma deriv_within_pi (h : ∀ i, differentiable_within_at 𝕜 (λ x, φ x i) s x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within φ s x = λ i, deriv_within (λ x, φ x i) s x := (has_deriv_within_at_pi.2 (λ i, (h i).has_deriv_within_at)).deriv_within hs lemma deriv_pi (h : ∀ i, differentiable_at 𝕜 (λ x, φ x i) x) : deriv φ x = λ i, deriv (λ x, φ x i) x := (has_deriv_at_pi.2 (λ i, (h i).has_deriv_at)).deriv end pi section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := by simpa using (has_fderiv_within_at.smul hc hf).has_deriv_within_at theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end theorem has_strict_deriv_at.smul (hc : has_strict_deriv_at c c' x) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := by simpa using (hc.smul hf).has_strict_deriv_at lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := by simpa using h.neg.has_deriv_at_filter theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg theorem has_strict_deriv_at.neg (h : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, -f x) (-f') x := by simpa using h.neg.has_strict_deriv_at lemma deriv_within.neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := by simp only [deriv_within, fderiv_within_neg hxs, continuous_linear_map.neg_apply] lemma deriv.neg : deriv (λy, -f y) x = - deriv f x := by simp only [deriv, fderiv_neg, continuous_linear_map.neg_apply] @[simp] lemma deriv.neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv.neg end neg section neg2 /-! ### Derivative of the negation function (i.e `has_neg.neg`) -/ variables (s x L) theorem has_deriv_at_filter_neg : has_deriv_at_filter has_neg.neg (-1) x L := has_deriv_at_filter.neg $ has_deriv_at_filter_id _ _ theorem has_deriv_within_at_neg : has_deriv_within_at has_neg.neg (-1) s x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg : has_deriv_at has_neg.neg (-1) x := has_deriv_at_filter_neg _ _ theorem has_deriv_at_neg' : has_deriv_at (λ x, -x) (-1) x := has_deriv_at_filter_neg _ _ theorem has_strict_deriv_at_neg : has_strict_deriv_at has_neg.neg (-1) x := has_strict_deriv_at.neg $ has_strict_deriv_at_id _ lemma deriv_neg : deriv has_neg.neg x = -1 := has_deriv_at.deriv (has_deriv_at_neg x) @[simp] lemma deriv_neg' : deriv (has_neg.neg : 𝕜 → 𝕜) = λ _, -1 := funext deriv_neg @[simp] lemma deriv_neg'' : deriv (λ x : 𝕜, -x) x = -1 := deriv_neg x lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) : deriv_within has_neg.neg s x = -1 := (has_deriv_within_at_neg x s).deriv_within hxs lemma differentiable_neg : differentiable 𝕜 (has_neg.neg : 𝕜 → 𝕜) := differentiable.neg differentiable_id lemma differentiable_on_neg : differentiable_on 𝕜 (has_neg.neg : 𝕜 → 𝕜) s := differentiable_on.neg differentiable_on_id end neg2 section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := by simpa only [sub_eq_add_neg] using hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg theorem has_strict_deriv_at.sub (hf : has_strict_deriv_at f f' x) (hg : has_strict_deriv_at g g' x) : has_strict_deriv_at (λ x, f x - g x) (f' - g') x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := by simpa only [sub_eq_add_neg] using hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := by simp only [deriv_within, fderiv_within_sub_const hxs] lemma deriv_sub_const (c : F) : deriv (λ y, f y - c) x = deriv f x := by simp only [deriv, fderiv_sub_const] theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_strict_deriv_at.const_sub (c : F) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (λ x, c - f x) (-f') x := by simpa only [sub_eq_add_neg] using hf.neg.const_add c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) : deriv_within (λy, c - f y) s x = -deriv_within f s x := by simp [deriv_within, fderiv_within_const_sub hxs] lemma deriv_const_sub (c : F) : deriv (λ y, c - f y) x = -deriv f x := by simp only [← deriv_within_univ, deriv_within_const_sub unique_diff_within_at_univ] end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := h.tendsto_nhds hL theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h protected theorem has_deriv_at.continuous_on {f f' : 𝕜 → F} (hderiv : ∀ x ∈ s, has_deriv_at f (f' x) x) : continuous_on f s := λ x hx, (hderiv x hx).continuous_at.continuous_within_at end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := hf₁.prod hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ lemma has_strict_deriv_at.prod (hf₁ : has_strict_deriv_at f₁ f₁' x) (hf₂ : has_strict_deriv_at f₂ f₂' x) : has_strict_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := by simpa using (hg.comp x hh).has_deriv_at_filter theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg $ hh.continuous_within_at.tendsto_nhds_within hst) hh /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_strict_deriv_at.scomp (hg : has_strict_deriv_at g g' (h x)) (hh : has_strict_deriv_at h h' x) : has_strict_deriv_at (g ∘ h) (h' • g') x := by simpa using (hg.comp x hh).has_strict_deriv_at theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of a scalar and vector functions -/ theorem has_deriv_at_filter.comp_has_fderiv_at_filter {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) {L : filter E} (hh₁ : has_deriv_at_filter h₁ h₁' (f x) (L.map f)) (hf : has_fderiv_at_filter f f' x L) : has_fderiv_at_filter (h₁ ∘ f) (h₁' • f') x L := by { convert has_fderiv_at_filter.comp x hh₁ hf, ext x, simp [mul_comm] } theorem has_strict_deriv_at.comp_has_strict_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_strict_deriv_at h₁ h₁' (f x)) (hf : has_strict_fderiv_at f f' x) : has_strict_fderiv_at (h₁ ∘ f) (h₁' • f') x := by { rw has_strict_deriv_at at hh₁, convert hh₁.comp x hf, ext x, simp [mul_comm] } theorem has_deriv_at.comp_has_fderiv_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_at f f' x) : has_fderiv_at (h₁ ∘ f) (h₁' • f') x := (hh₁.mono hf.continuous_at).comp_has_fderiv_at_filter x hf theorem has_deriv_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s} (x) (hh₁ : has_deriv_at h₁ h₁' (f x)) (hf : has_fderiv_within_at f f' s x) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (hh₁.mono hf.continuous_within_at).comp_has_fderiv_at_filter x hf theorem has_deriv_within_at.comp_has_fderiv_within_at {f : E → 𝕜} {f' : E →L[𝕜] 𝕜} {s t} (x) (hh₁ : has_deriv_within_at h₁ h₁' t (f x)) (hf : has_fderiv_within_at f f' s x) (hst : maps_to f s t) : has_fderiv_within_at (h₁ ∘ f) (h₁' • f') s x := (has_deriv_at_filter.mono hh₁ $ hf.continuous_within_at.tendsto_nhds_within hst).comp_has_fderiv_at_filter x hf /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_strict_deriv_at.comp (hh₁ : has_strict_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_strict_deriv_at h₂ h₂' x) : has_strict_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end protected lemma has_deriv_at_filter.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at_filter f f' x L) (hL : tendsto f L L) (hx : f x = x) (n : ℕ) : has_deriv_at_filter (f^[n]) (f'^n) x L := begin have := hf.iterate hL hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_deriv_at (f^[n]) (f'^n) x := begin have := has_fderiv_at.iterate hf hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_deriv_within_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_deriv_within_at f f' s x) (hx : f x = x) (hs : maps_to f s s) (n : ℕ) : has_deriv_within_at (f^[n]) (f'^n) s x := begin have := has_fderiv_within_at.iterate hf hx hs n, rwa [continuous_linear_map.smul_right_one_pow] at this end protected lemma has_strict_deriv_at.iterate {f : 𝕜 → 𝕜} {f' : 𝕜} (hf : has_strict_deriv_at f f' x) (hx : f x = x) (n : ℕ) : has_strict_deriv_at (f^[n]) (f'^n) x := begin have := hf.iterate hx n, rwa [continuous_linear_map.smul_right_one_pow] at this end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and a function on `𝕜` -/ open continuous_linear_map variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : maps_to f s t) : has_deriv_within_at (l ∘ f) (l' f') s x := by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)] using (hl.comp x hf.has_fderiv_within_at hst).has_deriv_within_at theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' f') s x := hl.has_fderiv_within_at.comp_has_deriv_within_at x hf (maps_to_univ _ _) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' f') x := has_deriv_within_at_univ.mp $ hl.comp_has_deriv_within_at x hf.has_deriv_within_at theorem has_strict_fderiv_at.comp_has_strict_deriv_at (hl : has_strict_fderiv_at l l' (f x)) (hf : has_strict_deriv_at f f' x) : has_strict_deriv_at (l ∘ f) (l' f') x := by simpa only [one_apply, one_smul, smul_right_apply, coe_comp', (∘)] using (hl.comp x hf.has_strict_fderiv_at).has_strict_deriv_at lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : maps_to f s t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := (hl.has_fderiv_within_at.comp_has_deriv_within_at x hf.has_deriv_within_at hs).deriv_within hxs lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := (hl.has_fderiv_at.comp_has_deriv_at x hf.has_deriv_at).deriv end composition_vector section mul /-! ### Derivative of the multiplication of two functions -/ variables {𝕜' 𝔸 : Type*} [normed_field 𝕜'] [normed_ring 𝔸] [normed_algebra 𝕜 𝕜'] [normed_algebra 𝕜 𝔸] {c d : 𝕜 → 𝔸} {c' d' : 𝔸} {u v : 𝕜 → 𝕜'} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin have := (has_fderiv_within_at.mul' hc hd).has_deriv_within_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end theorem has_strict_deriv_at.mul (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin have := (has_strict_fderiv_at.mul' hc hd).has_strict_deriv_at, rwa [continuous_linear_map.add_apply, continuous_linear_map.smul_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.smul_right_apply, continuous_linear_map.one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝔸) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝔸) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end theorem has_strict_deriv_at.mul_const (hc : has_strict_deriv_at c c' x) (d : 𝔸) : has_strict_deriv_at (λ y, c y * d) (c' * d) x := begin convert hc.mul (has_strict_deriv_at_const x d), rw [mul_zero, add_zero] end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝔸) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝔸) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv lemma deriv_mul_const_field (v : 𝕜') : deriv (λ y, u y * v) x = deriv u x * v := begin by_cases hu : differentiable_at 𝕜 u x, { exact deriv_mul_const hu v }, { rw [deriv_zero_of_not_differentiable_at hu, zero_mul], rcases eq_or_ne v 0 with rfl|hd, { simp only [mul_zero, deriv_const] }, { refine deriv_zero_of_not_differentiable_at (mt (λ H, _) hu), simpa only [mul_inv_cancel_right₀ hd] using H.mul_const v⁻¹ } } end @[simp] lemma deriv_mul_const_field' (v : 𝕜') : deriv (λ x, u x * v) = λ x, deriv u x * v := funext $ λ _, deriv_mul_const_field v theorem has_deriv_within_at.const_mul (c : 𝔸) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝔸) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end theorem has_strict_deriv_at.const_mul (c : 𝔸) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, c * d y) (c * d') x := begin convert (has_strict_deriv_at_const _ _).mul hd, rw [zero_mul, zero_add] end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝔸) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝔸) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv lemma deriv_const_mul_field (u : 𝕜') : deriv (λ y, u * v y) x = u * deriv v x := by simp only [mul_comm u, deriv_mul_const_field] @[simp] lemma deriv_const_mul_field' (u : 𝕜') : deriv (λ x, u * v x) = λ x, u * deriv v x := funext (λ x, deriv_const_mul_field u) end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : is_o (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) (λ (p : 𝕜 × 𝕜), (p.1 - p.2) * 1) (𝓝 (x, x)), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono (is_open.mem_nhds (is_open_ne.prod is_open_ne) ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv : differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:= ⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at, λ H, (has_deriv_at_inv H).differentiable_at⟩ lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv.2 x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := begin rcases eq_or_ne x 0 with rfl|hne, { simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] }, { exact (has_deriv_at_inv hne).deriv } end @[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv) lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact deriv_inv end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv : fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := by rw [← deriv_fderiv, deriv_inv] lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact fderiv_inv end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) (hx : d x ≠ 0) : has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv lemma differentiable_within_at.div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} : differentiable_within_at 𝕜 (λx, c x / d) s x := by simp [div_eq_inv_mul, differentiable_within_at.const_mul, hc] @[simp] lemma differentiable_at.div_const (hc : differentiable_at 𝕜 c x) {d : 𝕜} : differentiable_at 𝕜 (λ x, c x / d) x := by simpa only [div_eq_mul_inv] using (hc.has_deriv_at.mul_const d⁻¹).differentiable_at lemma differentiable_on.div_const (hc : differentiable_on 𝕜 c s) {d : 𝕜} : differentiable_on 𝕜 (λx, c x / d) s := by simp [div_eq_inv_mul, differentiable_on.const_mul, hc] @[simp] lemma differentiable.div_const (hc : differentiable 𝕜 c) {d : 𝕜} : differentiable 𝕜 (λx, c x / d) := by simp [div_eq_inv_mul, differentiable.const_mul, hc] lemma deriv_within_div_const (hc : differentiable_within_at 𝕜 c s x) {d : 𝕜} (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d) s x = (deriv_within c s x) / d := by simp [div_eq_inv_mul, deriv_within_const_mul, hc, hxs] @[simp] lemma deriv_div_const (d : 𝕜) : deriv (λx, c x / d) x = (deriv c x) / d := by simp only [div_eq_mul_inv, deriv_mul_const_field] end division section clm_comp_apply /-! ### Derivative of the pointwise composition/application of continuous linear maps -/ open continuous_linear_map variables {G : Type*} [normed_group G] [normed_space 𝕜 G] {c : 𝕜 → F →L[𝕜] G} {c' : F →L[𝕜] G} {d : 𝕜 → E →L[𝕜] F} {d' : E →L[𝕜] F} {u : 𝕜 → F} {u' : F} lemma has_strict_deriv_at.clm_comp (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) : has_strict_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin have := (hc.has_strict_fderiv_at.clm_comp hd.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_comp (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') s x := begin have := (hc.has_fderiv_within_at.clm_comp hd.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, comp_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_comp (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, (c y).comp (d y)) (c'.comp (d x) + (c x).comp d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.clm_comp hd end lemma deriv_within_clm_comp (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hxs : unique_diff_within_at 𝕜 s x): deriv_within (λ y, (c y).comp (d y)) s x = ((deriv_within c s x).comp (d x) + (c x).comp (deriv_within d s x)) := (hc.has_deriv_within_at.clm_comp hd.has_deriv_within_at).deriv_within hxs lemma deriv_clm_comp (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, (c y).comp (d y)) x = ((deriv c x).comp (d x) + (c x).comp (deriv d x)) := (hc.has_deriv_at.clm_comp hd.has_deriv_at).deriv lemma has_strict_deriv_at.clm_apply (hc : has_strict_deriv_at c c' x) (hu : has_strict_deriv_at u u' x) : has_strict_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_strict_fderiv_at.clm_apply hu.has_strict_fderiv_at).has_strict_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_within_at.clm_apply (hc : has_deriv_within_at c c' s x) (hu : has_deriv_within_at u u' s x) : has_deriv_within_at (λ y, (c y) (u y)) (c' (u x) + c x u') s x := begin have := (hc.has_fderiv_within_at.clm_apply hu.has_fderiv_within_at).has_deriv_within_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma has_deriv_at.clm_apply (hc : has_deriv_at c c' x) (hu : has_deriv_at u u' x) : has_deriv_at (λ y, (c y) (u y)) (c' (u x) + c x u') x := begin have := (hc.has_fderiv_at.clm_apply hu.has_fderiv_at).has_deriv_at, rwa [add_apply, comp_apply, flip_apply, smul_right_apply, smul_right_apply, one_apply, one_smul, one_smul, add_comm] at this, end lemma deriv_within_clm_apply (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hu : differentiable_within_at 𝕜 u s x) : deriv_within (λ y, (c y) (u y)) s x = (deriv_within c s x (u x) + c x (deriv_within u s x)) := (hc.has_deriv_within_at.clm_apply hu.has_deriv_within_at).deriv_within hxs lemma deriv_clm_apply (hc : differentiable_at 𝕜 c x) (hu : differentiable_at 𝕜 u x) : deriv (λ y, (c y) (u y)) x = (deriv c x (u x) + c x (deriv u x)) := (hc.has_deriv_at.clm_apply hu.has_deriv_at).deriv end clm_comp_apply theorem has_strict_deriv_at.has_strict_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_strict_deriv_at f f' x) (hf' : f' ≠ 0) : has_strict_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf theorem has_deriv_at.has_fderiv_at_equiv {f : 𝕜 → 𝕜} {f' x : 𝕜} (hf : has_deriv_at f f' x) (hf' : f' ≠ 0) : has_fderiv_at f (continuous_linear_equiv.units_equiv_aut 𝕜 (units.mk0 f' hf') : 𝕜 →L[𝕜] 𝕜) x := hf /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a` in the strict sense, then `g` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_strict_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_strict_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_strict_deriv_at g f'⁻¹ a := (hf.has_strict_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has a nonzero derivative `f'` at `f.symm a` in the strict sense, then `f.symm` has the derivative `f'⁻¹` at `a` in the strict sense. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_strict_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_strict_deriv_at f f' (f.symm a)) : has_strict_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) /-- If `f (g y) = y` for `y` in some neighborhood of `a`, `g` is continuous at `a`, and `f` has an invertible derivative `f'` at `g a`, then `g` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ theorem has_deriv_at.of_local_left_inverse {f g : 𝕜 → 𝕜} {f' a : 𝕜} (hg : continuous_at g a) (hf : has_deriv_at f f' (g a)) (hf' : f' ≠ 0) (hfg : ∀ᶠ y in 𝓝 a, f (g y) = y) : has_deriv_at g f'⁻¹ a := (hf.has_fderiv_at_equiv hf').of_local_left_inverse hg hfg /-- If `f` is a local homeomorphism defined on a neighbourhood of `f.symm a`, and `f` has an nonzero derivative `f'` at `f.symm a`, then `f.symm` has the derivative `f'⁻¹` at `a`. This is one of the easy parts of the inverse function theorem: it assumes that we already have an inverse function. -/ lemma local_homeomorph.has_deriv_at_symm (f : local_homeomorph 𝕜 𝕜) {a f' : 𝕜} (ha : a ∈ f.target) (hf' : f' ≠ 0) (htff' : has_deriv_at f f' (f.symm a)) : has_deriv_at f.symm f'⁻¹ a := htff'.of_local_left_inverse (f.symm.continuous_at ha) hf' (f.eventually_right_inverse ha) lemma has_deriv_at.eventually_ne (h : has_deriv_at f f' x) (hf' : f' ≠ 0) : ∀ᶠ z in 𝓝[{x}ᶜ] x, f z ≠ f x := (has_deriv_at_iff_has_fderiv_at.1 h).eventually_ne ⟨∥f'∥⁻¹, λ z, by field_simp [norm_smul, mt norm_eq_zero.1 hf']⟩ theorem not_differentiable_within_at_of_local_left_inverse_has_deriv_within_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} {s t : set 𝕜} (ha : a ∈ s) (hsu : unique_diff_within_at 𝕜 s a) (hf : has_deriv_within_at f 0 t (g a)) (hst : maps_to g s t) (hfg : f ∘ g =ᶠ[𝓝[s] a] id) : ¬differentiable_within_at 𝕜 g s a := begin intro hg, have := (hf.comp a hg.has_deriv_within_at hst).congr_of_eventually_eq_of_mem hfg.symm ha, simpa using hsu.eq_deriv _ this (has_deriv_within_at_id _ _) end theorem not_differentiable_at_of_local_left_inverse_has_deriv_at_zero {f g : 𝕜 → 𝕜} {a : 𝕜} (hf : has_deriv_at f 0 (g a)) (hfg : f ∘ g =ᶠ[𝓝 a] id) : ¬differentiable_at 𝕜 g a := begin intro hg, have := (hf.comp a hg.has_deriv_at).congr_of_eventually_eq hfg.symm, simpa using this.unique (has_deriv_at_id a) end end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_strict_deriv_at (x : 𝕜) : has_strict_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_strict_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_strict_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := (p.has_strict_deriv_at x).has_deriv_at protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) x := p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x)) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (p.derivative.eval x) := (p.has_fderiv_within_at x).fderiv_within hxs end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_strict_deriv_at_pow (n : ℕ) (x : 𝕜) : has_strict_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C (1 : 𝕜) * (polynomial.X)^n).has_strict_deriv_at x, { simp }, { rw [polynomial.derivative_C_mul_X_pow], simp } end lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := (has_strict_deriv_at_pow n x).has_deriv_at theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section zpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} {m : ℤ} lemma has_strict_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : has_strict_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_strict_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [zpow_coe_nat, int.cast_coe_nat], convert has_strict_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, zpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have hx : x ≠ 0, from h.resolve_right hm.not_le, have := (has_strict_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact zpow_ne_zero_of_ne_zero hx _], simp only [(∘), zpow_neg₀, one_div, inv_inv₀, smul_eq_mul] at this, convert this using 1, rw [sq, mul_inv₀, inv_inv₀, int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← zpow_add₀ hx, mul_assoc, ← zpow_add₀ hx], congr, abel }, { simp only [hm, zpow_zero, int.cast_zero, zero_mul, has_strict_deriv_at_const] }, { exact this m hm } end lemma has_deriv_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := (has_strict_deriv_at_zpow m x h).has_deriv_at theorem has_deriv_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_zpow m x h).has_deriv_within_at lemma differentiable_at_zpow : differentiable_at 𝕜 (λx, x^m) x ↔ x ≠ 0 ∨ 0 ≤ m := ⟨λ H, normed_field.continuous_at_zpow.1 H.continuous_at, λ H, (has_deriv_at_zpow m x H).differentiable_at⟩ lemma differentiable_within_at_zpow (m : ℤ) (x : 𝕜) (h : x ≠ 0 ∨ 0 ≤ m) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_zpow.mpr h).differentiable_within_at lemma differentiable_on_zpow (m : ℤ) (s : set 𝕜) (h : (0 : 𝕜) ∉ s ∨ 0 ≤ m) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_zpow m x $ h.imp_left $ ne_of_mem_of_not_mem hxs lemma deriv_zpow (m : ℤ) (x : 𝕜) : deriv (λ x, x ^ m) x = m * x ^ (m - 1) := begin by_cases H : x ≠ 0 ∨ 0 ≤ m, { exact (has_deriv_at_zpow m x H).deriv }, { rw deriv_zero_of_not_differentiable_at (mt differentiable_at_zpow.1 H), push_neg at H, rcases H with ⟨rfl, hm⟩, rw [zero_zpow _ ((sub_one_lt _).trans hm).ne, mul_zero] } end @[simp] lemma deriv_zpow' (m : ℤ) : deriv (λ x : 𝕜, x ^ m) = λ x, m * x ^ (m - 1) := funext $ deriv_zpow m lemma deriv_within_zpow (hxs : unique_diff_within_at 𝕜 s x) (h : x ≠ 0 ∨ 0 ≤ m) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_zpow m x h s).deriv_within hxs @[simp] lemma iter_deriv_zpow' (m : ℤ) (k : ℕ) : deriv^[k] (λ x : 𝕜, x ^ m) = λ x, (∏ i in finset.range k, (m - i)) * x ^ (m - k) := begin induction k with k ihk, { simp only [one_mul, int.coe_nat_zero, id, sub_zero, finset.prod_range_zero, function.iterate_zero] }, { simp only [function.iterate_succ_apply', ihk, deriv_const_mul_field', deriv_zpow', finset.prod_range_succ, int.coe_nat_succ, ← sub_sub, int.cast_sub, int.cast_coe_nat, mul_assoc], } end lemma iter_deriv_zpow (m : ℤ) (x : 𝕜) (k : ℕ) : deriv^[k] (λ y, y ^ m) x = (∏ i in finset.range k, (m - i)) * x ^ (m - k) := congr_fun (iter_deriv_zpow' m k) x lemma iter_deriv_pow (n : ℕ) (x : 𝕜) (k : ℕ) : deriv^[k] (λx:𝕜, x^n) x = (∏ i in finset.range k, (n - i)) * x^(n-k) := begin simp only [← zpow_coe_nat, iter_deriv_zpow, int.cast_coe_nat], cases le_or_lt k n with hkn hnk, { rw int.coe_nat_sub hkn }, { have : ∏ i in finset.range k, (n - i : 𝕜) = 0, from finset.prod_eq_zero (finset.mem_range.2 hnk) (sub_self _), simp only [this, zero_mul] } end @[simp] lemma iter_deriv_pow' (n k : ℕ) : deriv^[k] (λ x : 𝕜, x ^ n) = λ x, (∏ i in finset.range k, (n - i)) * x ^ (n - k) := funext $ λ x, iter_deriv_pow n x k lemma iter_deriv_inv (k : ℕ) (x : 𝕜) : deriv^[k] has_inv.inv x = (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) := by simpa only [zpow_neg_one₀, int.cast_neg, int.cast_one] using iter_deriv_zpow (-1) x k @[simp] lemma iter_deriv_inv' (k : ℕ) : deriv^[k] has_inv.inv = λ x : 𝕜, (∏ i in finset.range k, (-1 - i)) * x ^ (-1 - k : ℤ) := funext (iter_deriv_inv k) end zpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in 𝓝[s \ {x}] x, (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (is_open.mem_nhds is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in 𝓝[s] x, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (is_open.mem_nhds is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : f' < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r := (hf.Ioi_of_Ici.limsup_slope_le' (lt_irrefl x) hr).frequently end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in 𝓝[s \ {x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (is_open.mem_nhds is_open_Iio hr), have B : ∀ᶠ z in 𝓝[{x}] x, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup] at C, filter_upwards [C.1], simp only [norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in 𝓝[s] x, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.Ioi_of_Ici.limsup_norm_slope_le hr).frequently /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ici x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.Ioi_of_Ici.limsup_slope_norm_le hr).frequently, refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
51c407bf6be9d62faeff33d50e2e6c6d5fc7d8af
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/star/basic.lean
23802f8886ae38912a540e4b4cf5347fbb6ce1f8
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
5,349
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.apply_fun import algebra.ordered_ring import algebra.big_operators.basic import data.equiv.ring /-! # Star monoids and star rings We introduce the basic algebraic notions of star monoids, and star rings. Star algebras are introduced in `algebra.algebra.star`. These are implemented as "mixin" typeclasses, so to summon a star ring (for example) one needs to write `(R : Type) [ring R] [star_ring R]`. This avoids difficulties with diamond inheritance. For now we simply do not introduce notations, as different users are expected to feel strongly about the relative merits of `r^*`, `r†`, `rᘁ`, and so on. Our star rings are actually star semirings, but of course we can prove `star_neg : star (-r) = - star r` when the underlying semiring is a ring. -/ universes u v /-- Notation typeclass (with no default notation!) for an algebraic structure with a star operation. -/ class has_star (R : Type u) := (star : R → R) variables {R : Type u} /-- A star operation (e.g. complex conjugate). -/ def star [has_star R] (r : R) : R := has_star.star r /-- Typeclass for a star operation with is involutive. -/ class has_involutive_star (R : Type u) extends has_star R := (star_involutive : function.involutive star) @[simp] lemma star_star [has_involutive_star R] (r : R) : star (star r) = r := has_involutive_star.star_involutive _ lemma star_injective [has_involutive_star R] : function.injective (star : R → R) := has_involutive_star.star_involutive.injective /-- A `*`-monoid is a monoid `R` with an involutive operations `star` so `star (r * s) = star s * star r`. -/ class star_monoid (R : Type u) [monoid R] extends has_involutive_star R := (star_mul : ∀ r s : R, star (r * s) = star s * star r) @[simp] lemma star_mul [monoid R] [star_monoid R] (r s : R) : star (r * s) = star s * star r := star_monoid.star_mul r s /-- `star` as an `mul_equiv` from `R` to `Rᵒᵖ` -/ @[simps apply] def star_mul_equiv [monoid R] [star_monoid R] : R ≃* Rᵒᵖ := { to_fun := λ x, opposite.op (star x), map_mul' := λ x y, (star_mul x y).symm ▸ (opposite.op_mul _ _), ..(has_involutive_star.star_involutive.to_equiv star).trans opposite.equiv_to_opposite} variables (R) @[simp] lemma star_one [monoid R] [star_monoid R] : star (1 : R) = 1 := begin have := congr_arg opposite.unop (star_mul_equiv : R ≃* Rᵒᵖ).map_one, rwa [star_mul_equiv_apply, opposite.unop_op, opposite.unop_one] at this, end variables {R} /-- A `*`-ring `R` is a (semi)ring with an involutive `star` operation which is additive which makes `R` with its multiplicative structure into a `*`-monoid (i.e. `star (r * s) = star s * star r`). -/ class star_ring (R : Type u) [semiring R] extends star_monoid R := (star_add : ∀ r s : R, star (r + s) = star r + star s) @[simp] lemma star_add [semiring R] [star_ring R] (r s : R) : star (r + s) = star r + star s := star_ring.star_add r s /-- `star` as an `add_equiv` -/ @[simps apply] def star_add_equiv [semiring R] [star_ring R] : R ≃+ R := { to_fun := star, map_add' := star_add, ..(has_involutive_star.star_involutive.to_equiv star)} variables (R) @[simp] lemma star_zero [semiring R] [star_ring R] : star (0 : R) = 0 := (star_add_equiv : R ≃+ R).map_zero variables {R} /-- `star` as an `ring_equiv` from `R` to `Rᵒᵖ` -/ @[simps apply] def star_ring_equiv [semiring R] [star_ring R] : R ≃+* Rᵒᵖ := { to_fun := λ x, opposite.op (star x), ..star_add_equiv.trans (opposite.op_add_equiv : R ≃+ Rᵒᵖ), ..star_mul_equiv} section open_locale big_operators @[simp] lemma star_sum [semiring R] [star_ring R] {α : Type*} (s : finset α) (f : α → R): star (∑ x in s, f x) = ∑ x in s, star (f x) := (star_add_equiv : R ≃+ R).map_sum _ _ end @[simp] lemma star_neg [ring R] [star_ring R] (r : R) : star (-r) = - star r := (star_add_equiv : R ≃+ R).map_neg _ @[simp] lemma star_sub [ring R] [star_ring R] (r s : R) : star (r - s) = star r - star s := (star_add_equiv : R ≃+ R).map_sub _ _ @[simp] lemma star_bit0 [ring R] [star_ring R] (r : R) : star (bit0 r) = bit0 (star r) := by simp [bit0] @[simp] lemma star_bit1 [ring R] [star_ring R] (r : R) : star (bit1 r) = bit1 (star r) := by simp [bit1] /-- Any commutative semiring admits the trivial `*`-structure. -/ def star_ring_of_comm {R : Type*} [comm_semiring R] : star_ring R := { star := id, star_involutive := λ x, by simp, star_mul := by simp [mul_comm], star_add := by simp, } section local attribute [instance] star_ring_of_comm @[simp] lemma star_id_of_comm {R : Type*} [comm_semiring R] {x : R} : star x = x := rfl end /-- An ordered `*`-ring is a ring which is both an ordered ring and a `*`-ring, and `0 ≤ star r * r` for every `r`. (In a Banach algebra, the natural ordering is given by the positive cone which is the closure of the sums of elements `star r * r`. This ordering makes the Banach algebra an ordered `*`-ring.) -/ class star_ordered_ring (R : Type u) [ordered_semiring R] extends star_ring R := (star_mul_self_nonneg : ∀ r : R, 0 ≤ star r * r) lemma star_mul_self_nonneg [ordered_semiring R] [star_ordered_ring R] {r : R} : 0 ≤ star r * r := star_ordered_ring.star_mul_self_nonneg r
9eedd798bf39a914dcb7dd2f33c0fef90e8b4e40
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/complex/polynomial.lean
ac65b124c24681012100e233e7429a29232ecb61
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
5,586
lean
/- Copyright (c) 2019 Chris Hughes All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import analysis.special_functions.pow import field_theory.algebraic_closure /-! # The fundamental theorem of algebra This file proves that every nonconstant complex polynomial has a root. As a consequence, the complex numbers are algebraically closed. -/ open complex polynomial metric filter is_absolute_value set open_locale classical namespace complex /- The following proof uses the method given at <https://ncatlab.org/nlab/show/fundamental+theorem+of+algebra#classical_fta_via_advanced_calculus> -/ /-- **Fundamental theorem of algebra**: every non constant complex polynomial has a root -/ lemma exists_root {f : polynomial ℂ} (hf : 0 < degree f) : ∃ z : ℂ, is_root f z := let ⟨z₀, hz₀⟩ := f.exists_forall_norm_le in exists.intro z₀ $ classical.by_contradiction $ λ hf0, have hfX : f - C (f.eval z₀) ≠ 0, from mt sub_eq_zero.1 (λ h, not_le_of_gt hf (h.symm ▸ degree_C_le)), let n := root_multiplicity z₀ (f - C (f.eval z₀)) in let g := (f - C (f.eval z₀)) /ₘ ((X - C z₀) ^ n) in have hg0 : g.eval z₀ ≠ 0, from eval_div_by_monic_pow_root_multiplicity_ne_zero _ hfX, have hg : g * (X - C z₀) ^ n = f - C (f.eval z₀), from div_by_monic_mul_pow_root_multiplicity_eq _ _, have hn0 : 0 < n, from nat.pos_of_ne_zero $ λ hn0, by simpa [g, hn0] using hg0, let ⟨δ', hδ'₁, hδ'₂⟩ := continuous_iff.1 (polynomial.continuous g) z₀ ((g.eval z₀).abs) (complex.abs_pos.2 hg0) in let δ := min (min (δ' / 2) 1) (((f.eval z₀).abs / (g.eval z₀).abs) / 2) in have hf0' : 0 < (f.eval z₀).abs, from complex.abs_pos.2 hf0, have hg0' : 0 < abs (eval z₀ g), from complex.abs_pos.2 hg0, have hfg0 : 0 < (f.eval z₀).abs / abs (eval z₀ g), from div_pos hf0' hg0', have hδ0 : 0 < δ, from lt_min (lt_min (half_pos hδ'₁) (by norm_num)) (half_pos hfg0), have hδ : ∀ z : ℂ, abs (z - z₀) = δ → abs (g.eval z - g.eval z₀) < (g.eval z₀).abs, from λ z hz, hδ'₂ z (by rw [complex.dist_eq, hz]; exact ((min_le_left _ _).trans (min_le_left _ _)).trans_lt (half_lt_self hδ'₁)), have hδ1 : δ ≤ 1, from le_trans (min_le_left _ _) (min_le_right _ _), let F : polynomial ℂ := C (f.eval z₀) + C (g.eval z₀) * (X - C z₀) ^ n in let z' := (-f.eval z₀ * (g.eval z₀).abs * δ ^ n / ((f.eval z₀).abs * g.eval z₀)) ^ (n⁻¹ : ℂ) + z₀ in have hF₁ : F.eval z' = f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs, by simp only [F, cpow_nat_inv_pow _ hn0, div_eq_mul_inv, eval_pow, mul_assoc, mul_comm (g.eval z₀), mul_left_comm (g.eval z₀), mul_left_comm (g.eval z₀)⁻¹, mul_inv', inv_mul_cancel hg0, eval_C, eval_add, eval_neg, sub_eq_add_neg, eval_mul, eval_X, add_neg_cancel_right, neg_mul_eq_neg_mul_symm, mul_one, div_eq_mul_inv]; simp only [mul_comm, mul_left_comm, mul_assoc], have hδs : (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs < 1, from (div_lt_one hf0').2 $ (lt_div_iff' hg0').1 $ calc δ ^ n ≤ δ ^ 1 : pow_le_pow_of_le_one (le_of_lt hδ0) hδ1 hn0 ... = δ : pow_one _ ... ≤ ((f.eval z₀).abs / (g.eval z₀).abs) / 2 : min_le_right _ _ ... < _ : half_lt_self (div_pos hf0' hg0'), have hF₂ : (F.eval z').abs = (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n, from calc (F.eval z').abs = (f.eval z₀ - f.eval z₀ * (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs).abs : congr_arg abs hF₁ ... = abs (f.eval z₀) * complex.abs (1 - (g.eval z₀).abs * δ ^ n / (f.eval z₀).abs : ℝ) : by rw [← complex.abs_mul]; exact congr_arg complex.abs (by simp [mul_add, add_mul, mul_assoc, div_eq_mul_inv, sub_eq_add_neg]) ... = _ : by rw [complex.abs_of_nonneg (sub_nonneg.2 (le_of_lt hδs)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt hf0')), mul_one], have hef0 : abs (eval z₀ g) * (eval z₀ f).abs ≠ 0, from mul_ne_zero (mt complex.abs_eq_zero.1 hg0) (mt complex.abs_eq_zero.1 hf0), have hz'z₀ : abs (z' - z₀) = δ, by simp [z', mul_assoc, mul_left_comm _ (_ ^ n), mul_comm _ (_ ^ n), mul_comm (eval z₀ f).abs, _root_.mul_div_cancel _ hef0, of_real_mul, neg_mul_eq_neg_mul_symm, neg_div, is_absolute_value.abv_pow complex.abs, complex.abs_of_nonneg (le_of_lt hδ0), real.pow_nat_rpow_nat_inv (le_of_lt hδ0) hn0], have hF₃ : (f.eval z' - F.eval z').abs < (g.eval z₀).abs * δ ^ n, from calc (f.eval z' - F.eval z').abs = (g.eval z' - g.eval z₀).abs * (z' - z₀).abs ^ n : by rw [← eq_sub_iff_add_eq.1 hg, ← is_absolute_value.abv_pow complex.abs, ← complex.abs_mul, sub_mul]; simp [F, eval_pow, eval_add, eval_mul, eval_sub, eval_C, eval_X, eval_neg, add_sub_cancel, sub_eq_add_neg, add_assoc] ... = (g.eval z' - g.eval z₀).abs * δ ^ n : by rw hz'z₀ ... < _ : (mul_lt_mul_right (pow_pos hδ0 _)).2 (hδ _ hz'z₀), lt_irrefl (f.eval z₀).abs $ calc (f.eval z₀).abs ≤ (f.eval z').abs : hz₀ _ ... = (F.eval z' + (f.eval z' - F.eval z')).abs : by simp ... ≤ (F.eval z').abs + (f.eval z' - F.eval z').abs : complex.abs_add _ _ ... < (f.eval z₀).abs - (g.eval z₀).abs * δ ^ n + (g.eval z₀).abs * δ ^ n : add_lt_add_of_le_of_lt (by rw hF₂) hF₃ ... = (f.eval z₀).abs : sub_add_cancel _ _ instance is_alg_closed : is_alg_closed ℂ := is_alg_closed.of_exists_root _ $ λ p _ hp, complex.exists_root $ degree_pos_of_irreducible hp end complex
9c69a49611594478f3c259d42c1f26573c6f4559
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/thursday/afternoon/category_theory/exercise2.lean
c179781435d40d674bed8ef3c11bb94a18c95181
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
3,775
lean
import algebra.category.CommRing.basic import data.polynomial /-! Let's show that taking polynomials over a ring is functor `Ring ⥤ Ring`. -/ noncomputable theory -- the default implementation of polynomials is noncomputable -- Just ignore this for now: it's a hack that prevents an annoying problem, -- and a cleaner fix is on its way to mathlib. local attribute [irreducible] polynomial.eval₂ /-! mathlib is undergoing a transition at the moment from using "unbundled" homomorphisms (e.g. we talk about a bare function `f : R → S`, along with a typeclass `[is_semiring_hom f]`) to using "bundled" homomorphisms (e.g. a structure `f : R →+* S`, which has a coercion to a bare function). The category `Ring` uses bundled homomorphisms (and in future all of mathlib will). However at present the polynomial library hasn't been updated. You may find the `ring_hom.of` useful -- this upgrades an unbundled homomorphism to a bundled homomorphism. -/ /-! Hints: * use `polynomial.map` -/ def Ring.polynomial : Ring ⥤ Ring := -- sorry { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } -- sorry def CommRing.polynomial : CommRing ⥤ CommRing := -- sorry { obj := λ R, CommRing.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), } -- sorry open category_theory def commutes : (forget₂ CommRing Ring) ⋙ Ring.polynomial ≅ CommRing.polynomial ⋙ (forget₂ CommRing Ring) := -- Hint: You can do this in two lines, ≤ 33 columns! -- sorry { hom := { app := λ R, 𝟙 _, }, inv := { app := λ R, 𝟙 _, }, }. -- sorry /-! There are some further hints in `src/hints/thursday/afternoon/category_theory/exercise2/` -/ /-! Bonus problem: Why did we set `local attribute [irreducible] polynomial.eval₂`? What goes wrong without it? Why? -/ -- omit local attribute [semireducible] polynomial.eval₂ def Ring.polynomial' : Ring ⥤ Ring := { obj := λ R, Ring.of (polynomial R), map := λ R S f, ring_hom.of (polynomial.map f), map_comp' := λ R S T f g, begin refl end, }. -- fails, but takes >5s seconds to do so! /-! What's going on? For some reason trying to solve the goal in `map_comp'` using `refl` takes a huge amount of time. This causes the automation which is responsible for automatically proving functoriality of functors to time out, and fail. How can `refl` take so long? Isn't it just checking if two things are the same? The problem is that when we work in type theory, in principle no definition is "opaque", and Lean sometimes has to unfold definitions in order to compare if two things are actually the same. Usually it's pretty conservative about this, and manages to avoid unfolding too deeply before coming up with an answer, but in bad cases it can get really bad. Somehow this is happening here! The solution we have available is to mark definitions as `[irreducible]`, which (almost, but not quite completely) prevents Lean from unfolding when checking definitional equality. Of course, this has a consequence --- Lean will sometimes fail to prove things by `refl` now! The solution to this is to provide a thorough API for our important definitions, so that after some point in the development one never needs to unfold the actual definition again, but one can work through theorems proved about the definition (e.g. characterisations and universal properties). An important example of this is that we have marked `real` as `[irreducible]` in Lean --- after you've got things working, no one should ever have to know whether the "actual definition" is in terms of Cauchy sequences or Dedekind cuts. Unfortunately at this point we don't use `[irreducible]` often enough in Lean, and improving this aspect of mathlib is an ongoin project. -/ -- omit
a95cfb805852a72022ba25d6860408abcba91e2e
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/exists_intro1.lean
eadef6ded94f25a05ecc009d0079d9613c5fadf1
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
673
lean
example : ∃ x : nat, x = x := Exists.intro 0 rfl example : ∃ x : nat, x = x := exists.intro 0 rfl lemma ex1 : ∃ x : nat, x = x := Exists.intro 0 rfl lemma ex2 : ∃ x : nat, x = x := exists.intro 0 rfl lemma ex3 : ∃ x y : nat, x = y := exists.intro 0 (exists.intro 0 rfl) lemma ex4 : ∃ x y : nat, x = y + 1 := exists.intro 1 (exists.intro 0 rfl) lemma ex5 : ∃ x y z : nat, x = y + z := exists.intro 1 (exists.intro 1 (exists.intro 0 rfl)) lemma ex6 : ∃ x : nat, x = x := ⟨0, rfl⟩ lemma ex7 : ∃ x y z : nat, x = y + z := ⟨1, 1, 0, rfl⟩ example : ∃ x : nat, x = x := ⟨0, rfl⟩ example : ∃ x y z : nat, x = y + z := ⟨1, 1, 0, rfl⟩
38c0cbecfa84152667baa6cfa868d9c5261bfdcf
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/algebra/ordered_group.lean
43f51d5c0a0d4d0c393e35ec4e56e9533e2deafa
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
32,084
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Partially ordered additive groups, modeled on Isabelle's library. These classes can be refined if necessary. -/ import logic.eq data.unit data.sigma data.prod import algebra.binary algebra.group algebra.order open eq eq.ops -- note: ⁻¹ will be overloaded variable {A : Type} /- partially ordered monoids, such as the natural numbers -/ structure ordered_cancel_comm_monoid [class] (A : Type) extends add_comm_monoid A, add_left_cancel_semigroup A, add_right_cancel_semigroup A, order_pair A := (add_le_add_left : ∀a b, le a b → ∀c, le (add c a) (add c b)) (le_of_add_le_add_left : ∀a b c, le (add a b) (add a c) → le b c) (add_lt_add_left : ∀a b, lt a b → ∀c, lt (add c a) (add c b)) (lt_of_add_lt_add_left : ∀a b c, lt (add a b) (add a c) → lt b c) section variables [s : ordered_cancel_comm_monoid A] variables {a b c d e : A} include s theorem add_lt_add_left (H : a < b) (c : A) : c + a < c + b := !ordered_cancel_comm_monoid.add_lt_add_left H c theorem add_lt_add_right (H : a < b) (c : A) : a + c < b + c := begin rewrite [add.comm, {b + _}add.comm], exact (add_lt_add_left H c) end theorem add_le_add_left (H : a ≤ b) (c : A) : c + a ≤ c + b := !ordered_cancel_comm_monoid.add_le_add_left H c theorem add_le_add_right (H : a ≤ b) (c : A) : a + c ≤ b + c := (add.comm c a) ▸ (add.comm c b) ▸ (add_le_add_left H c) theorem add_le_add (Hab : a ≤ b) (Hcd : c ≤ d) : a + c ≤ b + d := le.trans (add_le_add_right Hab c) (add_le_add_left Hcd b) theorem le_add_of_nonneg_right (H : b ≥ 0) : a ≤ a + b := begin have H1 : a + b ≥ a + 0, from add_le_add_left H a, rewrite add_zero at H1, exact H1 end theorem le_add_of_nonneg_left (H : b ≥ 0) : a ≤ b + a := begin have H1 : 0 + a ≤ b + a, from add_le_add_right H a, rewrite zero_add at H1, exact H1 end theorem add_lt_add (Hab : a < b) (Hcd : c < d) : a + c < b + d := lt.trans (add_lt_add_right Hab c) (add_lt_add_left Hcd b) theorem add_lt_add_of_le_of_lt (Hab : a ≤ b) (Hcd : c < d) : a + c < b + d := lt_of_le_of_lt (add_le_add_right Hab c) (add_lt_add_left Hcd b) theorem add_lt_add_of_lt_of_le (Hab : a < b) (Hcd : c ≤ d) : a + c < b + d := lt_of_lt_of_le (add_lt_add_right Hab c) (add_le_add_left Hcd b) theorem lt_add_of_pos_right (H : b > 0) : a < a + b := !add_zero ▸ add_lt_add_left H a theorem lt_add_of_pos_left (H : b > 0) : a < b + a := !zero_add ▸ add_lt_add_right H a -- here we start using le_of_add_le_add_left. theorem le_of_add_le_add_left (H : a + b ≤ a + c) : b ≤ c := !ordered_cancel_comm_monoid.le_of_add_le_add_left H theorem le_of_add_le_add_right (H : a + b ≤ c + b) : a ≤ c := le_of_add_le_add_left (show b + a ≤ b + c, begin rewrite [add.comm, {b + _}add.comm], exact H end) theorem lt_of_add_lt_add_left (H : a + b < a + c) : b < c := !ordered_cancel_comm_monoid.lt_of_add_lt_add_left H theorem lt_of_add_lt_add_right (H : a + b < c + b) : a < c := lt_of_add_lt_add_left ((add.comm a b) ▸ (add.comm c b) ▸ H) theorem add_le_add_left_iff (a b c : A) : a + b ≤ a + c ↔ b ≤ c := iff.intro le_of_add_le_add_left (assume H, add_le_add_left H _) theorem add_le_add_right_iff (a b c : A) : a + b ≤ c + b ↔ a ≤ c := iff.intro le_of_add_le_add_right (assume H, add_le_add_right H _) theorem add_lt_add_left_iff (a b c : A) : a + b < a + c ↔ b < c := iff.intro lt_of_add_lt_add_left (assume H, add_lt_add_left H _) theorem add_lt_add_right_iff (a b c : A) : a + b < c + b ↔ a < c := iff.intro lt_of_add_lt_add_right (assume H, add_lt_add_right H _) -- here we start using properties of zero. theorem add_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a + b := !zero_add ▸ (add_le_add Ha Hb) theorem add_pos (Ha : 0 < a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add Ha Hb) theorem add_pos_of_pos_of_nonneg (Ha : 0 < a) (Hb : 0 ≤ b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) theorem add_pos_of_nonneg_of_pos (Ha : 0 ≤ a) (Hb : 0 < b) : 0 < a + b := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) theorem add_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : a + b ≤ 0 := !zero_add ▸ (add_le_add Ha Hb) theorem add_neg (Ha : a < 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add Ha Hb) theorem add_neg_of_neg_of_nonpos (Ha : a < 0) (Hb : b ≤ 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_lt_of_le Ha Hb) theorem add_neg_of_nonpos_of_neg (Ha : a ≤ 0) (Hb : b < 0) : a + b < 0 := !zero_add ▸ (add_lt_add_of_le_of_lt Ha Hb) -- TODO: add nonpos version (will be easier with simplifier) theorem add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg (Ha : 0 ≤ a) (Hb : 0 ≤ b) : a + b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume Hab : a + b = 0, have Ha' : a ≤ 0, from calc a = a + 0 : by rewrite add_zero ... ≤ a + b : add_le_add_left Hb ... = 0 : Hab, have Haz : a = 0, from le.antisymm Ha' Ha, have Hb' : b ≤ 0, from calc b = 0 + b : by rewrite zero_add ... ≤ a + b : by exact add_le_add_right Ha _ ... = 0 : Hab, have Hbz : b = 0, from le.antisymm Hb' Hb, and.intro Haz Hbz) (assume Hab : a = 0 ∧ b = 0, obtain Ha' Hb', from Hab, by rewrite [Ha', Hb', add_zero]) theorem le_add_of_nonneg_of_le (Ha : 0 ≤ a) (Hbc : b ≤ c) : b ≤ a + c := !zero_add ▸ add_le_add Ha Hbc theorem le_add_of_le_of_nonneg (Hbc : b ≤ c) (Ha : 0 ≤ a) : b ≤ c + a := !add_zero ▸ add_le_add Hbc Ha theorem lt_add_of_pos_of_le (Ha : 0 < a) (Hbc : b ≤ c) : b < a + c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc theorem lt_add_of_le_of_pos (Hbc : b ≤ c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha theorem add_le_of_nonpos_of_le (Ha : a ≤ 0) (Hbc : b ≤ c) : a + b ≤ c := !zero_add ▸ add_le_add Ha Hbc theorem add_le_of_le_of_nonpos (Hbc : b ≤ c) (Ha : a ≤ 0) : b + a ≤ c := !add_zero ▸ add_le_add Hbc Ha theorem add_lt_of_neg_of_le (Ha : a < 0) (Hbc : b ≤ c) : a + b < c := !zero_add ▸ add_lt_add_of_lt_of_le Ha Hbc theorem add_lt_of_le_of_neg (Hbc : b ≤ c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add_of_le_of_lt Hbc Ha theorem lt_add_of_nonneg_of_lt (Ha : 0 ≤ a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc theorem lt_add_of_lt_of_nonneg (Hbc : b < c) (Ha : 0 ≤ a) : b < c + a := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha theorem lt_add_of_pos_of_lt (Ha : 0 < a) (Hbc : b < c) : b < a + c := !zero_add ▸ add_lt_add Ha Hbc theorem lt_add_of_lt_of_pos (Hbc : b < c) (Ha : 0 < a) : b < c + a := !add_zero ▸ add_lt_add Hbc Ha theorem add_lt_of_nonpos_of_lt (Ha : a ≤ 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add_of_le_of_lt Ha Hbc theorem add_lt_of_lt_of_nonpos (Hbc : b < c) (Ha : a ≤ 0) : b + a < c := !add_zero ▸ add_lt_add_of_lt_of_le Hbc Ha theorem add_lt_of_neg_of_lt (Ha : a < 0) (Hbc : b < c) : a + b < c := !zero_add ▸ add_lt_add Ha Hbc theorem add_lt_of_lt_of_neg (Hbc : b < c) (Ha : a < 0) : b + a < c := !add_zero ▸ add_lt_add Hbc Ha end /- partially ordered groups -/ structure ordered_comm_group [class] (A : Type) extends add_comm_group A, order_pair A := (add_le_add_left : ∀a b, le a b → ∀c, le (add c a) (add c b)) (add_lt_add_left : ∀a b, lt a b → ∀ c, lt (add c a) (add c b)) theorem ordered_comm_group.le_of_add_le_add_left [ordered_comm_group A] {a b c : A} (H : a + b ≤ a + c) : b ≤ c := assert H' : -a + (a + b) ≤ -a + (a + c), from ordered_comm_group.add_le_add_left _ _ H _, by rewrite *neg_add_cancel_left at H'; exact H' theorem ordered_comm_group.lt_of_add_lt_add_left [ordered_comm_group A] {a b c : A} (H : a + b < a + c) : b < c := assert H' : -a + (a + b) < -a + (a + c), from ordered_comm_group.add_lt_add_left _ _ H _, by rewrite *neg_add_cancel_left at H'; exact H' definition ordered_comm_group.to_ordered_cancel_comm_monoid [trans_instance] [reducible] [s : ordered_comm_group A] : ordered_cancel_comm_monoid A := ⦃ ordered_cancel_comm_monoid, s, add_left_cancel := @add.left_cancel A _, add_right_cancel := @add.right_cancel A _, le_of_add_le_add_left := @ordered_comm_group.le_of_add_le_add_left A _, lt_of_add_lt_add_left := @ordered_comm_group.lt_of_add_lt_add_left A _⦄ section variables [s : ordered_comm_group A] (a b c d e : A) include s theorem neg_le_neg {a b : A} (H : a ≤ b) : -b ≤ -a := have H1 : 0 ≤ -a + b, from !add.left_inv ▸ !(add_le_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_le_add_right H1 (-b) theorem le_of_neg_le_neg {a b : A} (H : -b ≤ -a) : a ≤ b := neg_neg a ▸ neg_neg b ▸ neg_le_neg H theorem neg_le_neg_iff_le : -a ≤ -b ↔ b ≤ a := iff.intro le_of_neg_le_neg neg_le_neg theorem nonneg_of_neg_nonpos {a : A} (H : -a ≤ 0) : 0 ≤ a := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) theorem neg_nonpos_of_nonneg {a : A} (H : 0 ≤ a) : -a ≤ 0 := neg_zero ▸ neg_le_neg H theorem neg_nonpos_iff_nonneg : -a ≤ 0 ↔ 0 ≤ a := iff.intro nonneg_of_neg_nonpos neg_nonpos_of_nonneg theorem nonpos_of_neg_nonneg {a : A} (H : 0 ≤ -a) : a ≤ 0 := le_of_neg_le_neg (neg_zero⁻¹ ▸ H) theorem neg_nonneg_of_nonpos {a : A} (H : a ≤ 0) : 0 ≤ -a := neg_zero ▸ neg_le_neg H theorem neg_nonneg_iff_nonpos : 0 ≤ -a ↔ a ≤ 0 := iff.intro nonpos_of_neg_nonneg neg_nonneg_of_nonpos theorem neg_lt_neg {a b : A} (H : a < b) : -b < -a := have H1 : 0 < -a + b, from !add.left_inv ▸ !(add_lt_add_left H), !add_neg_cancel_right ▸ !zero_add ▸ add_lt_add_right H1 (-b) theorem lt_of_neg_lt_neg {a b : A} (H : -b < -a) : a < b := neg_neg a ▸ neg_neg b ▸ neg_lt_neg H theorem neg_lt_neg_iff_lt : -a < -b ↔ b < a := iff.intro lt_of_neg_lt_neg neg_lt_neg theorem pos_of_neg_neg {a : A} (H : -a < 0) : 0 < a := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) theorem neg_neg_of_pos {a : A} (H : 0 < a) : -a < 0 := neg_zero ▸ neg_lt_neg H theorem neg_neg_iff_pos : -a < 0 ↔ 0 < a := iff.intro pos_of_neg_neg neg_neg_of_pos theorem neg_of_neg_pos {a : A} (H : 0 < -a) : a < 0 := lt_of_neg_lt_neg (neg_zero⁻¹ ▸ H) theorem neg_pos_of_neg {a : A} (H : a < 0) : 0 < -a := neg_zero ▸ neg_lt_neg H theorem neg_pos_iff_neg : 0 < -a ↔ a < 0 := iff.intro neg_of_neg_pos neg_pos_of_neg theorem le_neg_iff_le_neg : a ≤ -b ↔ b ≤ -a := !neg_neg ▸ !neg_le_neg_iff_le theorem le_neg_of_le_neg {a b : A} : a ≤ -b → b ≤ -a := iff.mp !le_neg_iff_le_neg theorem neg_le_iff_neg_le : -a ≤ b ↔ -b ≤ a := !neg_neg ▸ !neg_le_neg_iff_le theorem neg_le_of_neg_le {a b : A} : -a ≤ b → -b ≤ a := iff.mp !neg_le_iff_neg_le theorem lt_neg_iff_lt_neg : a < -b ↔ b < -a := !neg_neg ▸ !neg_lt_neg_iff_lt theorem lt_neg_of_lt_neg {a b : A} : a < -b → b < -a := iff.mp !lt_neg_iff_lt_neg theorem neg_lt_iff_neg_lt : -a < b ↔ -b < a := !neg_neg ▸ !neg_lt_neg_iff_lt theorem neg_lt_of_neg_lt {a b : A} : -a < b → -b < a := iff.mp !neg_lt_iff_neg_lt theorem sub_nonneg_iff_le : 0 ≤ a - b ↔ b ≤ a := !sub_self ▸ !add_le_add_right_iff theorem sub_nonneg_of_le {a b : A} : b ≤ a → 0 ≤ a - b := iff.mpr !sub_nonneg_iff_le theorem le_of_sub_nonneg {a b : A} : 0 ≤ a - b → b ≤ a := iff.mp !sub_nonneg_iff_le theorem sub_nonpos_iff_le : a - b ≤ 0 ↔ a ≤ b := !sub_self ▸ !add_le_add_right_iff theorem sub_nonpos_of_le {a b : A} : a ≤ b → a - b ≤ 0 := iff.mpr !sub_nonpos_iff_le theorem le_of_sub_nonpos {a b : A} : a - b ≤ 0 → a ≤ b := iff.mp !sub_nonpos_iff_le theorem sub_pos_iff_lt : 0 < a - b ↔ b < a := !sub_self ▸ !add_lt_add_right_iff theorem sub_pos_of_lt {a b : A} : b < a → 0 < a - b := iff.mpr !sub_pos_iff_lt theorem lt_of_sub_pos {a b : A} : 0 < a - b → b < a := iff.mp !sub_pos_iff_lt theorem sub_neg_iff_lt : a - b < 0 ↔ a < b := !sub_self ▸ !add_lt_add_right_iff theorem sub_neg_of_lt {a b : A} : a < b → a - b < 0 := iff.mpr !sub_neg_iff_lt theorem lt_of_sub_neg {a b : A} : a - b < 0 → a < b := iff.mp !sub_neg_iff_lt theorem add_le_iff_le_neg_add : a + b ≤ c ↔ b ≤ -a + c := have H: a + b ≤ c ↔ -a + (a + b) ≤ -a + c, from iff.symm (!add_le_add_left_iff), !neg_add_cancel_left ▸ H theorem add_le_of_le_neg_add {a b c : A} : b ≤ -a + c → a + b ≤ c := iff.mpr !add_le_iff_le_neg_add theorem le_neg_add_of_add_le {a b c : A} : a + b ≤ c → b ≤ -a + c := iff.mp !add_le_iff_le_neg_add theorem add_le_iff_le_sub_left : a + b ≤ c ↔ b ≤ c - a := by rewrite [sub_eq_add_neg, {c+_}add.comm]; apply add_le_iff_le_neg_add theorem add_le_of_le_sub_left {a b c : A} : b ≤ c - a → a + b ≤ c := iff.mpr !add_le_iff_le_sub_left theorem le_sub_left_of_add_le {a b c : A} : a + b ≤ c → b ≤ c - a := iff.mp !add_le_iff_le_sub_left theorem add_le_iff_le_sub_right : a + b ≤ c ↔ a ≤ c - b := have H: a + b ≤ c ↔ a + b - b ≤ c - b, from iff.symm (!add_le_add_right_iff), !add_neg_cancel_right ▸ H theorem add_le_of_le_sub_right {a b c : A} : a ≤ c - b → a + b ≤ c := iff.mpr !add_le_iff_le_sub_right theorem le_sub_right_of_add_le {a b c : A} : a + b ≤ c → a ≤ c - b := iff.mp !add_le_iff_le_sub_right theorem le_add_iff_neg_add_le : a ≤ b + c ↔ -b + a ≤ c := assert H: a ≤ b + c ↔ -b + a ≤ -b + (b + c), from iff.symm (!add_le_add_left_iff), by rewrite neg_add_cancel_left at H; exact H theorem le_add_of_neg_add_le {a b c : A} : -b + a ≤ c → a ≤ b + c := iff.mpr !le_add_iff_neg_add_le theorem neg_add_le_of_le_add {a b c : A} : a ≤ b + c → -b + a ≤ c := iff.mp !le_add_iff_neg_add_le theorem le_add_iff_sub_left_le : a ≤ b + c ↔ a - b ≤ c := by rewrite [sub_eq_add_neg, {a+_}add.comm]; apply le_add_iff_neg_add_le theorem le_add_of_sub_left_le {a b c : A} : a - b ≤ c → a ≤ b + c := iff.mpr !le_add_iff_sub_left_le theorem sub_left_le_of_le_add {a b c : A} : a ≤ b + c → a - b ≤ c := iff.mp !le_add_iff_sub_left_le theorem le_add_iff_sub_right_le : a ≤ b + c ↔ a - c ≤ b := assert H: a ≤ b + c ↔ a - c ≤ b + c - c, from iff.symm (!add_le_add_right_iff), by rewrite [sub_eq_add_neg (b+c) c at H, add_neg_cancel_right at H]; exact H theorem le_add_of_sub_right_le {a b c : A} : a - c ≤ b → a ≤ b + c := iff.mpr !le_add_iff_sub_right_le theorem sub_right_le_of_le_add {a b c : A} : a ≤ b + c → a - c ≤ b := iff.mp !le_add_iff_sub_right_le theorem le_add_iff_neg_add_le_left : a ≤ b + c ↔ -b + a ≤ c := assert H: a ≤ b + c ↔ -b + a ≤ -b + (b + c), from iff.symm (!add_le_add_left_iff), by rewrite neg_add_cancel_left at H; exact H theorem le_add_of_neg_add_le_left {a b c : A} : -b + a ≤ c → a ≤ b + c := iff.mpr !le_add_iff_neg_add_le_left theorem neg_add_le_left_of_le_add {a b c : A} : a ≤ b + c → -b + a ≤ c := iff.mp !le_add_iff_neg_add_le_left theorem le_add_iff_neg_add_le_right : a ≤ b + c ↔ -c + a ≤ b := by rewrite add.comm; apply le_add_iff_neg_add_le_left theorem le_add_of_neg_add_le_right {a b c : A} : -c + a ≤ b → a ≤ b + c := iff.mpr !le_add_iff_neg_add_le_right theorem neg_add_le_right_of_le_add {a b c : A} : a ≤ b + c → -c + a ≤ b := iff.mp !le_add_iff_neg_add_le_right theorem le_add_iff_neg_le_sub_left : c ≤ a + b ↔ -a ≤ b - c := assert H : c ≤ a + b ↔ -a + c ≤ b, from !le_add_iff_neg_add_le, assert H' : -a + c ≤ b ↔ -a ≤ b - c, from !add_le_iff_le_sub_right, iff.trans H H' theorem le_add_of_neg_le_sub_left {a b c : A} : -a ≤ b - c → c ≤ a + b := iff.mpr !le_add_iff_neg_le_sub_left theorem neg_le_sub_left_of_le_add {a b c : A} : c ≤ a + b → -a ≤ b - c := iff.mp !le_add_iff_neg_le_sub_left theorem le_add_iff_neg_le_sub_right : c ≤ a + b ↔ -b ≤ a - c := by rewrite add.comm; apply le_add_iff_neg_le_sub_left theorem le_add_of_neg_le_sub_right {a b c : A} : -b ≤ a - c → c ≤ a + b := iff.mpr !le_add_iff_neg_le_sub_right theorem neg_le_sub_right_of_le_add {a b c : A} : c ≤ a + b → -b ≤ a - c := iff.mp !le_add_iff_neg_le_sub_right theorem add_lt_iff_lt_neg_add_left : a + b < c ↔ b < -a + c := assert H: a + b < c ↔ -a + (a + b) < -a + c, from iff.symm (!add_lt_add_left_iff), begin rewrite neg_add_cancel_left at H, exact H end theorem add_lt_of_lt_neg_add_left {a b c : A} : b < -a + c → a + b < c := iff.mpr !add_lt_iff_lt_neg_add_left theorem lt_neg_add_left_of_add_lt {a b c : A} : a + b < c → b < -a + c := iff.mp !add_lt_iff_lt_neg_add_left theorem add_lt_iff_lt_neg_add_right : a + b < c ↔ a < -b + c := by rewrite add.comm; apply add_lt_iff_lt_neg_add_left theorem add_lt_of_lt_neg_add_right {a b c : A} : a < -b + c → a + b < c := iff.mpr !add_lt_iff_lt_neg_add_right theorem lt_neg_add_right_of_add_lt {a b c : A} : a + b < c → a < -b + c := iff.mp !add_lt_iff_lt_neg_add_right theorem add_lt_iff_lt_sub_left : a + b < c ↔ b < c - a := begin rewrite [sub_eq_add_neg, {c+_}add.comm], apply add_lt_iff_lt_neg_add_left end theorem add_lt_of_lt_sub_left {a b c : A} : b < c - a → a + b < c := iff.mpr !add_lt_iff_lt_sub_left theorem lt_sub_left_of_add_lt {a b c : A} : a + b < c → b < c - a := iff.mp !add_lt_iff_lt_sub_left theorem add_lt_iff_lt_sub_right : a + b < c ↔ a < c - b := assert H: a + b < c ↔ a + b - b < c - b, from iff.symm (!add_lt_add_right_iff), by rewrite [sub_eq_add_neg at H, add_neg_cancel_right at H]; exact H theorem add_lt_of_lt_sub_right {a b c : A} : a < c - b → a + b < c := iff.mpr !add_lt_iff_lt_sub_right theorem lt_sub_right_of_add_lt {a b c : A} : a + b < c → a < c - b := iff.mp !add_lt_iff_lt_sub_right theorem lt_add_iff_neg_add_lt_left : a < b + c ↔ -b + a < c := assert H: a < b + c ↔ -b + a < -b + (b + c), from iff.symm (!add_lt_add_left_iff), by rewrite neg_add_cancel_left at H; exact H theorem lt_add_of_neg_add_lt_left {a b c : A} : -b + a < c → a < b + c := iff.mpr !lt_add_iff_neg_add_lt_left theorem neg_add_lt_left_of_lt_add {a b c : A} : a < b + c → -b + a < c := iff.mp !lt_add_iff_neg_add_lt_left theorem lt_add_iff_neg_add_lt_right : a < b + c ↔ -c + a < b := by rewrite add.comm; apply lt_add_iff_neg_add_lt_left theorem lt_add_of_neg_add_lt_right {a b c : A} : -c + a < b → a < b + c := iff.mpr !lt_add_iff_neg_add_lt_right theorem neg_add_lt_right_of_lt_add {a b c : A} : a < b + c → -c + a < b := iff.mp !lt_add_iff_neg_add_lt_right theorem lt_add_iff_sub_lt_left : a < b + c ↔ a - b < c := by rewrite [sub_eq_add_neg, {a + _}add.comm]; apply lt_add_iff_neg_add_lt_left theorem lt_add_of_sub_lt_left {a b c : A} : a - b < c → a < b + c := iff.mpr !lt_add_iff_sub_lt_left theorem sub_lt_left_of_lt_add {a b c : A} : a < b + c → a - b < c := iff.mp !lt_add_iff_sub_lt_left theorem lt_add_iff_sub_lt_right : a < b + c ↔ a - c < b := by rewrite add.comm; apply lt_add_iff_sub_lt_left theorem lt_add_of_sub_lt_right {a b c : A} : a - c < b → a < b + c := iff.mpr !lt_add_iff_sub_lt_right theorem sub_lt_right_of_lt_add {a b c : A} : a < b + c → a - c < b := iff.mp !lt_add_iff_sub_lt_right theorem sub_lt_of_sub_lt {a b c : A} : a - b < c → a - c < b := begin intro H, apply sub_lt_left_of_lt_add, apply lt_add_of_sub_lt_right H end theorem sub_le_of_sub_le {a b c : A} : a - b ≤ c → a - c ≤ b := begin intro H, apply sub_left_le_of_le_add, apply le_add_of_sub_right_le H end -- TODO: the Isabelle library has varations on a + b ≤ b ↔ a ≤ 0 theorem le_iff_le_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a ≤ b ↔ c ≤ d := calc a ≤ b ↔ a - b ≤ 0 : iff.symm (sub_nonpos_iff_le a b) ... = (c - d ≤ 0) : by rewrite H ... ↔ c ≤ d : sub_nonpos_iff_le c d theorem lt_iff_lt_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a < b ↔ c < d := calc a < b ↔ a - b < 0 : iff.symm (sub_neg_iff_lt a b) ... = (c - d < 0) : by rewrite H ... ↔ c < d : sub_neg_iff_lt c d theorem sub_le_sub_left {a b : A} (H : a ≤ b) (c : A) : c - b ≤ c - a := add_le_add_left (neg_le_neg H) c theorem sub_le_sub_right {a b : A} (H : a ≤ b) (c : A) : a - c ≤ b - c := add_le_add_right H (-c) theorem sub_le_sub {a b c d : A} (Hab : a ≤ b) (Hcd : c ≤ d) : a - d ≤ b - c := add_le_add Hab (neg_le_neg Hcd) theorem sub_lt_sub_left {a b : A} (H : a < b) (c : A) : c - b < c - a := add_lt_add_left (neg_lt_neg H) c theorem sub_lt_sub_right {a b : A} (H : a < b) (c : A) : a - c < b - c := add_lt_add_right H (-c) theorem sub_lt_sub {a b c d : A} (Hab : a < b) (Hcd : c < d) : a - d < b - c := add_lt_add Hab (neg_lt_neg Hcd) theorem sub_lt_sub_of_le_of_lt {a b c d : A} (Hab : a ≤ b) (Hcd : c < d) : a - d < b - c := add_lt_add_of_le_of_lt Hab (neg_lt_neg Hcd) theorem sub_lt_sub_of_lt_of_le {a b c d : A} (Hab : a < b) (Hcd : c ≤ d) : a - d < b - c := add_lt_add_of_lt_of_le Hab (neg_le_neg Hcd) theorem sub_le_self (a : A) {b : A} (H : b ≥ 0) : a - b ≤ a := calc a - b = a + -b : rfl ... ≤ a + 0 : add_le_add_left (neg_nonpos_of_nonneg H) ... = a : by rewrite add_zero theorem sub_lt_self (a : A) {b : A} (H : b > 0) : a - b < a := calc a - b = a + -b : rfl ... < a + 0 : add_lt_add_left (neg_neg_of_pos H) ... = a : by rewrite add_zero theorem add_le_add_three {a b c d e f : A} (H1 : a ≤ d) (H2 : b ≤ e) (H3 : c ≤ f) : a + b + c ≤ d + e + f := begin apply le.trans, apply add_le_add, apply add_le_add, repeat assumption, apply le.refl end theorem sub_le_of_nonneg {b : A} (H : b ≥ 0) : a - b ≤ a := add_le_of_le_of_nonpos (le.refl a) (neg_nonpos_of_nonneg H) theorem sub_lt_of_pos {b : A} (H : b > 0) : a - b < a := add_lt_of_le_of_neg (le.refl a) (neg_neg_of_pos H) theorem neg_add_neg_le_neg_of_pos {a : A} (H : a > 0) : -a + -a ≤ -a := !neg_add ▸ neg_le_neg (le_add_of_nonneg_left (le_of_lt H)) end /- linear ordered group with decidable order -/ structure decidable_linear_ordered_comm_group [class] (A : Type) extends add_comm_group A, decidable_linear_order A := (add_le_add_left : ∀ a b, le a b → ∀ c, le (add c a) (add c b)) (add_lt_add_left : ∀ a b, lt a b → ∀ c, lt (add c a) (add c b)) definition decidable_linear_ordered_comm_group.to_ordered_comm_group [trans_instance] [reducible] (A : Type) [s : decidable_linear_ordered_comm_group A] : ordered_comm_group A := ⦃ ordered_comm_group, s, le_of_lt := @le_of_lt A _, lt_of_le_of_lt := @lt_of_le_of_lt A _, lt_of_lt_of_le := @lt_of_lt_of_le A _ ⦄ section variables [s : decidable_linear_ordered_comm_group A] variables {a b c d e : A} include s /- these can be generalized to a lattice ordered group -/ theorem min_add_add_left : min (a + b) (a + c) = a + min b c := eq.symm (eq_min (show a + min b c ≤ a + b, from add_le_add_left !min_le_left _) (show a + min b c ≤ a + c, from add_le_add_left !min_le_right _) (take d, assume H₁ : d ≤ a + b, assume H₂ : d ≤ a + c, have H : d - a ≤ min b c, from le_min (iff.mp !le_add_iff_sub_left_le H₁) (iff.mp !le_add_iff_sub_left_le H₂), show d ≤ a + min b c, from iff.mpr !le_add_iff_sub_left_le H)) theorem min_add_add_right : min (a + c) (b + c) = min a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply min_add_add_left theorem max_add_add_left : max (a + b) (a + c) = a + max b c := eq.symm (eq_max (add_le_add_left !le_max_left _) (add_le_add_left !le_max_right _) (λ d H₁ H₂, have H : max b c ≤ d - a, from max_le (iff.mp !add_le_iff_le_sub_left H₁) (iff.mp !add_le_iff_le_sub_left H₂), show a + max b c ≤ d, from iff.mpr !add_le_iff_le_sub_left H)) theorem max_add_add_right : max (a + c) (b + c) = max a b + c := by rewrite [add.comm a c, add.comm b c, add.comm _ c]; apply max_add_add_left theorem max_neg_neg : max (-a) (-b) = - min a b := eq.symm (eq_max (show -a ≤ -(min a b), from neg_le_neg !min_le_left) (show -b ≤ -(min a b), from neg_le_neg !min_le_right) (take d, assume H₁ : -a ≤ d, assume H₂ : -b ≤ d, have H : -d ≤ min a b, from le_min (!iff.mp !neg_le_iff_neg_le H₁) (!iff.mp !neg_le_iff_neg_le H₂), show -(min a b) ≤ d, from !iff.mp !neg_le_iff_neg_le H)) theorem min_eq_neg_max_neg_neg : min a b = - max (-a) (-b) := by rewrite [max_neg_neg, neg_neg] theorem min_neg_neg : min (-a) (-b) = - max a b := by rewrite [min_eq_neg_max_neg_neg, *neg_neg] theorem max_eq_neg_min_neg_neg : max a b = - min (-a) (-b) := by rewrite [min_neg_neg, neg_neg] /- absolute value -/ variables {a b c} definition abs (a : A) : A := max a (-a) theorem abs_of_nonneg (H : a ≥ 0) : abs a = a := have H' : -a ≤ a, from le.trans (neg_nonpos_of_nonneg H) H, max_eq_left H' theorem abs_of_pos (H : a > 0) : abs a = a := abs_of_nonneg (le_of_lt H) theorem abs_of_nonpos (H : a ≤ 0) : abs a = -a := have H' : a ≤ -a, from le.trans H (neg_nonneg_of_nonpos H), max_eq_right H' theorem abs_of_neg (H : a < 0) : abs a = -a := abs_of_nonpos (le_of_lt H) theorem abs_zero : abs 0 = (0:A) := abs_of_nonneg (le.refl _) theorem abs_neg (a : A) : abs (-a) = abs a := by rewrite [↑abs, max.comm, neg_neg] theorem abs_pos_of_pos (H : a > 0) : abs a > 0 := by rewrite (abs_of_pos H); exact H theorem abs_pos_of_neg (H : a < 0) : abs a > 0 := !abs_neg ▸ abs_pos_of_pos (neg_pos_of_neg H) theorem abs_sub (a b : A) : abs (a - b) = abs (b - a) := by rewrite [-neg_sub, abs_neg] theorem ne_zero_of_abs_ne_zero {a : A} (H : abs a ≠ 0) : a ≠ 0 := assume Ha, H (Ha⁻¹ ▸ abs_zero) /- these assume a linear order -/ theorem eq_zero_of_neg_eq (H : -a = a) : a = 0 := lt.by_cases (assume H1 : a < 0, have H2: a > 0, from H ▸ neg_pos_of_neg H1, absurd H1 (lt.asymm H2)) (assume H1 : a = 0, H1) (assume H1 : a > 0, have H2: a < 0, from H ▸ neg_neg_of_pos H1, absurd H1 (lt.asymm H2)) theorem abs_nonneg (a : A) : abs a ≥ 0 := or.elim (le.total 0 a) (assume H : 0 ≤ a, by rewrite (abs_of_nonneg H); exact H) (assume H : a ≤ 0, calc 0 ≤ -a : neg_nonneg_of_nonpos H ... = abs a : abs_of_nonpos H) theorem abs_abs (a : A) : abs (abs a) = abs a := abs_of_nonneg !abs_nonneg theorem le_abs_self (a : A) : a ≤ abs a := or.elim (le.total 0 a) (assume H : 0 ≤ a, abs_of_nonneg H ▸ !le.refl) (assume H : a ≤ 0, le.trans H !abs_nonneg) theorem neg_le_abs_self (a : A) : -a ≤ abs a := !abs_neg ▸ !le_abs_self theorem eq_zero_of_abs_eq_zero (H : abs a = 0) : a = 0 := have H1 : a ≤ 0, from H ▸ le_abs_self a, have H2 : -a ≤ 0, from H ▸ abs_neg a ▸ le_abs_self (-a), le.antisymm H1 (nonneg_of_neg_nonpos H2) theorem abs_eq_zero_iff_eq_zero (a : A) : abs a = 0 ↔ a = 0 := iff.intro eq_zero_of_abs_eq_zero (assume H, congr_arg abs H ⬝ !abs_zero) theorem eq_of_abs_sub_eq_zero {a b : A} (H : abs (a - b) = 0) : a = b := have a - b = 0, from eq_zero_of_abs_eq_zero H, show a = b, from eq_of_sub_eq_zero this theorem abs_pos_of_ne_zero (H : a ≠ 0) : abs a > 0 := or.elim (lt_or_gt_of_ne H) abs_pos_of_neg abs_pos_of_pos theorem abs.by_cases {P : A → Prop} {a : A} (H1 : P a) (H2 : P (-a)) : P (abs a) := or.elim (le.total 0 a) (assume H : 0 ≤ a, (abs_of_nonneg H)⁻¹ ▸ H1) (assume H : a ≤ 0, (abs_of_nonpos H)⁻¹ ▸ H2) theorem abs_le_of_le_of_neg_le (H1 : a ≤ b) (H2 : -a ≤ b) : abs a ≤ b := abs.by_cases H1 H2 theorem abs_lt_of_lt_of_neg_lt (H1 : a < b) (H2 : -a < b) : abs a < b := abs.by_cases H1 H2 -- the triangle inequality section private lemma aux1 {a b : A} (H1 : a + b ≥ 0) (H2 : a ≥ 0) : abs (a + b) ≤ abs a + abs b := decidable.by_cases (assume H3 : b ≥ 0, calc abs (a + b) ≤ abs (a + b) : le.refl ... = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... = abs a + abs b : by rewrite (abs_of_nonneg H3)) (assume H3 : ¬ b ≥ 0, assert H4 : b ≤ 0, from le_of_lt (lt_of_not_ge H3), calc abs (a + b) = a + b : by rewrite (abs_of_nonneg H1) ... = abs a + b : by rewrite (abs_of_nonneg H2) ... ≤ abs a + 0 : add_le_add_left H4 ... ≤ abs a + -b : add_le_add_left (neg_nonneg_of_nonpos H4) ... = abs a + abs b : by rewrite (abs_of_nonpos H4)) private lemma aux2 {a b : A} (H1 : a + b ≥ 0) : abs (a + b) ≤ abs a + abs b := or.elim (le.total b 0) (assume H2 : b ≤ 0, have H3 : ¬ a < 0, from assume H4 : a < 0, have H5 : a + b < 0, from !add_zero ▸ add_lt_add_of_lt_of_le H4 H2, not_lt_of_ge H1 H5, aux1 H1 (le_of_not_gt H3)) (assume H2 : 0 ≤ b, begin have H3 : abs (b + a) ≤ abs b + abs a, begin rewrite add.comm at H1, exact aux1 H1 H2 end, rewrite [add.comm, {abs a + _}add.comm], exact H3 end) theorem abs_add_le_abs_add_abs (a b : A) : abs (a + b) ≤ abs a + abs b := or.elim (le.total 0 (a + b)) (assume H2 : 0 ≤ a + b, aux2 H2) (assume H2 : a + b ≤ 0, assert H3 : -a + -b = -(a + b), by rewrite neg_add, assert H4 : -(a + b) ≥ 0, from iff.mpr (neg_nonneg_iff_nonpos (a+b)) H2, have H5 : -a + -b ≥ 0, begin rewrite -H3 at H4, exact H4 end, calc abs (a + b) = abs (-a + -b) : by rewrite [-abs_neg, neg_add] ... ≤ abs (-a) + abs (-b) : aux2 H5 ... = abs a + abs b : by rewrite *abs_neg) theorem abs_sub_abs_le_abs_sub (a b : A) : abs a - abs b ≤ abs (a - b) := have H1 : abs a - abs b + abs b ≤ abs (a - b) + abs b, from calc abs a - abs b + abs b = abs a : by rewrite sub_add_cancel ... = abs (a - b + b) : by rewrite sub_add_cancel ... ≤ abs (a - b) + abs b : abs_add_le_abs_add_abs, le_of_add_le_add_right H1 theorem abs_sub_le (a b c : A) : abs (a - c) ≤ abs (a - b) + abs (b - c) := calc abs (a - c) = abs (a - b + (b - c)) : by rewrite [*sub_eq_add_neg, add.assoc, neg_add_cancel_left] ... ≤ abs (a - b) + abs (b - c) : abs_add_le_abs_add_abs theorem abs_add_three (a b c : A) : abs (a + b + c) ≤ abs a + abs b + abs c := begin apply le.trans, apply abs_add_le_abs_add_abs, apply le.trans, apply add_le_add_right, apply abs_add_le_abs_add_abs, apply le.refl end theorem dist_bdd_within_interval {a b lb ub : A} (H : lb < ub) (Hal : lb ≤ a) (Hau : a ≤ ub) (Hbl : lb ≤ b) (Hbu : b ≤ ub) : abs (a - b) ≤ ub - lb := begin cases (decidable.em (b ≤ a)) with [Hba, Hba], rewrite (abs_of_nonneg (iff.mpr !sub_nonneg_iff_le Hba)), apply sub_le_sub, apply Hau, apply Hbl, rewrite [abs_of_neg (iff.mpr !sub_neg_iff_lt (lt_of_not_ge Hba)), neg_sub], apply sub_le_sub, apply Hbu, apply Hal end end end