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
eda2a14d42ce1fd8988278bcd80adede1b073cba
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/data/set/basic.lean
72cf0873516dab32ebd4db136a742b1ad56241cc
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
73,522
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 -/ import tactic.basic import tactic.finish import data.subtype import logic.unique import data.prod import logic.function.basic /-! # Basic properties of sets Sets in Lean are homogeneous; all their elements have the same type. Sets whose elements have type `X` are thus defined as `set X := X → Prop`. Note that this function need not be decidable. The definition is in the core library. This file provides some basic definitions related to sets and functions not present in the core library, as well as extra lemmas for functions in the core library (empty set, univ, union, intersection, insert, singleton, set-theoretic difference, complement, and powerset). Note that a set is a term, not a type. There is a coersion from `set α` to `Type*` sending `s` to the corresponding subtype `↥s`. See also the file `set_theory/zfc.lean`, which contains an encoding of ZFC set theory in Lean. ## Main definitions Notation used here: - `f : α → β` is a function, - `s : set α` and `s₁ s₂ : set α` are subsets of `α` - `t : set β` is a subset of `β`. Definitions in the file: * `strict_subset s₁ s₂ : Prop` : the predicate `s₁ ⊆ s₂` but `s₁ ≠ s₂`. * `nonempty s : Prop` : the predicate `s ≠ ∅`. Note that this is the preferred way to express the fact that `s` has an element (see the Implementation Notes). * `preimage f t : set α` : the preimage f⁻¹(t) (written `f ⁻¹' t` in Lean) of a subset of β. * `subsingleton s : Prop` : the predicate saying that `s` has at most one element. * `range f : set β` : the image of `univ` under `f`. Also works for `{p : Prop} (f : p → α)` (unlike `image`) * `prod s t : set (α × β)` : the subset `s × t`. * `inclusion s₁ s₂ : ↥s₁ → ↥s₂` : the map `↥s₁ → ↥s₂` induced by an inclusion `s₁ ⊆ s₂`. ## Notation * `f ⁻¹' t` for `preimage f t` * `f '' s` for `image f s` * `sᶜ` for the complement of `s` ## Implementation notes * `s.nonempty` is to be preferred to `s ≠ ∅` or `∃ x, x ∈ s`. It has the advantage that the `s.nonempty` dot notation can be used. * For `s : set α`, do not use `subtype s`. Instead use `↥s` or `(s : Type*)` or `s`. ## Tags set, sets, subset, subsets, image, preimage, pre-image, range, union, intersection, insert, singleton, complement, powerset -/ /-! ### Set coercion to a type -/ open function universe variables u v w x /-- Set / lattice complement -/ class has_compl (α : Type*) := (compl : α → α) export has_compl (compl) postfix `ᶜ`:(max+1) := compl run_cmd do e ← tactic.get_env, tactic.set_env $ e.mk_protected `set.compl instance {α : Type*} : has_compl (set α) := ⟨set.compl⟩ namespace set /-- Coercion from a set to the corresponding subtype. -/ instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists theorem set_coe.exists' {s : set α} {p : Π x, x ∈ s → Prop} : (∃ x (h : x ∈ s), p x h) ↔ (∃ x : s, p x.1 x.2) := (@set_coe.exists _ _ $ λ x, p x.1 x.2).symm @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe /-- See also `subtype.prop` -/ lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.prop namespace set variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff {s t : set α} : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem set_of_set {s : set α} : set_of s = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl /-! ### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id theorem subset.rfl {s : set α} : s ⊆ s := subset.refl s @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alternative name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp [subset_def, classical.not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ ¬ (t ⊆ s) instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := classical.by_cases (λ H : t ⊆ s, or.inl $ subset.antisymm h H) (λ H, or.inr ⟨h, H⟩) lemma exists_of_ssubset {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} lemma ssubset_iff_of_subset {s t : set α} (h : s ⊆ t) : s ⊂ t ↔ ∃ x ∈ t, x ∉ s := ⟨exists_of_ssubset, λ ⟨x, hxt, hxs⟩, ⟨h, λ h, hxs $ h hxt⟩⟩ theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem : ¬ (a ∉ s) ↔ a ∈ s := by { classical, exact not_not } /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.not_subset_empty : s.nonempty → ¬(s ⊆ ∅) | ⟨x, hx⟩ hs := hs hx theorem nonempty.ne_empty : s.nonempty → s ≠ ∅ | ⟨x, hx⟩ hs := by { rw hs at hx, exact hx } /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.mono (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := let ⟨x, xt, xs⟩ := exists_of_ssubset ht in ⟨x, xt, xs⟩ lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty_of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ @[simp] lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ lemma nonempty.to_subtype (h : s.nonempty) : nonempty s := nonempty_subtype.2 h /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 lemma not_nonempty_iff_eq_empty {s : set α} : ¬s.nonempty ↔ s = ∅ := by simp only [set.nonempty, eq_empty_iff_forall_not_mem, not_exists] lemma empty_not_nonempty : ¬(∅ : set α).nonempty := not_nonempty_iff_eq_empty.2 rfl lemma eq_empty_or_nonempty (s : set α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inr (λ h, or.inl $ not_nonempty_iff_eq_empty.1 h) theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := (not_congr not_nonempty_iff_eq_empty.symm).trans classical.not_not theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : nonempty α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 lemma eq_univ_of_subset {s t : set α} (h : s ⊆ t) (hs : s = univ) : t = univ := eq_univ_of_univ_subset $ hs ▸ h @[simp] lemma univ_eq_empty_iff : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /-- `diagonal α` is the subset of `α × α` consisting of all pairs of the form `(a, a)`. -/ def diagonal (α : Type*) : set (α × α) := {p | p.1 = p.2} @[simp] lemma mem_diagonal {α : Type*} (x : α) : (x, x) ∈ diagonal α := by simp [diagonal] /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] lemma inter_compl_nonempty_iff {s t : set α} : (s ∩ tᶜ).nonempty ↔ ¬ s ⊆ t := begin split, { rintros ⟨x ,xs, xt⟩ sub, exact xt (sub xs) }, { intros h, rcases not_subset.mp h with ⟨x, xs, xt⟩, exact ⟨x, xs, xt⟩ } end theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_iff_insert {s t : set α} : s ⊂ t ↔ ∃ a ∉ s, insert a s ⊆ t := begin simp only [insert_subset, exists_and_distrib_right, ssubset_def, not_subset], simp only [exists_prop, and_comm] end theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff_insert.2 ⟨a, h, subset.refl _⟩ theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem bex_insert_iff {P : α → Prop} {a : α} {s : set α} : (∃ x ∈ insert a s, P x) ↔ (∃ x ∈ s, P x) ∨ P a := by finish [iff_def] theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := (insert_emptyc_eq _).symm @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := iff.rfl @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := set.ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := ⟨a, rfl⟩ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem singleton_union : {a} ∪ s = insert a s := rfl @[simp] theorem union_singleton : s ∪ {a} = insert a s := by rw [union_comm, singleton_union] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ s.nonempty := by rw [mem_singleton_iff, ← ne.def, ne_empty_iff_nonempty] instance unique_singleton (a : α) : unique ↥({a} : set α) := { default := ⟨a, mem_singleton a⟩, uniq := begin intros x, apply subtype.ext, apply eq_of_mem_singleton (subtype.mem x), end} /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem sep_mem_eq {s t : set α} : {x ∈ s | x ∈ t} = s ∩ t := rfl @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ sᶜ := h lemma compl_set_of {α} (p : α → Prop) : {a | p a}ᶜ = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ sᶜ) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ sᶜ = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ sᶜ ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ sᶜ = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : sᶜ ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : (∅ : set α)ᶜ = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : (s ∪ t)ᶜ = sᶜ ∩ tᶜ := by finish [ext_iff] local attribute [simp] -- Will be generalized to lattices in `compl_compl'` theorem compl_compl (s : set α) : sᶜᶜ = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : (s ∩ t)ᶜ = sᶜ ∪ tᶜ := by finish [ext_iff] @[simp] theorem compl_univ : (univ : set α)ᶜ = ∅ := by finish [ext_iff] lemma compl_empty_iff {s : set α} : sᶜ = ∅ ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set α} : sᶜ = univ ↔ s = ∅ := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set α} : sᶜ.nonempty ↔ s ≠ univ := ne_empty_iff_nonempty.symm.trans $ not_congr $ compl_empty_iff lemma mem_compl_singleton_iff {a x : α} : x ∈ ({a} : set α)ᶜ ↔ x ≠ a := not_iff_not_of_iff mem_singleton_iff lemma compl_singleton_eq (a : α) : ({a} : set α)ᶜ = {x | x ≠ a} := ext $ λ x, mem_compl_singleton_iff theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = (sᶜ ∩ tᶜ)ᶜ := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = (sᶜ ∪ tᶜ)ᶜ := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ sᶜ = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : sᶜ ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : sᶜ ⊆ t ↔ tᶜ ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : sᶜ ⊆ tᶜ ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : sᶜ ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ tᶜ ↔ t ⊆ sᶜ := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ tᶜ ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff lemma subset_compl_singleton_iff {a : α} {s : set α} : s ⊆ {a}ᶜ ↔ a ∉ s := by { rw subset_compl_comm, simp } theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ bᶜ ∪ c := begin classical, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ tᶜ := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := ⟨λ ⟨x, xs, xt⟩, not_subset.2 ⟨x, xs, xt⟩, λ h, let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩⟩ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := set.ext $ λ _, and_or_distrib_left theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := set.ext $ λ _, and_or_distrib_right theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := set.ext $ λ _, or_and_distrib_left theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := set.ext $ λ _, or_and_distrib_right theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : sᶜ = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff (s : set α) : (∅ \ s : set α) = ∅ := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_diff_union (s t : set α) : s ⊆ (s \ t) ∪ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_diff_singleton {x : α} {s t : set α} (h : s ⊆ t) (hx : x ∉ s) : s ⊆ t \ {x} := subset_inter h $ subset_compl_comm.1 $ singleton_subset_iff.2 hx lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] lemma diff_inter {s t u : set α} : s \ (t ∩ u) = (s \ t) ∪ (s \ u) := ext $ λ x, by simp [classical.not_and_distrib, and_or_distrib_left] lemma diff_inter_diff {s t u : set α} : s \ t ∩ (s \ u) = s \ (t ∪ u) := by { ext x, simp only [mem_inter_eq, mem_union_eq, mem_diff, not_or_distrib], exact ⟨λ ⟨⟨h1, h2⟩, _, h3⟩, ⟨h1, h2, h3⟩, λ ⟨h1, h2, h3⟩, ⟨⟨h1, h2⟩, h1, h3⟩⟩ } lemma diff_compl : s \ tᶜ = s ∩ t := by rw [diff_eq, compl_compl] lemma diff_diff_right {s t u : set α} : s \ (t \ u) = (s \ t) ∪ (s ∩ u) := by rw [diff_eq t u, diff_inter, diff_compl] @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp lemma diff_diff_cancel_left {s t : set α} (h : s ⊆ t) : t \ (t \ s) = s := by simp only [diff_diff_right, diff_self, inter_eq_self_of_subset_right h, empty_union] lemma mem_diff_singleton {x y : α} {s : set α} : x ∈ s \ {y} ↔ (x ∈ s ∧ x ≠ y) := iff.rfl lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ s.nonempty) := mem_diff_singleton.trans $ and_congr iff.rfl ne_empty_iff_nonempty /-! ### Powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /-! ### Inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' sᶜ = (f ⁻¹' s)ᶜ := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl @[simp] theorem preimage_id' {s : set α} : (λ x, x) ⁻¹' s = s := rfl theorem preimage_const_of_mem {b : β} {s : set β} (h : b ∈ s) : (λ (x : α), b) ⁻¹' s = univ := eq_univ_of_forall $ λ x, h theorem preimage_const_of_not_mem {b : β} {s : set β} (h : b ∉ s) : (λ (x : α), b) ⁻¹' s = ∅ := eq_empty_of_subset_empty $ λ x hx, h hx theorem preimage_const (b : β) (s : set β) [decidable (b ∈ s)] : (λ (x : α), b) ⁻¹' s = if b ∈ s then univ else ∅ := by { split_ifs with hb hb, exacts [preimage_const_of_mem hb, preimage_const_of_not_mem hb] } theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl lemma preimage_preimage {g : β → γ} {f : α → β} {s : set γ} : f ⁻¹' (g ⁻¹' s) = (λ x, g (f x)) ⁻¹' s := preimage_comp.symm theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ lemma if_preimage (s : set α) [decidable_pred s] (f g : α → β) (t : set β) : (λa, if a ∈ s then f a else g a)⁻¹' t = (s ∩ f ⁻¹' t) ∪ (sᶜ ∩ g ⁻¹' t) := begin ext, simp only [mem_inter_eq, mem_union_eq, mem_preimage], split_ifs; simp [mem_def, h] end lemma preimage_coe_coe_diagonal {α : Type*} (s : set α) : (prod.map coe coe) ⁻¹' (diagonal α) = diagonal s := begin ext ⟨⟨x, x_in⟩, ⟨y, y_in⟩⟩, simp [set.diagonal], end end preimage /-! ### Image of a set under a function -/ section image infix ` '' `:80 := image -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem bex_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∃ y ∈ f '' s, p y) ↔ (∃ x ∈ s, p (f x)) := by simp theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /-- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm /-- Image is monotone with respect to `⊆`. See `set.monotone_image` for the statement in terms of `≤`. -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp lemma image_inter_subset (f : α → β) (s t : set α) : f '' (s ∩ t) ⊆ f '' s ∩ f '' t := subset_inter (image_subset _ $ inter_subset_left _ _) (image_subset _ $ inter_subset_right _ _) theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (image_inter_subset _ _ _) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_nonempty {s : set α} {a : α} : (s ∩ {a}).nonempty ↔ a ∈ s := by finish [set.nonempty] -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ tᶜ ∈ S := begin suffices : ∀ x, xᶜ = t ↔ tᶜ = x, {simp [this]}, intro x, split; { intro e, subst e, simp } end /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := ext $ by simp theorem image_id (s : set α) : id '' s = s := by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_pair (f : α → β) (a b : α) : f '' {a, b} = {f a, f b} := by simp only [image_insert_eq, image_singleton] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' sᶜ ⊆ (f '' s)ᶜ := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : (f '' s)ᶜ ⊆ f '' sᶜ := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' sᶜ = (f '' s)ᶜ := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) theorem subset_image_diff (f : α → β) (s t : set α) : f '' s \ f '' t ⊆ f '' (s \ t) := begin rw [diff_subset_iff, ← image_union, union_diff_self], exact image_subset f (subset_union_right t s) end theorem image_diff {f : α → β} (hf : injective f) (s t : set α) : f '' (s \ t) = f '' s \ f '' t := subset.antisymm (subset.trans (image_inter_subset _ _ _) $ inter_subset_inter_right _ $ image_compl_subset hf) (subset_image_diff f s t) lemma nonempty.image (f : α → β) {s : set α} : s.nonempty → (f '' s).nonempty | ⟨x, hx⟩ := ⟨f x, mem_image_of_mem f hx⟩ lemma nonempty.of_image {f : α → β} {s : set α} : (f '' s).nonempty → s.nonempty | ⟨y, x, hx, _⟩ := ⟨x, hx⟩ @[simp] lemma nonempty_image_iff {f : α → β} {s : set α} : (f '' s).nonempty ↔ s.nonempty := ⟨nonempty.of_image, λ h, h.image f⟩ /-- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) protected lemma push_pull (f : α → β) (s : set α) (t : set β) : f '' (s ∩ f ⁻¹' t) = f '' s ∩ t := begin apply subset.antisymm, { calc f '' (s ∩ f ⁻¹' t) ⊆ f '' s ∩ (f '' (f⁻¹' t)) : image_inter_subset _ _ _ ... ⊆ f '' s ∩ t : inter_subset_inter_right _ (image_preimage_subset f t) }, { rintros _ ⟨⟨x, h', rfl⟩, h⟩, exact ⟨x, ⟨h', h⟩, rfl⟩ } end protected lemma push_pull' (f : α → β) (s : set α) (t : set β) : f '' (f ⁻¹' t ∩ s) = t ∩ f '' s := by simp only [inter_comm, set.push_pull] theorem compl_image : image (compl : set α → set α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {p : set α → Prop} : compl '' {s | p s} = {s | p sᶜ} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image /-! ### Subsingleton -/ /-- A set `s` is a `subsingleton`, if it has at most one element. -/ protected def subsingleton (s : set α) : Prop := ∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y lemma subsingleton.mono (ht : t.subsingleton) (hst : s ⊆ t) : s.subsingleton := λ x hx y hy, ht (hst hx) (hst hy) lemma subsingleton.image (hs : s.subsingleton) (f : α → β) : (f '' s).subsingleton := λ _ ⟨x, hx, Hx⟩ _ ⟨y, hy, Hy⟩, Hx ▸ Hy ▸ congr_arg f (hs hx hy) lemma subsingleton.eq_singleton_of_mem (hs : s.subsingleton) {x:α} (hx : x ∈ s) : s = {x} := ext $ λ y, ⟨λ hy, (hs hx hy) ▸ mem_singleton _, λ hy, (eq_of_mem_singleton hy).symm ▸ hx⟩ lemma subsingleton_empty : (∅ : set α).subsingleton := λ x, false.elim lemma subsingleton_singleton {a} : ({a} : set α).subsingleton := λ x hx y hy, (eq_of_mem_singleton hx).symm ▸ (eq_of_mem_singleton hy).symm ▸ rfl lemma subsingleton.eq_empty_or_singleton (hs : s.subsingleton) : s = ∅ ∨ ∃ x, s = {x} := s.eq_empty_or_nonempty.elim or.inl (λ ⟨x, hx⟩, or.inr ⟨x, hs.eq_singleton_of_mem hx⟩) lemma subsingleton_univ [subsingleton α] : (univ : set α).subsingleton := λ x hx y hy, subsingleton.elim x y theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl @[simp] theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := by simp lemma exists_range_iff' {p : α → Prop} : (∃ a, a ∈ range f ∧ p a) ↔ ∃ i, p (f i) := by simpa only [exists_prop] using exists_range_iff theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id theorem range_inl_union_range_inr : range (@sum.inl α β) ∪ range sum.inr = univ := ext $ λ x, by cases x; simp @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := range_iff_surjective.2 quot.exists_rep @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {s : set α} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_nonempty_iff_nonempty : (range f).nonempty ↔ nonempty ι := ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_nonempty [h : nonempty ι] (f : ι → α) : (range f).nonempty := range_nonempty_iff_nonempty.2 h @[simp] lemma range_eq_empty {f : ι → α} : range f = ∅ ↔ ¬ nonempty ι := not_nonempty_iff_eq_empty.symm.trans $ not_congr range_nonempty_iff_nonempty theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end @[simp] theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ @[simp] theorem preimage_range_inter {f : α → β} {s : set β} : f ⁻¹' (range f ∩ s) = f ⁻¹' s := by rw [inter_comm, preimage_inter_range] theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x lemma diagonal_eq_range {α : Type*} : diagonal α = range (λ x, (x, x)) := by { ext ⟨x, y⟩, simp [diagonal, eq_comm] } theorem preimage_singleton_nonempty {f : α → β} {y : β} : (f ⁻¹' {y}).nonempty ↔ y ∈ range f := iff.rfl theorem preimage_singleton_eq_empty {f : α → β} {y : β} : f ⁻¹' {y} = ∅ ↔ y ∉ range f := not_nonempty_iff_eq_empty.symm.trans $ not_congr preimage_singleton_nonempty /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end @[simp] lemma preimage_range (f : α → β) : f ⁻¹' (range f) = univ := eq_univ_of_forall mem_range_self end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set open set namespace function variables {ι : Sort*} {α : Type*} {β : Type*} {f : α → β} lemma surjective.preimage_injective (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 lemma injective.preimage_surjective (hf : injective f) : surjective (preimage f) := by { intro s, use f '' s, rw preimage_image_eq _ hf } lemma surjective.image_surjective (hf : surjective f) : surjective (image f) := by { intro s, use f ⁻¹' s, rw image_preimage_eq hf } lemma injective.image_injective (hf : injective f) : injective (image f) := by { intros s t h, rw [←preimage_image_eq s hf, ←preimage_image_eq t hf, h] } lemma surjective.range_eq {f : ι → α} (hf : surjective f) : range f = univ := range_iff_surjective.2 hf lemma surjective.range_comp (g : α → β) {f : ι → α} (hf : surjective f) : range (g ∘ f) = range g := by rw [range_comp, hf.range_eq, image_univ] lemma injective.nonempty_apply_iff {f : set α → set β} (hf : injective f) (h2 : f ∅ = ∅) {s : set α} : (f s).nonempty ↔ s.nonempty := by rw [← ne_empty_iff_nonempty, ← h2, ← ne_empty_iff_nonempty, hf.ne_iff] end function open function /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma coe_image {p : α → Prop} {s : set (subtype p)} : coe '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ lemma range_coe {s : set α} : range (coe : s → α) = s := by { rw ← set.image_univ, simp [-set.image_univ, coe_image] } /-- A variant of `range_coe`. Try to use `range_coe` if possible. This version is useful when defining a new type that is defined as the subtype of something. In that case, the coercion doesn't fire anymore. -/ lemma range_val {s : set α} : range (subtype.val : s → α) = s := range_coe /-- We make this the simp lemma instead of `range_coe`. The reason is that if we write for `s : set α` the function `coe : s → α`, then the inferred implicit arguments of `coe` are `coe α (λ x, x ∈ s)`. -/ @[simp] lemma range_coe_subtype {p : α → Prop} : range (coe : subtype p → α) = {x | p x} := range_coe lemma range_val_subtype {p : α → Prop} : range (subtype.val : subtype p → α) = {x | p x} := range_coe theorem coe_image_subset (s : set α) (t : set s) : t.image coe ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem coe_image_univ (s : set α) : (coe : s → α) '' set.univ = s := image_univ.trans range_coe @[simp] theorem image_preimage_coe (s t : set α) : (coe : s → α) '' (coe ⁻¹' t) = t ∩ s := image_preimage_eq_inter_range.trans $ congr_arg _ range_coe theorem image_preimage_val (s t : set α) : (subtype.val : s → α) '' (subtype.val ⁻¹' t) = t ∩ s := image_preimage_coe s t theorem preimage_coe_eq_preimage_coe_iff {s t u : set α} : ((coe : s → α) ⁻¹' t = coe ⁻¹' u) ↔ t ∩ s = u ∩ s := begin rw [←image_preimage_coe, ←image_preimage_coe], split, { intro h, rw h }, intro h, exact coe_injective.image_injective h end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((subtype.val : s → α) ⁻¹' t = subtype.val ⁻¹' u) ↔ (t ∩ s = u ∩ s) := preimage_coe_eq_preimage_coe_iff lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (coe '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨coe '' s, _, hs⟩, convert image_subset_range _ _, rw [range_coe] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨coe ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_coe], exact hs₁ end end subtype namespace set /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ lemma prod_subset_iff {P : set (α × β)} : (set.prod s t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h _ pin, by { cases mem_prod.1 pin with hs ht, simpa using h _ hs _ ht }⟩ @[simp] theorem prod_empty : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : set.prod (range m₁) (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : set.prod (univ : set α) (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_eq_empty_iff {s : set α} {t : set β} : set.prod s t = ∅ ↔ (s = ∅ ∨ t = ∅) := by simp only [not_nonempty_iff_eq_empty.symm, prod_nonempty_iff, classical.not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (set.prod s t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : set.prod s t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t.nonempty) : prod.fst '' (set.prod s t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (set.prod s t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : set.prod s t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s.nonempty) (t : set β) : prod.snd '' (set.prod s t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let ⟨x, x_in⟩ := hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (set.prod s t ⊆ set.prod s₁ t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, cases (set.prod s t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s.nonempty ∧ t.nonempty, by rwa [prod_nonempty_iff] at h, split, { assume H : set.prod s t ⊆ set.prod s₁ t₁, have h' : s₁.nonempty ∧ t₁.nonempty := prod_nonempty_iff.1 (h.mono H), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp only [st.1.ne_empty, st.2.ne_empty, or_false] at H, exact prod_mono H.1 H.2 } } end end prod /-! ### Lemmas about set-indexed products of sets -/ section pi variables {α : Type*} {π : α → Type*} /-- Given an index set `i` and a family of sets `s : Πa, set (π a)`, `pi i s` is the set of dependent functions `f : Πa, π a` such that `f a` belongs to `π a` whenever `a ∈ i`. -/ def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi /-! ### Lemmas about `inclusion`, the injection of subtypes induced by `⊆` -/ section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl @[simp] lemma coe_inclusion {s t : set α} (h : s ⊆ t) (x : s) : (inclusion h x : α) = (x : α) := rfl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext_iff_val.2 ∘ subtype.ext_iff_val.1 lemma range_inclusion {s t : set α} (h : s ⊆ t) : range (inclusion h) = {x : t | (x:α) ∈ s} := ext $ λ ⟨x, hx⟩ , by simp [inclusion] end inclusion end set namespace subsingleton variables {α : Type*} [subsingleton α] lemma eq_univ_of_nonempty {s : set α} : s.nonempty → s = univ := λ ⟨x, hx⟩, eq_univ_of_forall $ λ y, subsingleton.elim x y ▸ hx @[elab_as_eliminator] lemma set_cases {p : set α → Prop} (h0 : p ∅) (h1 : p univ) (s) : p s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ h0) $ λ h, (eq_univ_of_nonempty h).symm ▸ h1 end subsingleton namespace set variables {α : Type u} {β : Type v} {f : α → β} @[simp] lemma preimage_injective : injective (preimage f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.preimage_injective⟩, obtain ⟨x, hx⟩ : (f ⁻¹' {y}).nonempty, { rw [h.nonempty_apply_iff preimage_empty], apply singleton_nonempty }, exact ⟨x, hx⟩ end @[simp] lemma preimage_surjective : surjective (preimage f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.preimage_surjective⟩, cases h {x} with s hs, have := mem_singleton x, rwa [← hs, mem_preimage, hx, ← mem_preimage, hs, mem_singleton_iff, eq_comm] at this end @[simp] lemma image_surjective : surjective (image f) ↔ surjective f := begin refine ⟨λ h y, _, surjective.image_surjective⟩, cases h {y} with s hs, have := mem_singleton y, rw [← hs] at this, rcases this with ⟨x, h1x, h2x⟩, exact ⟨x, h2x⟩ end @[simp] lemma image_injective : injective (image f) ↔ injective f := begin refine ⟨λ h x x' hx, _, injective.image_injective⟩, rw [← singleton_eq_singleton_iff], apply h, rw [image_singleton, image_singleton, hx] end end set
82ff5f5456c4cdf3361cdde798105da5e4046ed6
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Deriving/DecEq.lean
1f661652ee97498d243a1c5001e6f0f885b38172
[ "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
4,983
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.Transform import Lean.Meta.Inductive import Lean.Elab.Deriving.Basic import Lean.Elab.Deriving.Util namespace Lean.Elab.Deriving.DecEq open Lean.Parser.Term open Meta def mkDecEqHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do mkHeader ctx `DecidableEq 2 indVal def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) (argNames : Array Name) : TermElabM Syntax := do let discrs ← mkDiscrs header indVal let alts ← mkAlts `(match $[$discrs],* with $alts:matchAlt*) where mkSameCtorRhs : List (Syntax × Syntax × Bool) → TermElabM Syntax | [] => `(isTrue rfl) | (a, b, recField) :: todo => withFreshMacroScope do let rhs ← `(if h : $a = $b then by subst h; exact $(← mkSameCtorRhs todo):term else isFalse (by intro n; injection n; apply h _; assumption)) if recField then -- add local instance for `a = b` using the function being defined `auxFunName` `(let inst := $(mkIdent auxFunName) $a $b; $rhs) else return rhs mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName₁ in indVal.ctors do let ctorInfo ← getConstInfoCtor ctorName₁ for ctorName₂ in indVal.ctors do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.numIndices] do patterns := patterns.push (← `(_)) if ctorName₁ == ctorName₂ then let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies let mut patterns := patterns let mut ctorArgs1 := #[] let mut ctorArgs2 := #[] -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.numParams] do ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) let mut todo := #[] for i in [:ctorInfo.numFields] do let x := xs[indVal.numParams + i] if type.containsFVar x.fvarId! then -- If resulting type depends on this field, we don't need to compare ctorArgs1 := ctorArgs1.push (← `(_)) ctorArgs2 := ctorArgs2.push (← `(_)) else let a := mkIdent (← mkFreshUserName `a) let b := mkIdent (← mkFreshUserName `b) ctorArgs1 := ctorArgs1.push a ctorArgs2 := ctorArgs2.push b let recField := (← inferType x).isAppOf indVal.name todo := todo.push (a, b, recField) patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs1:term*)) patterns := patterns.push (← `(@$(mkIdent ctorName₁):ident $ctorArgs2:term*)) let rhs ← mkSameCtorRhs todo.toList `(matchAltExpr| | $[$patterns:term],* => $rhs:term) alts := alts.push alt else if (← compatibleCtors ctorName₁ ctorName₂) then patterns := patterns ++ #[(← `($(mkIdent ctorName₁) ..)), (← `($(mkIdent ctorName₂) ..))] let rhs ← `(isFalse (by intro h; injection h)) alts ← alts.push (← `(matchAltExpr| | $[$patterns:term],* => $rhs:term)) return alts def mkAuxFunction (ctx : Context) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[0] let indVal ← ctx.typeInfos[0] let header ← mkDecEqHeader ctx indVal let mut body ← mkMatch ctx header indVal auxFunName header.argNames let binders := header.binders let type ← `(Decidable ($(mkIdent header.targetNames[0]) = $(mkIdent header.targetNames[1]))) `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $type:term := $body:term) def mkDecEqCmds (indVal : InductiveVal) : TermElabM (Array Syntax) := do let ctx ← mkContext "decEq" indVal.name let cmds := #[← mkAuxFunction ctx] ++ (← mkInstanceCmds ctx `DecidableEq #[indVal.name] (useAnonCtor := false)) trace[Elab.Deriving.decEq]! "\n{cmds}" return cmds open Command def mkDecEqInstanceHandler (declNames : Array Name) : CommandElabM Bool := do if declNames.size != 1 then return false -- mutually inductive types are not supported yet else let indVal ← getConstInfoInduct declNames[0] if indVal.isNested then return false -- nested inductive types are not supported yet else let cmds ← liftTermElabM none <| mkDecEqCmds indVal cmds.forM elabCommand return true builtin_initialize registerBuiltinDerivingHandler `DecidableEq mkDecEqInstanceHandler registerTraceClass `Elab.Deriving.decEq end Lean.Elab.Deriving.DecEq
189de2b7daf428542395ed35779e9d7897609633
f3849be5d845a1cb97680f0bbbe03b85518312f0
/old_library/init/meta/rb_map.lean
c4c3b33987c30bb5a9fb8e134fbe64b3505233d3
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,182
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, Jeremy Avigad -/ prelude import init.ordering init.meta.name init.meta.format meta_constant {u₁ u₂} rb_map : Type u₁ → Type u₂ → Type (max u₁ u₂ 1) namespace rb_map meta_constant mk_core {key : Type} (data : Type) : (key → key → ordering) → rb_map key data meta_constant size {key : Type} {data : Type} : rb_map key data → nat meta_constant insert {key : Type} {data : Type} : rb_map key data → key → data → rb_map key data meta_constant erase {key : Type} {data : Type} : rb_map key data → key → rb_map key data meta_constant contains {key : Type} {data : Type} : rb_map key data → key → bool meta_constant find {key : Type} {data : Type} : rb_map key data → key → option data meta_constant min {key : Type} {data : Type} : rb_map key data → option data meta_constant max {key : Type} {data : Type} : rb_map key data → option data meta_constant fold {key : Type} {data : Type} {A :Type} : rb_map key data → A → (key → data → A → A) → A attribute [inline] meta_definition mk (key : Type) [has_ordering key] (data : Type) : rb_map key data := mk_core data has_ordering.cmp open list meta_definition of_list {key : Type} {data : Type} [has_ordering key] : list (key × data) → rb_map key data | [] := mk key data | ((k, v)::ls) := insert (of_list ls) k v end rb_map attribute [reducible] meta_definition nat_map (data : Type) := rb_map nat data namespace nat_map export rb_map (hiding mk) attribute [inline] meta_definition mk (data : Type) : nat_map data := rb_map.mk nat data end nat_map attribute [reducible] meta_definition name_map (data : Type) := rb_map name data namespace name_map export rb_map (hiding mk) attribute [inline] meta_definition mk (data : Type) : name_map data := rb_map.mk name data end name_map open rb_map prod section open format variables {key : Type} {data : Type} [has_to_format key] [has_to_format data] private meta_definition format_key_data (k : key) (d : data) (first : bool) : format := (if first = tt then to_fmt "" else to_fmt "," ++ line) ++ to_fmt k ++ space ++ to_fmt "←" ++ space ++ to_fmt d attribute [instance] meta_definition rb_map_has_to_format : has_to_format (rb_map key data) := has_to_format.mk (λ m, group (to_fmt "⟨" ++ nest 1 (fst (fold m (to_fmt "", tt) (λ k d p, (fst p ++ format_key_data k d (snd p), ff)))) ++ to_fmt "⟩")) end section variables {key : Type} {data : Type} [has_to_string key] [has_to_string data] private meta_definition key_data_to_string (k : key) (d : data) (first : bool) : string := (if first = tt then "" else ", ") ++ to_string k ++ " ← " ++ to_string d attribute [instance] meta_definition rb_map_has_to_string : has_to_string (rb_map key data) := has_to_string.mk (λ m, "⟨" ++ (fst (fold m ("", tt) (λ k d p, (fst p ++ key_data_to_string k d (snd p), ff)))) ++ "⟩") end /- a variant of rb_maps that stores a list of elements for each key. "find" returns the list of elements in the opposite order that they were inserted. -/ meta_definition rb_lmap (key : Type) (data : Type) : Type := rb_map key (list data) namespace rb_lmap protected meta_definition mk (key : Type) [has_ordering key] (data : Type) : rb_lmap key data := rb_map.mk key (list data) meta_definition insert {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) (d : data) : rb_lmap key data := match (rb_map.find rbl k) with | none := rb_map.insert rbl k [d] | (some l) := rb_map.insert (rb_map.erase rbl k) k (d :: l) end meta_definition erase {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : rb_lmap key data := rb_map.erase rbl k meta_definition contains {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : bool := rb_map.contains rbl k meta_definition find {key : Type} {data : Type} (rbl : rb_lmap key data) (k : key) : list data := match (rb_map.find rbl k) with | none := [] | (some l) := l end end rb_lmap
b36131c271e6eb6848844a9c1eff23cb06b7cdea
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/run/typeclass_metas_internal_goals2.lean
dd3f2c46ae4db846db98a9f365cb2b5cc5b0db63
[ "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
375
lean
new_frontend class Foo (α β : Type) : Type := (u : Unit := ()) class Bar (α β : Type) : Type := (u : Unit := ()) class Top : Type := (u : Unit := ()) instance FooNatA (β : Type) : Foo Nat β := {u:=()} instance BarANat (α : Type) : Bar α Nat := {u:=()} instance FooBarToTop (α β : Type) [Foo α β] [Bar α β] : Top := {u:=()} set_option pp.all true #synth Top
e3972b556c4063eae4f1834cb2df05e7a81bee5b
2cf781335f4a6706b7452ab07ce323201e2e101f
/lean/deps/galois_stdlib/src/galois/data/list/default.lean
4f59e26d107aec69f0b6cd6bf96209e9d9cd33ba
[ "Apache-2.0" ]
permissive
simonjwinwood/reopt-vcg
697cdd5e68366b5aa3298845eebc34fc97ccfbe2
6aca24e759bff4f2230bb58270bac6746c13665e
refs/heads/master
1,586,353,878,347
1,549,667,148,000
1,549,667,148,000
159,409,828
0
0
null
1,543,358,444,000
1,543,358,444,000
null
UTF-8
Lean
false
false
699
lean
import data.list.basic -- from mathlib import .nth_le import .with_mem namespace list /-- Take conjunction of all propositions in list. -/ protected def forall_prop : list Prop → Prop | [] := true | (h::r) := h ∧ forall_prop r section is_empty /-- Return true if list is empty -/ def is_empty {α: Type _} : list α → Prop | [] := true | (_::_) := false /-- Decide whether list is empty -/ instance is_empty.decidable (α: Type _) : decidable_pred (@is_empty α) | [] := decidable.is_true trivial | (_::_) := decidable.is_false id end is_empty theorem map_eq_nil {α} {β} (f : α → β) (l:list α) : (list.map f l = nil) ↔ (l = nil) := begin cases l; simp [map], end end list
7142db38e6da618fcd6f2826283e60df648bde90
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/lp_equiv.lean
b705a4bd3ce8c92fee1d581f94923a31f5ef87c5
[ "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
7,237
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.lp_space import analysis.normed_space.pi_Lp import topology.continuous_function.bounded /-! # Equivalences among $L^p$ spaces In this file we collect a variety of equivalences among various $L^p$ spaces. In particular, when `α` is a `fintype`, given `E : α → Type u` and `p : ℝ≥0∞`, there is a natural linear isometric equivalence `lp_pi_Lpₗᵢ : lp E p ≃ₗᵢ pi_Lp p E`. In addition, when `α` is a discrete topological space, the bounded continuous functions `α →ᵇ β` correspond exactly to `lp (λ _, β) ∞`. Here there can be more structure, including ring and algebra structures, and we implement these equivalences accordingly as well. We keep this as a separate file so that the various $L^p$ space files don't import the others. Recall that `pi_Lp` is just a type synonym for `Π i, E i` but given a different metric and norm structure, although the topological, uniform and bornological structures coincide definitionally. These structures are only defined on `pi_Lp` for `fintype α`, so there are no issues of convergence to consider. While `pre_lp` is also a type synonym for `Π i, E i`, it allows for infinite index types. On this type there is a predicate `mem_ℓp` which says that the relevant `p`-norm is finite and `lp E p` is the subtype of `pre_lp` satisfying `mem_ℓp`. ## TODO * Equivalence between `lp` and `measure_theory.Lp`, for `f : α → E` (i.e., functions rather than pi-types) and the counting measure on `α` -/ open_locale ennreal section lp_pi_Lp variables {α : Type*} {E : α → Type*} [Π i, normed_add_comm_group (E i)] {p : ℝ≥0∞} /-- When `α` is `finite`, every `f : pre_lp E p` satisfies `mem_ℓp f p`. -/ lemma mem_ℓp.all [finite α] (f : Π i, E i) : mem_ℓp f p := begin rcases p.trichotomy with (rfl | rfl | h), { exact mem_ℓp_zero_iff.mpr {i : α | f i ≠ 0}.to_finite, }, { exact mem_ℓp_infty_iff.mpr (set.finite.bdd_above (set.range (λ (i : α), ‖f i‖)).to_finite) }, { casesI nonempty_fintype α, exact mem_ℓp_gen ⟨finset.univ.sum _, has_sum_fintype _⟩ } end variables [fintype α] /-- The canonical `equiv` between `lp E p ≃ pi_Lp p E` when `E : α → Type u` with `[fintype α]`. -/ def equiv.lp_pi_Lp : lp E p ≃ pi_Lp p E := { to_fun := λ f, f, inv_fun := λ f, ⟨f, mem_ℓp.all f⟩, left_inv := λ f, lp.ext $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, rfl } lemma coe_equiv_lp_pi_Lp (f : lp E p) : equiv.lp_pi_Lp f = f := rfl lemma coe_equiv_lp_pi_Lp_symm (f : pi_Lp p E) : (equiv.lp_pi_Lp.symm f : Π i, E i) = f := rfl lemma equiv_lp_pi_Lp_norm (f : lp E p) : ‖equiv.lp_pi_Lp f‖ = ‖f‖ := begin unfreezingI { rcases p.trichotomy with (rfl | rfl | h) }, { rw [pi_Lp.norm_eq_card, lp.norm_eq_card_dsupport], refl }, { rw [pi_Lp.norm_eq_csupr, lp.norm_eq_csupr], refl }, { rw [pi_Lp.norm_eq_sum h, lp.norm_eq_tsum_rpow h, tsum_fintype], refl }, end /-- The canonical `add_equiv` between `lp E p` and `pi_Lp p E` when `E : α → Type u` with `[fintype α]` and `[fact (1 ≤ p)]`. -/ def add_equiv.lp_pi_Lp [fact (1 ≤ p)] : lp E p ≃+ pi_Lp p E := { map_add' := λ f g, rfl, .. equiv.lp_pi_Lp } lemma coe_add_equiv_lp_pi_Lp [fact (1 ≤ p)] (f : lp E p) : add_equiv.lp_pi_Lp f = f := rfl lemma coe_add_equiv_lp_pi_Lp_symm [fact (1 ≤ p)] (f : pi_Lp p E) : (add_equiv.lp_pi_Lp.symm f : Π i, E i) = f := rfl section equivₗᵢ variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] [Π i, normed_space 𝕜 (E i)] /-- The canonical `linear_isometry_equiv` between `lp E p` and `pi_Lp p E` when `E : α → Type u` with `[fintype α]` and `[fact (1 ≤ p)]`. -/ noncomputable def lp_pi_Lpₗᵢ [fact (1 ≤ p)] : lp E p ≃ₗᵢ[𝕜] pi_Lp p E := { map_smul' := λ k f, rfl, norm_map' := equiv_lp_pi_Lp_norm, .. add_equiv.lp_pi_Lp } variables {𝕜} lemma coe_lp_pi_Lpₗᵢ [fact (1 ≤ p)] (f : lp E p) : lp_pi_Lpₗᵢ 𝕜 f = f := rfl lemma coe_lp_pi_Lpₗᵢ_symm [fact (1 ≤ p)] (f : pi_Lp p E) : ((lp_pi_Lpₗᵢ 𝕜).symm f : Π i, E i) = f := rfl end equivₗᵢ end lp_pi_Lp section lp_bcf open_locale bounded_continuous_function open bounded_continuous_function -- note: `R` and `A` are explicit because otherwise Lean has elaboration problems variables {α E : Type*} (R A 𝕜 : Type*) [topological_space α] [discrete_topology α] variables [normed_ring A] [norm_one_class A] [nontrivially_normed_field 𝕜] [normed_algebra 𝕜 A] variables [normed_add_comm_group E] [normed_space 𝕜 E] [non_unital_normed_ring R] section normed_add_comm_group /-- The canonical map between `lp (λ (_ : α), E) ∞` and `α →ᵇ E` as an `add_equiv`. -/ noncomputable def add_equiv.lp_bcf : lp (λ (_ : α), E) ∞ ≃+ (α →ᵇ E) := { to_fun := λ f, of_normed_add_comm_group_discrete f (‖f‖) $ le_csupr (mem_ℓp_infty_iff.mp f.prop), inv_fun := λ f, ⟨f, f.bdd_above_range_norm_comp⟩, left_inv := λ f, lp.ext rfl, right_inv := λ f, ext $ λ x, rfl, map_add' := λ f g, ext $ λ x, rfl } lemma coe_add_equiv_lp_bcf (f : lp (λ (_ : α), E) ∞) : (add_equiv.lp_bcf f : α → E) = f := rfl lemma coe_add_equiv_lp_bcf_symm (f : α →ᵇ E) : (add_equiv.lp_bcf.symm f : α → E) = f := rfl /-- The canonical map between `lp (λ (_ : α), E) ∞` and `α →ᵇ E` as a `linear_isometry_equiv`. -/ noncomputable def lp_bcfₗᵢ : lp (λ (_ : α), E) ∞ ≃ₗᵢ[𝕜] (α →ᵇ E) := { map_smul' := λ k f, rfl, norm_map' := λ f, by { simp only [norm_eq_supr_norm, lp.norm_eq_csupr], refl }, .. add_equiv.lp_bcf } variables {𝕜} lemma coe_lp_bcfₗᵢ (f : lp (λ (_ : α), E) ∞) : (lp_bcfₗᵢ 𝕜 f : α → E) = f := rfl lemma coe_lp_bcfₗᵢ_symm (f : α →ᵇ E) : ((lp_bcfₗᵢ 𝕜).symm f : α → E) = f := rfl end normed_add_comm_group section ring_algebra /-- The canonical map between `lp (λ (_ : α), R) ∞` and `α →ᵇ R` as a `ring_equiv`. -/ noncomputable def ring_equiv.lp_bcf : lp (λ (_ : α), R) ∞ ≃+* (α →ᵇ R) := { map_mul' := λ f g, ext $ λ x, rfl, .. @add_equiv.lp_bcf _ R _ _ _ } variables {R} lemma coe_ring_equiv_lp_bcf (f : lp (λ (_ : α), R) ∞) : (ring_equiv.lp_bcf R f : α → R) = f := rfl lemma coe_ring_equiv_lp_bcf_symm (f : α →ᵇ R) : ((ring_equiv.lp_bcf R).symm f : α → R) = f := rfl variables (α) -- even `α` needs to be explicit here for elaboration -- the `norm_one_class A` shouldn't really be necessary, but currently it is for -- `one_mem_ℓp_infty` to get the `ring` instance on `lp`. /-- The canonical map between `lp (λ (_ : α), A) ∞` and `α →ᵇ A` as an `alg_equiv`. -/ noncomputable def alg_equiv.lp_bcf : lp (λ (_ : α), A) ∞ ≃ₐ[𝕜] (α →ᵇ A) := { commutes' := λ k, rfl, .. ring_equiv.lp_bcf A } variables {α A 𝕜} lemma coe_alg_equiv_lp_bcf (f : lp (λ (_ : α), A) ∞) : (alg_equiv.lp_bcf α A 𝕜 f : α → A) = f := rfl lemma coe_alg_equiv_lp_bcf_symm (f : α →ᵇ A) : ((alg_equiv.lp_bcf α A 𝕜).symm f : α → A) = f := rfl end ring_algebra end lp_bcf
ce26f8bb0c2c169405aa7fa30d1af8e6fe06c869
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/tree_subterm_pred.lean
3c8d7df955c01fd82c85122c7cea24d2ee508b0d
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,138
lean
import logic open eq.ops inductive tree (A : Type) := | leaf : A → tree A | node : tree A → tree A → tree A namespace tree inductive direct_subterm {A : Type} : tree A → tree A → Prop := | node_l : Π (l r : tree A), direct_subterm l (node l r) | node_r : Π (l r : tree A), direct_subterm r (node l r) definition direct_subterm.wf {A : Type} : well_founded (@direct_subterm A) := well_founded.intro (λ t : tree A, tree.rec_on t (λ (a : A), acc.intro (leaf a) (λ (s : tree A) (H : direct_subterm s (leaf a)), have gen : ∀ r : tree A, direct_subterm s r → r = leaf a → acc direct_subterm s, from λ r H, direct_subterm.rec_on H (λ l r e, tree.no_confusion e) (λ l r e, tree.no_confusion e), gen (leaf a) H rfl)) (λ (l r : tree A) (ihl : acc direct_subterm l) (ihr : acc direct_subterm r), acc.intro (node l r) (λ (s : tree A) (H : direct_subterm s (node l r)), have gen : ∀ n₁ : tree A, direct_subterm s n₁ → node l r = n₁ → acc direct_subterm s, from λ n₁ H, direct_subterm.rec_on H (λ (l' r' : tree A) (Heq : node l r = node l' r'), tree.no_confusion Heq (λ leq req, eq.rec_on leq ihl)) (λ (l' r' : tree A) (Heq : node l r = node l' r'), tree.no_confusion Heq (λ leq req, eq.rec_on req ihr)), gen (node l r) H rfl))) definition direct_subterm.wf₂ {A : Type} : well_founded (@direct_subterm A) := begin constructor, intro t, induction t, repeat (constructor; intro y hlt; cases hlt; repeat assumption) end definition subterm {A : Type} : tree A → tree A → Prop := tc (@direct_subterm A) definition subterm.wf {A : Type} : well_founded (@subterm A) := tc.wf (@direct_subterm.wf A) example : subterm (leaf 2) (node (leaf 1) (leaf 2)) := !tc.base !direct_subterm.node_r example : subterm (leaf 2) (node (node (leaf 1) (leaf 2)) (leaf 3)) := have s₁ : subterm (leaf 2) (node (leaf 1) (leaf 2)), from !tc.base !direct_subterm.node_r, have s₂ : subterm (node (leaf 1) (leaf 2)) (node (node (leaf 1) (leaf 2)) (leaf 3)), from !tc.base !direct_subterm.node_l, !tc.trans s₁ s₂ end tree
c9595e94f7e399060eb26558714aa4385762f5eb
618003631150032a5676f229d13a079ac875ff77
/src/algebra/quadratic_discriminant.lean
96517fdae5711902e5c2bed745cd6fc3cfe455ff
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
6,864
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import tactic.linarith /-! # Quadratic discriminants and roots of a quadratic This file defines the discriminant of a quadratic and gives the solution to a quadratic equation. ## Main definition The discriminant of a quadratic `a*x*x + b*x + c` is `b*b - 4*a*c`. ## Main statements • Roots of a quadratic can be written as `(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is the square root of the discriminant. • If the discriminant has no square root, then the corresponding quadratic has no root. • If a quadratic is always non-negative, then its discriminant is non-positive. ## Tags polynomial, quadratic, discriminant, root -/ variables {α : Type*} section lemmas variables [linear_ordered_field α] {a b c : α} lemma exists_le_mul_self : ∀ a : α, ∃ x : α, a ≤ x * x := begin classical, -- TODO: otherwise linarith performance sucks assume a, cases le_total 1 a with ha ha, { use a, exact le_mul_of_ge_one_left (by linarith) ha }, { use 1, linarith } end lemma exists_lt_mul_self : ∀ a : α, ∃ x : α, a < x * x := begin classical, -- todo: otherwise linarith performance sucks assume a, rcases (exists_le_mul_self a) with ⟨x, hx⟩, cases le_total 0 x with hx' hx', { use (x + 1), have : (x+1)*(x+1) = x*x + 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) }, { use (x - 1), have : (x-1)*(x-1) = x*x - 2*x + 1, {ring}, exact lt_of_le_of_lt hx (by rw this; linarith) } end end lemmas variables [linear_ordered_field α] {a b c x : α} /-- Discriminant of a quadratic -/ def discrim [ring α] (a b c : α) : α := b^2 - 4 * a * c /-- A quadratic has roots if and only if its discriminant equals some square. -/ lemma quadratic_eq_zero_iff_discrim_eq_square (ha : a ≠ 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b)^2 := by classical; exact -- TODO: otherwise linarith performance sucks assume x, iff.intro (assume h, calc discrim a b c = 4*a*(a*x*x + b*x + c) + b*b - 4*a*c : by rw [h, discrim]; ring ... = (2*a*x + b)^2 : by ring) (assume h, have ha : 2*2*a ≠ 0 := mul_ne_zero (mul_ne_zero two_ne_zero two_ne_zero) ha, eq_of_mul_eq_mul_left_of_ne_zero ha $ calc 2 * 2 * a * (a * x * x + b * x + c) = (2*a*x + b)^2 - (b^2 - 4*a*c) : by ring ... = 0 : by { rw [← h, discrim], ring } ... = 2*2*a*0 : by ring) /-- Roots of a quadratic -/ lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : α} (h : discrim a b c = s * s) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks rw [quadratic_eq_zero_iff_discrim_eq_square ha, h, pow_two, mul_self_eq_mul_self_iff], have ne : 2 * a ≠ 0 := mul_ne_zero two_ne_zero ha, have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm, have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne, have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne, split, { intro h', rcases h', { left, rw h', simpa [add_comm] }, { right, rw h', simpa [add_comm, sub_eq_add_neg] } }, { intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } } end /-- A quadratic has roots if its discriminant has square roots -/ lemma exist_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) : ∃ x, a * x * x + b * x + c = 0 := begin rcases h with ⟨s, hs⟩, use (-b + s) / (2 * a), rw quadratic_eq_zero_iff ha hs, simp end /-- Root of a quadratic when its discriminant equals zero -/ lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) : ∀ x : α, a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) := assume x, begin classical, -- TODO: otherwise linarith performance sucks have : discrim a b c = 0 * 0 := eq.trans h (by ring), rw quadratic_eq_zero_iff ha this, simp end /-- A quadratic has no root if its discriminant has no square root. -/ lemma quadratic_ne_zero_of_discrim_ne_square (ha : a ≠ 0) (h : ∀ s : α, discrim a b c ≠ s * s) : ∀ (x : α), a * x * x + b * x + c ≠ 0 := begin assume x h', rw [quadratic_eq_zero_iff_discrim_eq_square ha, pow_two] at h', have := h _, contradiction end /-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/ lemma discriminant_le_zero {a b c : α} (h : ∀ x : α, 0 ≤ a*x*x + b*x + c) : discrim a b c ≤ 0 := by classical; exact -- TODO: otherwise linarith performance sucks have hc : 0 ≤ c, by { have := h 0, linarith }, begin rw [discrim, pow_two], cases lt_trichotomy a 0 with ha ha, -- if a < 0 cases classical.em (b = 0) with hb hb, { rw hb at *, rcases exists_lt_mul_self (-c/a) with ⟨x, hx⟩, have := mul_lt_mul_of_neg_left hx ha, rw [mul_div_cancel' _ (ne_of_lt ha), ← mul_assoc] at this, have h₂ := h x, linarith }, { cases classical.em (c = 0) with hc' hc', { rw hc' at *, have : -(a*-b*-b + b*-b + 0) = (1-a)*(b*b), {ring}, have h := h (-b), rw [← neg_nonpos, this] at h, have : b * b ≤ 0 := nonpos_of_mul_nonpos_left h (by linarith), linarith }, { have h := h (-c/b), have : a*(-c/b)*(-c/b) + b*(-c/b) + c = a*((c/b)*(c/b)), { rw mul_div_cancel' _ hb, ring }, rw this at h, have : 0 ≤ a := nonneg_of_mul_nonneg_right h (mul_self_pos $ div_ne_zero hc' hb), linarith [ha] } }, cases ha with ha ha, -- if a = 0 cases classical.em (b = 0) with hb hb, { rw [ha, hb], linarith }, { have := h ((-c-1)/b), rw [ha, mul_div_cancel' _ hb] at this, linarith }, -- if a > 0 have := calc 4*a* (a*(-(b/a)*(1/2))*(-(b/a)*(1/2)) + b*(-(b/a)*(1/2)) + c) = (a*(b/a)) * (a*(b/a)) - 2*(a*(b/a))*b + 4*a*c : by ring ... = -(b*b - 4*a*c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring }, have ha' : 0 ≤ 4*a, {linarith}, have h := (mul_nonneg ha' (h (-(b/a) * (1/2)))), rw this at h, rwa ← neg_nonneg end /-- If a polynomial of degree 2 is always positive, then its discriminant is negative, at least when the coefficient of the quadratic term is nonzero. -/ lemma discriminant_lt_zero {a b c : α} (ha : a ≠ 0) (h : ∀ x : α, 0 < a*x*x + b*x + c) : discrim a b c < 0 := begin classical, -- TODO: otherwise linarith performance sucks have : ∀ x : α, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x), refine lt_of_le_of_ne (discriminant_le_zero this) _, assume h', have := h (-b / (2 * a)), have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0, { rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] }, linarith end
f334c7b0b527a130f0ce683562adaaa561d417cf
9dc8cecdf3c4634764a18254e94d43da07142918
/src/order/jordan_holder.lean
19164b293c418a9a04cae15f5c0dde426967b94f
[ "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
30,654
lean
/- Copyright (c) 2021 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import order.lattice import data.list.sort import logic.equiv.fin import logic.equiv.functor import data.fintype.basic /-! # Jordan-Hölder Theorem This file proves the Jordan Hölder theorem for a `jordan_holder_lattice`, a class also defined in this file. Examples of `jordan_holder_lattice` include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. Using this approach the theorem need not be proved seperately for both groups and modules, the proof in this file can be applied to both. ## Main definitions The main definitions in this file are `jordan_holder_lattice` and `composition_series`, and the relation `equivalent` on `composition_series` A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. A `composition_series X` is a finite nonempty series of elements of the lattice `X` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i, s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` ## Main theorems The main theorem is `composition_series.jordan_holder`, which says that if two composition series have the same least element and the same largest element, then they are `equivalent`. ## TODO Provide instances of `jordan_holder_lattice` for both submodules and subgroups, and potentially for modular lattices. It is not entirely clear how this should be done. Possibly there should be no global instances of `jordan_holder_lattice`, and the instances should only be defined locally in order to prove the Jordan-Hölder theorem for modules/groups and the API should be transferred because many of the theorems in this file will have stronger versions for modules. There will also need to be an API for mapping composition series across homomorphisms. It is also probably possible to provide an instance of `jordan_holder_lattice` for any `modular_lattice`, and in this case the Jordan-Hölder theorem will say that there is a well defined notion of length of a modular lattice. However an instance of `jordan_holder_lattice` for a modular lattice will not be able to contain the correct notion of isomorphism for modules, so a separate instance for modules will still be required and this will clash with the instance for modular lattices, and so at least one of these instances should not be a global instance. -/ universe u open set /-- A `jordan_holder_lattice` is the class for which the Jordan Hölder theorem is proved. A Jordan Hölder lattice is a lattice equipped with a notion of maximality, `is_maximal`, and a notion of isomorphism of pairs `iso`. In the example of subgroups of a group, `is_maximal H K` means that `H` is a maximal normal subgroup of `K`, and `iso (H₁, K₁) (H₂, K₂)` means that the quotient `H₁ / K₁` is isomorphic to the quotient `H₂ / K₂`. `iso` must be symmetric and transitive and must satisfy the second isomorphism theorem `iso (H, H ⊔ K) (H ⊓ K, K)`. Examples include `subgroup G` if `G` is a group, and `submodule R M` if `M` is an `R`-module. -/ class jordan_holder_lattice (X : Type u) [lattice X] := (is_maximal : X → X → Prop) (lt_of_is_maximal : ∀ {x y}, is_maximal x y → x < y) (sup_eq_of_is_maximal : ∀ {x y z}, is_maximal x z → is_maximal y z → x ≠ y → x ⊔ y = z) (is_maximal_inf_left_of_is_maximal_sup : ∀ {x y}, is_maximal x (x ⊔ y) → is_maximal y (x ⊔ y) → is_maximal (x ⊓ y) x) (iso : (X × X) → (X × X) → Prop) (iso_symm : ∀ {x y}, iso x y → iso y x) (iso_trans : ∀ {x y z}, iso x y → iso y z → iso x z) (second_iso : ∀ {x y}, is_maximal x (x ⊔ y) → iso (x, x ⊔ y) (x ⊓ y, y)) namespace jordan_holder_lattice variables {X : Type u} [lattice X] [jordan_holder_lattice X] lemma is_maximal_inf_right_of_is_maximal_sup {x y : X} (hxz : is_maximal x (x ⊔ y)) (hyz : is_maximal y (x ⊔ y)) : is_maximal (x ⊓ y) y := begin rw [inf_comm], rw [sup_comm] at hxz hyz, exact is_maximal_inf_left_of_is_maximal_sup hyz hxz end lemma is_maximal_of_eq_inf (x b : X) {a y : X} (ha : x ⊓ y = a) (hxy : x ≠ y) (hxb : is_maximal x b) (hyb : is_maximal y b) : is_maximal a y := begin have hb : x ⊔ y = b, from sup_eq_of_is_maximal hxb hyb hxy, substs a b, exact is_maximal_inf_right_of_is_maximal_sup hxb hyb end lemma second_iso_of_eq {x y a b : X} (hm : is_maximal x a) (ha : x ⊔ y = a) (hb : x ⊓ y = b) : iso (x, a) (b, y) := by substs a b; exact second_iso hm lemma is_maximal.iso_refl {x y : X} (h : is_maximal x y) : iso (x, y) (x, y) := second_iso_of_eq h (sup_eq_right.2 (le_of_lt (lt_of_is_maximal h))) (inf_eq_left.2 (le_of_lt (lt_of_is_maximal h))) end jordan_holder_lattice open jordan_holder_lattice attribute [symm] iso_symm attribute [trans] iso_trans /-- A `composition_series X` is a finite nonempty series of elements of a `jordan_holder_lattice` such that each element is maximal inside the next. The length of a `composition_series X` is one less than the number of elements in the series. Note that there is no stipulation that a series start from the bottom of the lattice and finish at the top. For a composition series `s`, `s.top` is the largest element of the series, and `s.bot` is the least element. -/ structure composition_series (X : Type u) [lattice X] [jordan_holder_lattice X] : Type u := (length : ℕ) (series : fin (length + 1) → X) (step' : ∀ i : fin length, is_maximal (series i.cast_succ) (series i.succ)) namespace composition_series variables {X : Type u} [lattice X] [jordan_holder_lattice X] instance : has_coe_to_fun (composition_series X) (λ x, fin (x.length + 1) → X) := { coe := composition_series.series } instance [inhabited X] : inhabited (composition_series X) := ⟨{ length := 0, series := default, step' := λ x, x.elim0 }⟩ variables {X} lemma step (s : composition_series X) : ∀ i : fin s.length, is_maximal (s i.cast_succ) (s i.succ) := s.step' @[simp] lemma coe_fn_mk (length : ℕ) (series step) : (@composition_series.mk X _ _ length series step : fin length.succ → X) = series := rfl theorem lt_succ (s : composition_series X) (i : fin s.length) : s i.cast_succ < s i.succ := lt_of_is_maximal (s.step _) protected theorem strict_mono (s : composition_series X) : strict_mono s := fin.strict_mono_iff_lt_succ.2 s.lt_succ protected theorem injective (s : composition_series X) : function.injective s := s.strict_mono.injective @[simp] protected theorem inj (s : composition_series X) {i j : fin s.length.succ} : s i = s j ↔ i = j := s.injective.eq_iff instance : has_mem X (composition_series X) := ⟨λ x s, x ∈ set.range s⟩ lemma mem_def {x : X} {s : composition_series X} : x ∈ s ↔ x ∈ set.range s := iff.rfl lemma total {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) : x ≤ y ∨ y ≤ x := begin rcases set.mem_range.1 hx with ⟨i, rfl⟩, rcases set.mem_range.1 hy with ⟨j, rfl⟩, rw [s.strict_mono.le_iff_le, s.strict_mono.le_iff_le], exact le_total i j end /-- The ordered `list X` of elements of a `composition_series X`. -/ def to_list (s : composition_series X) : list X := list.of_fn s /-- Two `composition_series` are equal if they are the same length and have the same `i`th element for every `i` -/ lemma ext_fun {s₁ s₂ : composition_series X} (hl : s₁.length = s₂.length) (h : ∀ i, s₁ i = s₂ (fin.cast (congr_arg nat.succ hl) i)) : s₁ = s₂ := begin cases s₁, cases s₂, dsimp at *, subst hl, simpa [function.funext_iff] using h end @[simp] lemma length_to_list (s : composition_series X) : s.to_list.length = s.length + 1 := by rw [to_list, list.length_of_fn] lemma to_list_ne_nil (s : composition_series X) : s.to_list ≠ [] := by rw [← list.length_pos_iff_ne_nil, length_to_list]; exact nat.succ_pos _ lemma to_list_injective : function.injective (@composition_series.to_list X _ _) := λ s₁ s₂ (h : list.of_fn s₁ = list.of_fn s₂), have h₁ : s₁.length = s₂.length, from nat.succ_injective ((list.length_of_fn s₁).symm.trans $ (congr_arg list.length h).trans $ list.length_of_fn s₂), have h₂ : ∀ i : fin s₁.length.succ, (s₁ i) = s₂ (fin.cast (congr_arg nat.succ h₁) i), begin assume i, rw [← list.nth_le_of_fn s₁ i, ← list.nth_le_of_fn s₂], simp [h] end, begin cases s₁, cases s₂, dsimp at *, subst h₁, simp only [heq_iff_eq, eq_self_iff_true, true_and], simp only [fin.cast_refl] at h₂, exact funext h₂ end lemma chain'_to_list (s : composition_series X) : list.chain' is_maximal s.to_list := list.chain'_iff_nth_le.2 begin assume i hi, simp only [to_list, list.nth_le_of_fn'], rw [length_to_list] at hi, exact s.step ⟨i, hi⟩ end lemma to_list_sorted (s : composition_series X) : s.to_list.sorted (<) := list.pairwise_iff_nth_le.2 (λ i j hi hij, begin dsimp [to_list], rw [list.nth_le_of_fn', list.nth_le_of_fn'], exact s.strict_mono hij end) lemma to_list_nodup (s : composition_series X) : s.to_list.nodup := s.to_list_sorted.nodup @[simp] lemma mem_to_list {s : composition_series X} {x : X} : x ∈ s.to_list ↔ x ∈ s := by rw [to_list, list.mem_of_fn, mem_def] /-- Make a `composition_series X` from the ordered list of its elements. -/ def of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : composition_series X := { length := l.length - 1, series := λ i, l.nth_le i begin conv_rhs { rw ← tsub_add_cancel_of_le (nat.succ_le_of_lt (list.length_pos_of_ne_nil hl)) }, exact i.2 end, step' := λ ⟨i, hi⟩, list.chain'_iff_nth_le.1 hc i hi } lemma length_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : (of_list l hl hc).length = l.length - 1 := rfl lemma of_list_to_list (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := begin refine ext_fun _ _, { rw [length_of_list, length_to_list, nat.succ_sub_one] }, { rintros ⟨i, hi⟩, dsimp [of_list, to_list], rw [list.nth_le_of_fn'] } end @[simp] lemma of_list_to_list' (s : composition_series X) : of_list s.to_list s.to_list_ne_nil s.chain'_to_list = s := of_list_to_list s @[simp] lemma to_list_of_list (l : list X) (hl : l ≠ []) (hc : list.chain' is_maximal l) : to_list (of_list l hl hc) = l := begin refine list.ext_le _ _, { rw [length_to_list, length_of_list, tsub_add_cancel_of_le (nat.succ_le_of_lt $ list.length_pos_of_ne_nil hl)] }, { assume i hi hi', dsimp [of_list, to_list], rw [list.nth_le_of_fn'], refl } end /-- Two `composition_series` are equal if they have the same elements. See also `ext_fun`. -/ @[ext] lemma ext {s₁ s₂ : composition_series X} (h : ∀ x, x ∈ s₁ ↔ x ∈ s₂) : s₁ = s₂ := to_list_injective $ list.eq_of_perm_of_sorted (by classical; exact list.perm_of_nodup_nodup_to_finset_eq s₁.to_list_nodup s₂.to_list_nodup (finset.ext $ by simp *)) s₁.to_list_sorted s₂.to_list_sorted /-- The largest element of a `composition_series` -/ def top (s : composition_series X) : X := s (fin.last _) lemma top_mem (s : composition_series X) : s.top ∈ s := mem_def.2 (set.mem_range.2 ⟨fin.last _, rfl⟩) @[simp] lemma le_top {s : composition_series X} (i : fin (s.length + 1)) : s i ≤ s.top := s.strict_mono.monotone (fin.le_last _) lemma le_top_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : x ≤ s.top := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ le_top _ /-- The smallest element of a `composition_series` -/ def bot (s : composition_series X) : X := s 0 lemma bot_mem (s : composition_series X) : s.bot ∈ s := mem_def.2 (set.mem_range.2 ⟨0, rfl⟩) @[simp] lemma bot_le {s : composition_series X} (i : fin (s.length + 1)) : s.bot ≤ s i := s.strict_mono.monotone (fin.zero_le _) lemma bot_le_of_mem {s : composition_series X} {x : X} (hx : x ∈ s) : s.bot ≤ x := let ⟨i, hi⟩ := set.mem_range.2 hx in hi ▸ bot_le _ lemma length_pos_of_mem_ne {s : composition_series X} {x y : X} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) : 0 < s.length := let ⟨i, hi⟩ := hx, ⟨j, hj⟩ := hy in have hij : i ≠ j, from mt s.inj.2 $ λ h, hxy (hi ▸ hj ▸ h), hij.lt_or_lt.elim (λ hij, (lt_of_le_of_lt (zero_le i) (lt_of_lt_of_le hij (nat.le_of_lt_succ j.2)))) (λ hji, (lt_of_le_of_lt (zero_le j) (lt_of_lt_of_le hji (nat.le_of_lt_succ i.2)))) lemma forall_mem_eq_of_length_eq_zero {s : composition_series X} (hs : s.length = 0) {x y} (hx : x ∈ s) (hy : y ∈ s) : x = y := by_contradiction (λ hxy, pos_iff_ne_zero.1 (length_pos_of_mem_ne hx hy hxy) hs) /-- Remove the largest element from a `composition_series`. If the series `s` has length zero, then `s.erase_top = s` -/ @[simps] def erase_top (s : composition_series X) : composition_series X := { length := s.length - 1, series := λ i, s ⟨i, lt_of_lt_of_le i.2 (nat.succ_le_succ tsub_le_self)⟩, step' := λ i, begin have := s.step ⟨i, lt_of_lt_of_le i.2 tsub_le_self⟩, cases i, exact this end } lemma top_erase_top (s : composition_series X) : s.erase_top.top = s ⟨s.length - 1, lt_of_le_of_lt tsub_le_self (nat.lt_succ_self _)⟩ := show s _ = s _, from congr_arg s begin ext, simp only [erase_top_length, fin.coe_last, fin.coe_cast_succ, fin.coe_of_nat_eq_mod, fin.coe_mk, coe_coe] end lemma erase_top_top_le (s : composition_series X) : s.erase_top.top ≤ s.top := by simp [erase_top, top, s.strict_mono.le_iff_le, fin.le_iff_coe_le_coe, tsub_le_self] @[simp] lemma bot_erase_top (s : composition_series X) : s.erase_top.bot = s.bot := rfl lemma mem_erase_top_of_ne_of_mem {s : composition_series X} {x : X} (hx : x ≠ s.top) (hxs : x ∈ s) : x ∈ s.erase_top := begin rcases hxs with ⟨i, rfl⟩, have hi : (i : ℕ) < (s.length - 1).succ, { conv_rhs { rw [← nat.succ_sub (length_pos_of_mem_ne ⟨i, rfl⟩ s.top_mem hx), nat.succ_sub_one] }, exact lt_of_le_of_ne (nat.le_of_lt_succ i.2) (by simpa [top, s.inj, fin.ext_iff] using hx) }, refine ⟨i.cast_succ, _⟩, simp [fin.ext_iff, nat.mod_eq_of_lt hi] end lemma mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) : x ∈ s.erase_top ↔ x ≠ s.top ∧ x ∈ s := begin simp only [mem_def], dsimp only [erase_top, coe_fn_mk], split, { rintros ⟨i, rfl⟩, have hi : (i : ℕ) < s.length, { conv_rhs { rw [← nat.succ_sub_one s.length, nat.succ_sub h] }, exact i.2 }, simp [top, fin.ext_iff, (ne_of_lt hi)] }, { intro h, exact mem_erase_top_of_ne_of_mem h.1 h.2 } end lemma lt_top_of_mem_erase_top {s : composition_series X} {x : X} (h : 0 < s.length) (hx : x ∈ s.erase_top) : x < s.top := lt_of_le_of_ne (le_top_of_mem ((mem_erase_top h).1 hx).2) ((mem_erase_top h).1 hx).1 lemma is_maximal_erase_top_top {s : composition_series X} (h : 0 < s.length) : is_maximal s.erase_top.top s.top := have s.length - 1 + 1 = s.length, by conv_rhs { rw [← nat.succ_sub_one s.length] }; rw nat.succ_sub h, begin rw [top_erase_top, top], convert s.step ⟨s.length - 1, nat.sub_lt h zero_lt_one⟩; ext; simp [this] end lemma append_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := by { cases i, simp [fin.append, *] } lemma append_succ_cast_add_aux {s₁ s₂ : composition_series X} (i : fin s₁.length) (h : s₁ (fin.last _) = s₂ 0) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.cast_add s₂.length i).succ = s₁ i.succ := begin cases i with i hi, simp only [fin.append, hi, fin.succ_mk, function.comp_app, fin.cast_succ_mk, fin.coe_mk, fin.cast_add_mk], split_ifs, { refl }, { have : i + 1 = s₁.length, from le_antisymm hi (le_of_not_gt h_1), calc s₂ ⟨i + 1 - s₁.length, by simp [this]⟩ = s₂ 0 : congr_arg s₂ (by simp [fin.ext_iff, this]) ... = s₁ (fin.last _) : h.symm ... = _ : congr_arg s₁ (by simp [fin.ext_iff, this]) } end lemma append_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := begin cases i, simp only [fin.append, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, dif_neg, fin.cast_succ_mk, not_false_iff, fin.coe_mk] end lemma append_succ_nat_add_aux {s₁ s₂ : composition_series X} (i : fin s₂.length) : fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂ (fin.nat_add s₁.length i).succ = s₂ i.succ := begin cases i with i hi, simp only [fin.append, add_assoc, nat.not_lt_zero, fin.nat_add_mk, add_lt_iff_neg_left, add_tsub_cancel_left, fin.succ_mk, dif_neg, not_false_iff, fin.coe_mk] end /-- Append two composition series `s₁` and `s₂` such that the least element of `s₁` is the maximum element of `s₂`. -/ @[simps length] def append (s₁ s₂ : composition_series X) (h : s₁.top = s₂.bot) : composition_series X := { length := s₁.length + s₂.length, series := fin.append (nat.add_succ _ _).symm (s₁ ∘ fin.cast_succ) s₂, step' := λ i, begin refine fin.add_cases _ _ i, { intro i, rw [append_succ_cast_add_aux _ h, append_cast_add_aux], exact s₁.step i }, { intro i, rw [append_nat_add_aux, append_succ_nat_add_aux], exact s₂.step i } end } @[simp] lemma append_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).cast_succ = s₁ i.cast_succ := append_cast_add_aux i @[simp] lemma append_succ_cast_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₁.length) : append s₁ s₂ h (fin.cast_add s₂.length i).succ = s₁ i.succ := append_succ_cast_add_aux i h @[simp] lemma append_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).cast_succ = s₂ i.cast_succ := append_nat_add_aux i @[simp] lemma append_succ_nat_add {s₁ s₂ : composition_series X} (h : s₁.top = s₂.bot) (i : fin s₂.length) : append s₁ s₂ h (fin.nat_add s₁.length i).succ = s₂ i.succ := append_succ_nat_add_aux i /-- Add an element to the top of a `composition_series` -/ @[simps length] def snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : composition_series X := { length := s.length + 1, series := fin.snoc s x, step' := λ i, begin refine fin.last_cases _ _ i, { rwa [fin.snoc_cast_succ, fin.succ_last, fin.snoc_last, ← top] }, { intro i, rw [fin.snoc_cast_succ, ← fin.cast_succ_fin_succ, fin.snoc_cast_succ], exact s.step _ } end } @[simp] lemma top_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).top = x := fin.snoc_last _ _ @[simp] lemma snoc_last (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : snoc s x hsat (fin.last (s.length + 1)) = x := fin.snoc_last _ _ @[simp] lemma snoc_cast_succ (s : composition_series X) (x : X) (hsat : is_maximal s.top x) (i : fin (s.length + 1)) : snoc s x hsat (i.cast_succ) = s i := fin.snoc_cast_succ _ _ _ @[simp] lemma bot_snoc (s : composition_series X) (x : X) (hsat : is_maximal s.top x) : (snoc s x hsat).bot = s.bot := by rw [bot, bot, ← fin.cast_succ_zero, snoc_cast_succ] lemma mem_snoc {s : composition_series X} {x y: X} {hsat : is_maximal s.top x} : y ∈ snoc s x hsat ↔ y ∈ s ∨ y = x := begin simp only [snoc, mem_def], split, { rintros ⟨i, rfl⟩, refine fin.last_cases _ (λ i, _) i, { right, simp }, { left, simp } }, { intro h, rcases h with ⟨i, rfl⟩ | rfl, { use i.cast_succ, simp }, { use (fin.last _), simp } } end lemma eq_snoc_erase_top {s : composition_series X} (h : 0 < s.length) : s = snoc (erase_top s) s.top (is_maximal_erase_top_top h) := begin ext x, simp [mem_snoc, mem_erase_top h], by_cases h : x = s.top; simp [*, s.top_mem] end @[simp] lemma snoc_erase_top_top {s : composition_series X} (h : is_maximal s.erase_top.top s.top) : s.erase_top.snoc s.top h = s := have h : 0 < s.length, from nat.pos_of_ne_zero begin assume hs, refine ne_of_gt (lt_of_is_maximal h) _, simp [top, fin.ext_iff, hs] end, (eq_snoc_erase_top h).symm /-- Two `composition_series X`, `s₁` and `s₂` are equivalent if there is a bijection `e : fin s₁.length ≃ fin s₂.length` such that for any `i`, `iso (s₁ i) (s₁ i.succ) (s₂ (e i), s₂ (e i.succ))` -/ def equivalent (s₁ s₂ : composition_series X) : Prop := ∃ f : fin s₁.length ≃ fin s₂.length, ∀ i : fin s₁.length, iso (s₁ i.cast_succ, s₁ i.succ) (s₂ (f i).cast_succ, s₂ (f i).succ) namespace equivalent @[refl] lemma refl (s : composition_series X) : equivalent s s := ⟨equiv.refl _, λ _, (s.step _).iso_refl⟩ @[symm] lemma symm {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : equivalent s₂ s₁ := ⟨h.some.symm, λ i, iso_symm (by simpa using h.some_spec (h.some.symm i))⟩ @[trans] lemma trans {s₁ s₂ s₃ : composition_series X} (h₁ : equivalent s₁ s₂) (h₂ : equivalent s₂ s₃) : equivalent s₁ s₃ := ⟨h₁.some.trans h₂.some, λ i, iso_trans (h₁.some_spec i) (h₂.some_spec (h₁.some i))⟩ lemma append {s₁ s₂ t₁ t₂ : composition_series X} (hs : s₁.top = s₂.bot) (ht : t₁.top = t₂.bot) (h₁ : equivalent s₁ t₁) (h₂ : equivalent s₂ t₂) : equivalent (append s₁ s₂ hs) (append t₁ t₂ ht) := let e : fin (s₁.length + s₂.length) ≃ fin (t₁.length + t₂.length) := calc fin (s₁.length + s₂.length) ≃ fin s₁.length ⊕ fin s₂.length : fin_sum_fin_equiv.symm ... ≃ fin t₁.length ⊕ fin t₂.length : equiv.sum_congr h₁.some h₂.some ... ≃ fin (t₁.length + t₂.length) : fin_sum_fin_equiv in ⟨e, begin assume i, refine fin.add_cases _ _ i, { assume i, simpa [top, bot] using h₁.some_spec i }, { assume i, simpa [top, bot] using h₂.some_spec i } end⟩ protected lemma snoc {s₁ s₂ : composition_series X} {x₁ x₂ : X} {hsat₁ : is_maximal s₁.top x₁} {hsat₂ : is_maximal s₂.top x₂} (hequiv : equivalent s₁ s₂) (htop : iso (s₁.top, x₁) (s₂.top, x₂)) : equivalent (s₁.snoc x₁ hsat₁) (s₂.snoc x₂ hsat₂) := let e : fin s₁.length.succ ≃ fin s₂.length.succ := calc fin (s₁.length + 1) ≃ option (fin s₁.length) : fin_succ_equiv_last ... ≃ option (fin s₂.length) : functor.map_equiv option hequiv.some ... ≃ fin (s₂.length + 1) : fin_succ_equiv_last.symm in ⟨e, λ i, begin refine fin.last_cases _ _ i, { simpa [top] using htop }, { assume i, simpa [fin.succ_cast_succ] using hequiv.some_spec i } end⟩ lemma length_eq {s₁ s₂ : composition_series X} (h : equivalent s₁ s₂) : s₁.length = s₂.length := by simpa using fintype.card_congr h.some lemma snoc_snoc_swap {s : composition_series X} {x₁ x₂ y₁ y₂ : X} {hsat₁ : is_maximal s.top x₁} {hsat₂ : is_maximal s.top x₂} {hsaty₁ : is_maximal (snoc s x₁ hsat₁).top y₁} {hsaty₂ : is_maximal (snoc s x₂ hsat₂).top y₂} (hr₁ : iso (s.top, x₁) (x₂, y₂)) (hr₂ : iso (x₁, y₁) (s.top, x₂)) : equivalent (snoc (snoc s x₁ hsat₁) y₁ hsaty₁) (snoc (snoc s x₂ hsat₂) y₂ hsaty₂) := let e : fin (s.length + 1 + 1) ≃ fin (s.length + 1 + 1) := equiv.swap (fin.last _) (fin.cast_succ (fin.last _)) in have h1 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _).cast_succ, from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), have h2 : ∀ {i : fin s.length}, i.cast_succ.cast_succ ≠ (fin.last _), from λ _, ne_of_lt (by simp [fin.cast_succ_lt_last]), ⟨e, begin intro i, dsimp only [e], refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_left, snoc_cast_succ, snoc_last, fin.succ_last, snoc_last, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last], exact hr₂ }, { refine fin.last_cases _ (λ i, _) i, { erw [equiv.swap_apply_right, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_last, snoc_last, snoc_last, fin.succ_last, snoc_last], exact hr₁ }, { erw [equiv.swap_apply_of_ne_of_ne h2 h1, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, fin.succ_cast_succ, snoc_cast_succ, snoc_cast_succ, snoc_cast_succ], exact (s.step i).iso_refl } } end⟩ end equivalent lemma length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁ : s₁.length = 0) : s₂.length = 0 := begin have : s₁.bot = s₁.top, from congr_arg s₁ (fin.ext (by simp [hs₁])), have : (fin.last s₂.length) = (0 : fin s₂.length.succ), from s₂.injective (hb.symm.trans (this.trans ht)).symm, simpa [fin.ext_iff] end lemma length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : 0 < s₁.length → 0 < s₂.length := not_imp_not.1 begin simp only [pos_iff_ne_zero, ne.def, not_iff_not, not_not], exact length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb.symm ht.symm end lemma eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero {s₁ s₂ : composition_series X} (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) (hs₁0 : s₁.length = 0) : s₁ = s₂ := have ∀ x, x ∈ s₁ ↔ x = s₁.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero hs₁0 hx s₁.top_mem, λ hx, hx.symm ▸ s₁.top_mem⟩, have ∀ x, x ∈ s₂ ↔ x = s₂.top, from λ x, ⟨λ hx, forall_mem_eq_of_length_eq_zero (length_eq_zero_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hs₁0) hx s₂.top_mem, λ hx, hx.symm ▸ s₂.top_mem⟩, by { ext, simp * } /-- Given a `composition_series`, `s`, and an element `x` such that `x` is maximal inside `s.top` there is a series, `t`, such that `t.top = x`, `t.bot = s.bot` and `snoc t s.top _` is equivalent to `s`. -/ lemma exists_top_eq_snoc_equivalant (s : composition_series X) (x : X) (hm : is_maximal x s.top) (hb : s.bot ≤ x) : ∃ t : composition_series X, t.bot = s.bot ∧ t.length + 1 = s.length ∧ ∃ htx : t.top = x, equivalent s (snoc t s.top (htx.symm ▸ hm)) := begin induction hn : s.length with n ih generalizing s x, { exact (ne_of_gt (lt_of_le_of_lt hb (lt_of_is_maximal hm)) (forall_mem_eq_of_length_eq_zero hn s.top_mem s.bot_mem)).elim }, { have h0s : 0 < s.length, from hn.symm ▸ nat.succ_pos _, by_cases hetx : s.erase_top.top = x, { use s.erase_top, simp [← hetx, hn] }, { have imxs : is_maximal (x ⊓ s.erase_top.top) s.erase_top.top, from is_maximal_of_eq_inf x s.top rfl (ne.symm hetx) hm (is_maximal_erase_top_top h0s), have := ih _ _ imxs (le_inf (by simpa) (le_top_of_mem s.erase_top.bot_mem)) (by simp [hn]), rcases this with ⟨t, htb, htl, htt, hteqv⟩, have hmtx : is_maximal t.top x, from is_maximal_of_eq_inf s.erase_top.top s.top (by rw [inf_comm, htt]) hetx (is_maximal_erase_top_top h0s) hm, use snoc t x hmtx, refine ⟨by simp [htb], by simp [htl], by simp, _⟩, have : s.equivalent ((snoc t s.erase_top.top (htt.symm ▸ imxs)).snoc s.top (by simpa using is_maximal_erase_top_top h0s)), { conv_lhs { rw eq_snoc_erase_top h0s }, exact equivalent.snoc hteqv (by simpa using (is_maximal_erase_top_top h0s).iso_refl) }, refine this.trans _, refine equivalent.snoc_snoc_swap _ _, { exact iso_symm (second_iso_of_eq hm (sup_eq_of_is_maximal hm (is_maximal_erase_top_top h0s) (ne.symm hetx)) htt.symm) }, { exact second_iso_of_eq (is_maximal_erase_top_top h0s) (sup_eq_of_is_maximal (is_maximal_erase_top_top h0s) hm hetx) (by rw [inf_comm, htt]) } } } end /-- The **Jordan-Hölder** theorem, stated for any `jordan_holder_lattice`. If two composition series start and finish at the same place, they are equivalent. -/ theorem jordan_holder (s₁ s₂ : composition_series X) (hb : s₁.bot = s₂.bot) (ht : s₁.top = s₂.top) : equivalent s₁ s₂ := begin induction hle : s₁.length with n ih generalizing s₁ s₂, { rw [eq_of_bot_eq_bot_of_top_eq_top_of_length_eq_zero hb ht hle] }, { have h0s₂ : 0 < s₂.length, from length_pos_of_bot_eq_bot_of_top_eq_top_of_length_pos hb ht (hle.symm ▸ nat.succ_pos _), rcases exists_top_eq_snoc_equivalant s₁ s₂.erase_top.top (ht.symm ▸ is_maximal_erase_top_top h0s₂) (hb.symm ▸ s₂.bot_erase_top ▸ bot_le_of_mem (top_mem _)) with ⟨t, htb, htl, htt, hteq⟩, have := ih t s₂.erase_top (by simp [htb, ← hb]) htt (nat.succ_inj'.1 (htl.trans hle)), refine hteq.trans _, conv_rhs { rw [eq_snoc_erase_top h0s₂] }, simp only [ht], exact equivalent.snoc this (by simp [htt, (is_maximal_erase_top_top h0s₂).iso_refl]) } end end composition_series
3d913cffc26f65a732148b761b44d966d11c6cff
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/polynomial/div.lean
2f68b60bb390a54c4aa9839c327988f4c9b1f707
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,689
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.monic import ring_theory.multiplicity /-! # Division of univariate polynomials The main defs are `div_by_monic` and `mod_by_monic`. The compatibility between these is given by `mod_by_monic_add_div`. We also define `root_multiplicity`. -/ noncomputable theory open_locale classical big_operators open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : polynomial α} : X ∣ f ↔ f.coeff 0 = 0 := ⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero], λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩ end comm_semiring section comm_semiring variables [comm_semiring R] {p q : polynomial R} lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one h; exact hq (subsingleton.elim _ _), ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section ring variables [ring R] {p q : polynomial R} lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne h.2, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [hq.degree_mul, degree_C_mul_X_pow _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul_monic hq, leading_coeff_mul_X_pow, leading_coeff_C]) /-- See `div_by_monic`. -/ noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R}, monic q → polynomial R × polynomial R | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial R) : polynomial R := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt [nontrivial R] : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), degree (p %ₘ q) < degree q | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq.ne_zero)), end using_well_founded {dec_tac := tactic.assumption} @[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 := if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff [nontrivial R] (hq : monic q) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R} (hq : monic q) : degree (p %ₘ q) ≤ degree q := by { nontriviality R, exact (degree_mod_by_monic_lt _ hq).le } end ring section comm_ring variables [comm_ring R] {p q : polynomial R} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma div_by_monic_eq_zero_iff [nontrivial R] (hq : monic q) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := begin nontriviality R, have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq ... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_right_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) end lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then if h : degree q ≤ degree p then by haveI := nontrivial.of_polynomial_ne hp0; rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := if hpq : degree p < degree q then begin haveI := nontrivial.of_polynomial_ne hp0, rw [(div_by_monic_eq_zero_iff hq).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_coe _ end else begin haveI := nontrivial.of_polynomial_ne hp0, rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq.ne_zero) ▸ h0q)) end theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : polynomial R) {g : polynomial R} (hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g := begin by_cases h01 : (0 : R) = 1, { haveI := subsingleton_of_zero_eq_one h01, rw [subsingleton.elim (f /ₘ g) 0, subsingleton.elim f 0, subsingleton.elim g 0, nat_degree_zero] }, haveI : nontrivial R := ⟨⟨0, 1, h01⟩⟩, by_cases hfg : f /ₘ g = 0, { rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg at hfg, rw nat.sub_eq_zero_of_le (nat_degree_le_nat_degree $ le_of_lt hfg) }, have hgf := hfg, rw div_by_monic_eq_zero_iff hg at hgf, push_neg at hgf, have := degree_add_div_by_monic hg hgf, have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] }, rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg, ← with_bot.coe_add, with_bot.coe_eq_coe] at this, rw [← this, nat.add_sub_cancel_left] end lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := begin nontriviality R, have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (f %ₘ g)) : degree_sub_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, degree_mod_by_monic_lt _ hg⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul']; simpa [monic.def.1 hg]), exact ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ end lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := begin nontriviality S, haveI : nontrivial R := f.domain_nontrivial, have : map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), { exact (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq) ⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ _ ... < degree q : degree_mod_by_monic_lt _ hq ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, f.map_one]; exact one_ne_zero)⟩) }, exact ⟨this.1.symm, this.2.symm⟩ end lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, begin nontriviality R, obtain ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h, by_contradiction hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q), { rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr] }, have : degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this, exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this) end⟩ theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : polynomial R} (hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y := begin rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (monic_map f hx), ← map_mod_by_monic f hx], exact ⟨λ H, map_injective f hf $ by rw [H, map_zero], λ H, by rw [H, map_zero]⟩ end @[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p %ₘ (X - C a) = C (p.eval a) := begin nontriviality R, have h : (p %ₘ (X - C a)).eval a = p.eval a, { rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero] }, have : degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a), have : degree (p %ₘ (X - C a)) ≤ 0, { cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } }, rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] lemma eval₂_mod_by_monic_eq_self_of_root [comm_ring S] {f : R →+* S} {p q : polynomial R} (hq : q.monic) {x : S} (hx : q.eval₂ f x = 0) : (p %ₘ q).eval₂ f x = p.eval₂ f x := by rw [mod_by_monic_eq_sub_mul_div p hq, eval₂_sub, eval₂_mul, hx, zero_mul, sub_zero] section multiplicity /-- An algorithm for deciding polynomial divisibility. The algorithm is "compute `p %ₘ q` and compare to `0`". ` See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`. -/ def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := multiplicity_finite_of_degree_pos_of_monic (have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one h; exact h0 (subsingleton.elim _ _)), by haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩; rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) h0 /-- The largest power of `X - C a` which divides `p`. This is computable via the divisibility algorithm `decidable_dvd_monic`. -/ def root_multiplicity (a : R) (p : polynomial R) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, part.dom]; congr; funext; congr @[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) : root_multiplicity x p = 0 := begin rw root_multiplicity_eq_multiplicity, split_ifs, { refl }, rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, nat.cast_zero], intro hdvd, exact h (dvd_iff_is_root.mp hdvd) end lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := begin rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_lt_coe, enat.coe_get], exact multiplicity.dvd_iff_multiplicity_pos end lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : polynomial R) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from monic_pow (monic_X_sub_C _) _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : polynomial R} (a : R) (hp : p ≠ 0) : eval a (p /ₘ ((X - C a) ^ root_multiplicity a p)) ≠ 0 := begin haveI : nontrivial R := nontrivial.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring end polynomial
024379571403bdd0fd0c03caca15144ccbe7ccb9
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/meta/well_founded_tactics.lean
e31dbdbb7c845af1d3a36a59d37c94fc98c558f9
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
6,502
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 -/ prelude import init.meta init.data.sigma.lex init.data.nat.lemmas init.data.list.instances import init.data.list.qsort /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_of_zero_lt_left (a b : nat) (h : 0 < b) : a < a + b := show a + 0 < a + b, by {apply nat.add_lt_add_left, assumption} /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.zero_lt_one_add (a : nat) : 0 < 1 + a := suffices 0 < a + 1, by {simp [nat.add_comm], assumption}, nat.zero_lt_succ _ /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_right (a b c : nat) : a < b → a < b + c := λ h, lt_of_lt_of_le h (nat.le_add_right _ _) /- TODO(Leo): move this lemma, or delete it after we add algebraic normalizer. -/ lemma nat.lt_add_left (a b c : nat) : a < b → a < c + b := λ h, lt_of_lt_of_le h (nat.le_add_left _ _) namespace well_founded_tactics open tactic private meta def clear_wf_rec_goal_aux : list expr → tactic unit | [] := return () | (h::hs) := clear_wf_rec_goal_aux hs >> try (guard (h.local_pp_name.is_internal || h.is_aux_decl) >> clear h) meta def clear_internals : tactic unit := local_context >>= clear_wf_rec_goal_aux meta def unfold_wf_rel : tactic unit := dunfold_target [``has_well_founded.r] {fail_if_unchanged := ff} meta def is_psigma_mk : expr → tactic (expr × expr) | `(psigma.mk %%a %%b) := return (a, b) | _ := failed meta def process_lex : tactic unit → tactic unit | tac := do t ← target >>= whnf, if t.is_napp_of `psigma.lex 6 then let a := t.app_fn.app_arg in let b := t.app_arg in do (a₁, a₂) ← is_psigma_mk a, (b₁, b₂) ← is_psigma_mk b, (is_def_eq a₁ b₁ >> `[apply psigma.lex.right] >> process_lex tac) <|> (`[apply psigma.lex.left] >> tac) else tac private meta def unfold_sizeof_measure : tactic unit := dunfold_target [``sizeof_measure, ``measure, ``inv_image] {fail_if_unchanged := ff} private meta def add_simps : simp_lemmas → list name → tactic simp_lemmas | s [] := return s | s (n::ns) := do s' ← s.add_simp n ff, add_simps s' ns private meta def collect_sizeof_lemmas (e : expr) : tactic simp_lemmas := e.mfold simp_lemmas.mk $ λ c d s, if c.is_constant then match c.const_name with | name.mk_string "sizeof" p := do eqns ← get_eqn_lemmas_for tt c.const_name, add_simps s eqns | _ := return s end else return s private meta def unfold_sizeof_loop : tactic unit := do dunfold_target [``sizeof, ``has_sizeof.sizeof] {fail_if_unchanged := ff}, S ← target >>= collect_sizeof_lemmas, (simp_target S >> unfold_sizeof_loop) <|> try `[simp] meta def unfold_sizeof : tactic unit := unfold_sizeof_measure >> unfold_sizeof_loop /- The following section should be removed as soon as we implement the algebraic normalizer. -/ section simple_dec_tac open tactic expr private meta def collect_add_args : expr → list expr | `(%%a + %%b) := collect_add_args a ++ collect_add_args b | e := [e] private meta def mk_nat_add : list expr → tactic expr | [] := to_expr ``(0) | [a] := return a | (a::as) := do rs ← mk_nat_add as, to_expr ``(%%a + %%rs) private meta def mk_nat_add_add : list expr → list expr → tactic expr | [] b := mk_nat_add b | a [] := mk_nat_add a | a b := do t ← mk_nat_add a, s ← mk_nat_add b, to_expr ``(%%t + %%s) private meta def get_add_fn (e : expr) : expr := if is_napp_of e `has_add.add 4 then e.app_fn.app_fn else e private meta def prove_eq_by_perm (a b : expr) : tactic expr := (is_def_eq a b >> to_expr ``(eq.refl %%a)) <|> perm_ac (get_add_fn a) `(nat.add_assoc) `(nat.add_comm) a b private meta def num_small_lt (a b : expr) : bool := if a = b then ff else if is_napp_of a `has_one.one 2 then tt else if is_napp_of b `has_one.one 2 then ff else a.lt b private meta def sort_args (args : list expr) : list expr := args.qsort num_small_lt meta def cancel_nat_add_lt : tactic unit := do `(%%lhs < %%rhs) ← target, ty ← infer_type lhs >>= whnf, guard (ty = `(nat)), let lhs_args := collect_add_args lhs, let rhs_args := collect_add_args rhs, let common := lhs_args.bag_inter rhs_args, if common = [] then return () else do let lhs_rest := lhs_args.diff common, let rhs_rest := rhs_args.diff common, new_lhs ← mk_nat_add_add common (sort_args lhs_rest), new_rhs ← mk_nat_add_add common (sort_args rhs_rest), lhs_pr ← prove_eq_by_perm lhs new_lhs, rhs_pr ← prove_eq_by_perm rhs new_rhs, target_pr ← to_expr ``(congr (congr_arg (<) %%lhs_pr) %%rhs_pr), new_target ← to_expr ``(%%new_lhs < %%new_rhs), replace_target new_target target_pr, `[apply nat.add_lt_add_left] <|> `[apply nat.lt_add_of_zero_lt_left] meta def check_target_is_value_lt : tactic unit := do `(%%lhs < %%rhs) ← target, guard lhs.is_numeral meta def trivial_nat_lt : tactic unit := comp_val <|> `[apply nat.zero_lt_one_add] <|> assumption <|> (do check_target_is_value_lt, (`[apply nat.lt_add_right] >> trivial_nat_lt) <|> (`[apply nat.lt_add_left] >> trivial_nat_lt)) <|> failed end simple_dec_tac meta def default_dec_tac : tactic unit := abstract $ do clear_internals, unfold_wf_rel, -- The next line was adapted from code in mathlib by Scott Morrison. -- Because `unfold_sizeof` could actually discharge the goal, add a test -- using `done` to detect this. process_lex (unfold_sizeof >> (done <|> (cancel_nat_add_lt >> trivial_nat_lt))) end well_founded_tactics /-- Argument for using_well_founded The tactic `rel_tac` has to synthesize an element of type (has_well_founded A). The two arguments are: a local representing the function being defined by well founded recursion, and a list of recursive equations. The equations can be used to decide which well founded relation should be used. The tactic `dec_tac` has to synthesize decreasing proofs. -/ meta structure well_founded_tactics := (rel_tac : expr → list expr → tactic unit := λ _ _, tactic.apply_instance) (dec_tac : tactic unit := well_founded_tactics.default_dec_tac) meta def well_founded_tactics.default : well_founded_tactics := {}
937491bfc2556f9676cc9e994743ea8a010049a6
ea11767c9c6a467c4b7710ec6f371c95cfc023fd
/src/monoidal_categories/lemmas/pentagon_in_terms_of_natural_transformations_definitions.lean
578c9f4c55808dd289296b1569bf8f6835e7b581
[]
no_license
RitaAhmadi/lean-monoidal-categories
68a23f513e902038e44681336b87f659bbc281e0
81f43e1e0d623a96695aa8938951d7422d6d7ba6
refs/heads/master
1,651,458,686,519
1,529,824,613,000
1,529,824,613,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,047
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..monoidal_category import categories.functor_categories.whiskering open categories open categories.functor open categories.products open categories.natural_transformation open categories.functor_categories namespace categories.monoidal_category universe variables u v variables (C : Type u) [𝒞 : monoidal_category.{u v} C] include 𝒞 open monoidal_category @[reducible] definition pentagon_3step_1 := let α := associator_transformation C in whisker_on_right (α.morphism × IdentityNaturalTransformation (IdentityFunctor C)) 𝒞.tensor @[reducible] definition pentagon_3step_2 := let α := associator_transformation C in whisker_on_left (FunctorComposition (ProductCategoryAssociator C C C × IdentityFunctor C) ((IdentityFunctor C × tensor C) × IdentityFunctor C)) α.morphism @[reducible] definition pentagon_3step_3 := let α := associator_transformation C in whisker_on_left (FunctorComposition (ProductCategoryAssociator C C C × IdentityFunctor C) (ProductCategoryAssociator C (C × C) C)) (whisker_on_right (IdentityNaturalTransformation (IdentityFunctor C) × α.morphism) (tensor C)) @[reducible] definition pentagon_3step := (pentagon_3step_1 C) ⊟ (pentagon_3step_2 C) ⊟ (pentagon_3step_3 C) @[reducible] definition pentagon_2step_1 := let α := associator_transformation C in whisker_on_left ((tensor C × IdentityFunctor C) × IdentityFunctor C) α.morphism @[reducible] definition pentagon_2step_2 := let α := associator_transformation C in whisker_on_left (FunctorComposition (ProductCategoryAssociator (C × C) C C) (IdentityFunctor (C × C) × tensor C)) α.morphism @[reducible] definition pentagon_2step := (pentagon_2step_1 C) ⊟ (pentagon_2step_2 C) end categories.monoidal_category
4abf7a2f80af3305b4f7d1dd097bd5e296258152
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/system/random/basic.lean
e0bcbb06cb015891d6dc88053662c6739b24c8de
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
9,904
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.group_power.default import Mathlib.control.uliftable import Mathlib.control.monad.basic import Mathlib.data.bitvec.basic import Mathlib.data.list.basic import Mathlib.data.set.intervals.basic import Mathlib.data.stream.basic import Mathlib.data.fin import Mathlib.tactic.cache import Mathlib.tactic.interactive import Mathlib.tactic.norm_num import Mathlib.Lean3Lib.system.io import Mathlib.Lean3Lib.system.random import Mathlib.PostPort universes u u_1 v l namespace Mathlib /-! # Rand Monad and Random Class This module provides tools for formulating computations guided by randomness and for defining objects that can be created randomly. ## Main definitions * `rand` monad for computations guided by randomness; * `random` class for objects that can be generated randomly; * `random` to generate one object; * `random_r` to generate one object inside a range; * `random_series` to generate an infinite series of objects; * `random_series_r` to generate an infinite series of objects inside a range; * `io.mk_generator` to create a new random number generator; * `io.run_rand` to run a randomized computation inside the `io` monad; * `tactic.run_rand` to run a randomized computation inside the `tactic` monad ## Local notation * `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively; ## Tags random monad io ## References * Similar library in Haskell: https://hackage.haskell.org/package/MonadRandom -/ /-- A monad to generate random objects using the generator type `g` -/ def rand_g (g : Type) (α : Type u) := state (ulift g) α /-- A monad to generate random objects using the generator type `std_gen` -/ def rand (α : Type u_1) := rand_g std_gen protected instance rand_g.uliftable (g : Type) : uliftable (rand_g g) (rand_g g) := state_t.uliftable' (equiv.trans equiv.ulift (equiv.symm equiv.ulift)) /-- Generate one more `ℕ` -/ def rand_g.next {g : Type} [random_gen g] : rand_g g ℕ := state_t.mk (prod.map id ulift.up ∘ random_gen.next ∘ ulift.down) /-- `bounded_random α` gives us machinery to generate values of type `α` between certain bounds -/ class bounded_random (α : Type u) [preorder α] where random_r : (g : Type) → [_inst_1_1 : random_gen g] → (x y : α) → x ≤ y → rand_g g ↥(set.Icc x y) /-- `random α` gives us machinery to generate values of type `α` -/ class random (α : Type u) where random : (g : Type) → [_inst_1 : random_gen g] → rand_g g α /-- shift_31_left = 2^31; multiplying by it shifts the binary representation of a number left by 31 bits, dividing by it shifts it right by 31 bits -/ def shift_31_left : ℕ := bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 (bit0 1)))))))))))))))))))))))))))))) namespace rand /-- create a new random number generator distinct from the one stored in the state -/ def split (g : Type) [random_gen g] : rand_g g g := state_t.mk (prod.map id ulift.up ∘ random_gen.split ∘ ulift.down) /-- Generate a random value of type `α`. -/ def random (α : Type u) {g : Type} [random_gen g] [random α] : rand_g g α := random α g /-- generate an infinite series of random values of type `α` -/ def random_series (α : Type u) {g : Type} [random_gen g] [random α] : rand_g g (stream α) := do let gen ← uliftable.up (split g) pure (stream.corec_state (random α g) gen) /-- Generate a random value between `x` and `y` inclusive. -/ def random_r {α : Type u} {g : Type} [random_gen g] [preorder α] [bounded_random α] (x : α) (y : α) (h : x ≤ y) : rand_g g ↥(set.Icc x y) := bounded_random.random_r g x y h /-- generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ def random_series_r {α : Type u} {g : Type} [random_gen g] [preorder α] [bounded_random α] (x : α) (y : α) (h : x ≤ y) : rand_g g (stream ↥(set.Icc x y)) := do let gen ← uliftable.up (split g) pure (stream.corec_state (bounded_random.random_r g x y h) gen) end rand namespace io /-- create and a seed a random number generator -/ def mk_generator : io std_gen := do let seed ← rand 0 shift_31_left return (mk_std_gen seed) /-- Run `cmd` using a randomly seeded random number generator -/ def run_rand {α : Type} (cmd : rand α) : io α := do let g ← mk_generator return (prod.fst (state_t.run cmd (ulift.up g))) /-- Run `cmd` using the provided seed. -/ def run_rand_with {α : Type} (seed : ℕ) (cmd : rand α) : io α := return (prod.fst (state_t.run cmd (ulift.up (mk_std_gen seed)))) /-- randomly generate a value of type α -/ def random {α : Type} [random α] : io α := run_rand (rand.random α) /-- randomly generate an infinite series of value of type α -/ def random_series {α : Type} [random α] : io (stream α) := run_rand (rand.random_series α) /-- randomly generate a value of type α between `x` and `y` -/ def random_r {α : Type} [preorder α] [bounded_random α] (x : α) (y : α) (p : x ≤ y) : io ↥(set.Icc x y) := run_rand (bounded_random.random_r std_gen x y p) /-- randomly generate an infinite series of value of type α between `x` and `y` -/ def random_series_r {α : Type} [preorder α] [bounded_random α] (x : α) (y : α) (h : x ≤ y) : io (stream ↥(set.Icc x y)) := run_rand (rand.random_series_r x y h) end io namespace tactic /-- create a seeded random number generator in the `tactic` monad -/ /-- run `cmd` using the a randomly seeded random number generator in the tactic monad -/ /-- Generate a random value between `x` and `y` inclusive. -/ /-- Generate an infinite series of random values of type `α` between `x` and `y` inclusive. -/ /-- randomly generate a value of type α -/ end tactic namespace fin /-- generate a `fin` randomly -/ protected def random {g : Type} [random_gen g] {n : ℕ} [fact (0 < n)] : rand_g g (fin n) := state_t.mk fun (_x : ulift g) => sorry end fin protected instance nat_bounded_random : bounded_random ℕ := bounded_random.mk fun (g : Type) (inst : random_gen g) (x y : ℕ) (hxy : x ≤ y) => do let z ← fin.random pure { val := subtype.val z + x, property := sorry } /-- This `bounded_random` interval generates integers between `x` and `y` by first generating a natural number between `0` and `y - x` and shifting the result appropriately. -/ protected instance int_bounded_random : bounded_random ℤ := bounded_random.mk fun (g : Type) (inst : random_gen g) (x y : ℤ) (hxy : x ≤ y) => do bounded_random.random_r g 0 (int.nat_abs (y - x)) sorry sorry protected instance fin_random (n : ℕ) [fact (0 < n)] : random (fin n) := random.mk fun (g : Type) (inst : random_gen g) => fin.random protected instance fin_bounded_random (n : ℕ) : bounded_random (fin n) := bounded_random.mk fun (g : Type) (inst : random_gen g) (x y : fin n) (p : x ≤ y) => do rand.random_r (subtype.val x) (subtype.val y) p sorry /-- A shortcut for creating a `random (fin n)` instance from a proof that `0 < n` rather than on matching on `fin (succ n)` -/ def random_fin_of_pos {n : ℕ} (h : 0 < n) : random (fin n) := sorry theorem bool_of_nat_mem_Icc_of_mem_Icc_to_nat (x : Bool) (y : Bool) (n : ℕ) : n ∈ set.Icc (bool.to_nat x) (bool.to_nat y) → bool.of_nat n ∈ set.Icc x y := sorry protected instance bool.random : random Bool := random.mk fun (g : Type) (inst : random_gen g) => (bool.of_nat ∘ subtype.val) <$> bounded_random.random_r g 0 1 sorry protected instance bool.bounded_random : bounded_random Bool := bounded_random.mk fun (g : Type) (_inst : random_gen g) (x y : Bool) (p : x ≤ y) => subtype.map bool.of_nat (bool_of_nat_mem_Icc_of_mem_Icc_to_nat x y) <$> bounded_random.random_r g (bool.to_nat x) (bool.to_nat y) (bool.to_nat_le_to_nat p) /-- generate a random bit vector of length `n` -/ def bitvec.random {g : Type} [random_gen g] (n : ℕ) : rand_g g (bitvec n) := bitvec.of_fin <$> rand.random (fin (bit0 1 ^ n)) /-- generate a random bit vector of length `n` -/ def bitvec.random_r {g : Type} [random_gen g] {n : ℕ} (x : bitvec n) (y : bitvec n) (h : x ≤ y) : rand_g g ↥(set.Icc x y) := (fun (h' : ∀ (a : fin (bit0 1 ^ n)), a ∈ set.Icc (bitvec.to_fin x) (bitvec.to_fin y) → bitvec.of_fin a ∈ set.Icc x y) => subtype.map bitvec.of_fin h' <$> rand.random_r (bitvec.to_fin x) (bitvec.to_fin y) (bitvec.to_fin_le_to_fin_of_le h)) sorry protected instance random_bitvec (n : ℕ) : random (bitvec n) := random.mk fun (_x : Type) (inst : random_gen _x) => bitvec.random n protected instance bounded_random_bitvec (n : ℕ) : bounded_random (bitvec n) := bounded_random.mk fun (_x : Type) (inst : random_gen _x) (x y : bitvec n) (p : x ≤ y) => bitvec.random_r x y p
e136851533e1428f78c04f0bc21a98b653613a1c
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/set/basic.lean
6c049e5222dc854e11ec98e3063b96bfff2a64f4
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
62,206
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import tactic.basic tactic.finish data.subtype logic.unique open function /-! # Basic properties of sets This file provides some basic definitions related to sets and functions (e.g., `preimage`) not present in the core library, as well as extra lemmas. -/ /-! ### Set coercion to a type -/ namespace set instance {α : Type*} : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ end set section set_coe universe u variables {α : Type u} theorem set.set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl theorem set_coe.ext {s : set α} {a b : s} : (↑a : α) = ↑b → a = b := subtype.eq theorem set_coe.ext_iff {s : set α} {a b : s} : (↑a : α) = ↑b ↔ a = b := iff.intro set_coe.ext (assume h, h ▸ rfl) end set_coe lemma subtype.mem {α : Type*} {s : set α} (p : s) : (p : α) ∈ s := p.property namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[ext] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨λ h x, by rw h, ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /-! ### Lemmas about `mem` and `set_of` -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl lemma set_of_app_iff {p : α → Prop} {x : α} : { x | p x } x ↔ p x := iff.rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl @[simp] lemma sep_set_of {α} {p q : α → Prop} : {a ∈ {a | p a } | q a} = {a | p a ∧ q a} := rfl @[simp] lemma set_of_mem {α} {s : set α} : {a | a ∈ s} = s := rfl /-! #### Lemmas about subsets -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a ∈ s, a ∉ t := by simp [subset_def, classical.not_forall] /-! ### Definition of strict subsets `s ⊂ t` and basic properties. -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ ¬ (t ⊆ s) instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ ¬ (t ⊆ s)) := rfl theorem eq_or_ssubset_of_subset (h : s ⊆ t) : s = t ∨ s ⊂ t := classical.by_cases (λ H : t ⊆ s, or.inl $ subset.antisymm h H) (λ H, or.inr ⟨h, H⟩) lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := not_subset.1 h.2 lemma ssubset_iff_subset_ne {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /-! ### Non-empty sets -/ /-- The property `s.nonempty` expresses the fact that the set `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : set α) : Prop := ∃ x, x ∈ s lemma nonempty_of_mem {x} (h : x ∈ s) : s.nonempty := ⟨x, h⟩ theorem nonempty.ne_empty : s.nonempty → s ≠ ∅ | ⟨x, hx⟩ hs := by { rw hs at hx, exact hx } /-- Extract a witness from `s.nonempty`. This function might be used instead of case analysis on the argument. Note that it makes a proof depend on the `classical.choice` axiom. -/ protected noncomputable def nonempty.some (h : s.nonempty) : α := classical.some h protected lemma nonempty.some_mem (h : s.nonempty) : h.some ∈ s := classical.some_spec h lemma nonempty.of_subset (ht : s ⊆ t) (hs : s.nonempty) : t.nonempty := hs.imp ht lemma nonempty_of_ssubset (ht : s ⊂ t) : (t \ s).nonempty := let ⟨x, xt, xs⟩ := exists_of_ssubset ht in ⟨x, xt, xs⟩ lemma nonempty.of_diff (h : (s \ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.of_ssubset' (ht : s ⊂ t) : t.nonempty := (nonempty_of_ssubset ht).of_diff lemma nonempty.inl (hs : s.nonempty) : (s ∪ t).nonempty := hs.imp $ λ _, or.inl lemma nonempty.inr (ht : t.nonempty) : (s ∪ t).nonempty := ht.imp $ λ _, or.inr @[simp] lemma union_nonempty : (s ∪ t).nonempty ↔ s.nonempty ∨ t.nonempty := exists_or_distrib lemma nonempty.left (h : (s ∩ t).nonempty) : s.nonempty := h.imp $ λ _, and.left lemma nonempty.right (h : (s ∩ t).nonempty) : t.nonempty := h.imp $ λ _, and.right lemma nonempty_iff_univ_nonempty : nonempty α ↔ (univ : set α).nonempty := ⟨λ ⟨x⟩, ⟨x, trivial⟩, λ ⟨x, _⟩, ⟨x⟩⟩ lemma univ_nonempty : ∀ [h : nonempty α], (univ : set α).nonempty | ⟨x⟩ := ⟨x, trivial⟩ /-! ### Lemmas about the empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_nonempty : s ≠ ∅ ↔ s.nonempty := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem, set.nonempty] theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := ne_empty_iff_nonempty theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := ne_empty_iff_nonempty.2 ⟨x, h⟩ theorem coe_nonempty_iff_ne_empty {s : set α} : nonempty s ↔ s ≠ ∅ := nonempty_subtype.trans ne_empty_iff_exists_mem.symm -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /-! ### Universal set. In Lean `@univ α` (or `univ : set α`) is the set that contains all elements of type `α`. Mathematically it is the same as `α` but it has a different type. -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 @[simp] lemma univ_eq_empty_iff {α : Type*} : (univ : set α) = ∅ ↔ ¬ nonempty α := eq_empty_iff_forall_not_mem.trans ⟨λ H ⟨x⟩, H x trivial, λ H x _, H ⟨x⟩⟩ lemma nonempty_iff_univ_ne_empty {α : Type*} : nonempty α ↔ (univ : set α) ≠ ∅ := by classical; exact iff_not_comm.1 univ_eq_empty_iff lemma exists_mem_of_nonempty (α) : ∀ [nonempty α], ∃x:α, x ∈ (univ : set α) | ⟨x⟩ := ⟨x, trivial⟩ @[simp] lemma univ_ne_empty {α} [h : nonempty α] : (univ : set α) ≠ ∅ := λ e, univ_eq_empty_iff.1 e h instance univ_decidable : decidable_pred (@set.univ α) := λ x, is_true trivial /-! ### Lemmas about union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h lemma subset_union_of_subset_left {s t : set α} (h : s ⊆ t) (u : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_left t u) lemma subset_union_of_subset_right {s u : set α} (h : s ⊆ u) (t : set α) : s ⊆ t ∪ u := subset.trans h (subset_union_right t u) @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /-! ### Lemmas about intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /-! ### Distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /-! ### Lemmas about `insert` `insert α s` is the set `{α} ∪ s`. -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] lemma ne_insert_of_not_mem {s : set α} (t : set α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { classical, contrapose! h, simp [h] } theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_iff_subset_ne, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := ext $ assume a, by simp [or.comm, or.left_comm] theorem insert_nonempty (a : α) (s : set α) : (insert a s).nonempty := ⟨a, mem_insert a s⟩ theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /-! ### Lemmas about singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] @[simp] lemma set_of_eq_eq_singleton {a : α} : {n | n = a} = {a} := set.ext $ λ n, (set.mem_singleton_iff).symm -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_nonempty (a : α) : ({a} : set α).nonempty := insert_nonempty _ _ @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := ext $ by simp @[simp] theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] @[simp] theorem singleton_union : {a} ∪ s = insert a s := by rw [union_comm, union_singleton] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] lemma nmem_singleton_empty {s : set α} : s ∉ ({∅} : set (set α)) ↔ nonempty s := by simp [coe_nonempty_iff_ne_empty] instance unique_singleton {α : Type*} (a : α) : unique ↥({a} : set α) := { default := ⟨a, mem_singleton a⟩, uniq := begin intros x, apply subtype.coe_ext.2, apply eq_of_mem_singleton (subtype.mem x), end} /-! ### Lemmas about sets defined as `{x ∈ s | p x}`. -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] @[simp] lemma sep_univ {α} {p : α → Prop} : {a ∈ (univ : set α) | p a} = {a | p a} := set.ext $ by simp /-! ### Lemmas about complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h lemma compl_set_of {α} (p : α → Prop) : - {a | p a} = { a | ¬ p a } := rfl theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] lemma compl_empty_iff {s : set α} : -s = ∅ ↔ s = univ := by { split, intro h, rw [←compl_compl s, h, compl_empty], intro h, rw [h, compl_univ] } lemma compl_univ_iff {s : set α} : -s = univ ↔ s = ∅ := by rw [←compl_empty_iff, compl_compl] lemma nonempty_compl {s : set α} : nonempty (-s : set α) ↔ s ≠ univ := by { symmetry, rw [coe_nonempty_iff_ne_empty], apply not_congr, split, intro h, rw [h, compl_univ], intro h, rw [←compl_compl s, h, compl_empty] } theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff theorem inter_subset (a b c : set α) : a ∩ b ⊆ c ↔ a ⊆ -b ∪ c := begin haveI := classical.prop_decidable, split, { intros h x xa, by_cases h' : x ∈ b, simp [h ⟨xa, h'⟩], simp [h'] }, intros h x, rintro ⟨xa, xb⟩, cases h xa, contradiction, assumption end /-! ### Lemmas about set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem nonempty_diff {s t : set α} : (s \ t).nonempty ↔ ¬ (s ⊆ t) := ⟨λ ⟨x, xs, xt⟩, not_subset.2 ⟨x, xs, xt⟩, λ h, let ⟨x, xs, xt⟩ := not_subset.1 h in ⟨x, xs, xt⟩⟩ theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_union_distrib_left {s t u : set α} : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := set.ext $ λ _, and_or_distrib_left theorem inter_union_distrib_right {s t u : set α} : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := set.ext $ λ _, and_or_distrib_right theorem union_inter_distrib_left {s t u : set α} : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := set.ext $ λ _, or_and_distrib_left theorem union_inter_distrib_right {s t u : set α} : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := set.ext $ λ _, or_and_distrib_right theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] @[simp] lemma empty_diff {α : Type*} (s : set α) : (∅ \ s : set α) = ∅ := eq_empty_of_subset_empty $ assume x ⟨hx, _⟩, hx theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma subset_insert_diff (s t : set α) : s ⊆ (s \ t) ∪ t := by rw [union_comm, ←diff_subset_iff] @[simp] lemma diff_singleton_subset_iff {x : α} {s t : set α} : s \ {x} ⊆ t ↔ s ⊆ insert x t := by { rw [←union_singleton, union_comm], apply diff_subset_iff } lemma subset_insert_diff_singleton (x : α) (s : set α) : s ⊆ insert x (s \ {x}) := by rw [←diff_singleton_subset_iff] lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff_of_mem (s) (h : a ∈ t) : insert a s \ t = s \ t := ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem insert_diff_of_not_mem (s) (h : a ∉ t) : insert a s \ t = insert a (s \ t) := begin classical, ext x, by_cases h' : x ∈ t, { have : x ≠ a, { assume H, rw H at h', exact h h' }, simp [h, h', this] }, { simp [h, h'] } end theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self, -union_singleton, -singleton_union] @[simp] lemma diff_self {s : set α} : s \ s = ∅ := ext $ by simp lemma mem_diff_singleton {s s' : set α} {t : set (set α)} : s ∈ t \ {s'} ↔ (s ∈ t ∧ s ≠ s') := by simp lemma mem_diff_singleton_empty {s : set α} {t : set (set α)} : s ∈ t \ {∅} ↔ (s ∈ t ∧ nonempty s) := by simp [coe_nonempty_iff_ne_empty] /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage {s : set β} {a : α} : (a ∈ f ⁻¹' s) ↔ (f a ∈ s) := iff.rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem subset_preimage_univ {s : set α} : s ⊆ f ⁻¹' univ := subset_univ _ @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl @[simp] theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, ext $ assume ⟨x, hx⟩, by simp [h]⟩ lemma if_preimage (s : set α) [decidable_pred s] (f g : α → β) (t : set β) : (λa, if a ∈ s then f a else g a)⁻¹' t = (s ∩ f ⁻¹' t) ∪ (-s ∩ g ⁻¹' t) := begin ext, simp only [mem_inter_eq, mem_union_eq, mem_preimage], split_ifs; simp [mem_def, h] end end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] /- A common special case of `image_congr` -/ lemma image_congr' {f g : α → β} {s : set α} (h : ∀ (x : α), f x = g x) : f '' s = g '' s := image_congr (λx _, h x) theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ /-- A variant of `image_comp`, useful for rewriting -/ lemma image_image (g : β → γ) (f : α → β) (s : set α) : g '' (f '' s) = (λ x, g (f x)) '' s := (image_comp g f s).symm theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := ext $ λ x, by simp [image]; rw eq_comm theorem nonempty.image_const {s : set α} (hs : s.nonempty) (a : β) : (λ _, a) '' s = {a} := ext $ λ x, ⟨λ ⟨y, _, h⟩, h ▸ mem_singleton _, λ h, (eq_of_mem_singleton h).symm ▸ hs.imp (λ y hy, ⟨hy, rfl⟩)⟩ @[simp] lemma image_eq_empty {α β} {f : α → β} {s : set α} : f '' s = ∅ ↔ s = ∅ := by simp only [eq_empty_iff_forall_not_mem]; exact ⟨λ H a ha, H _ ⟨_, ha, rfl⟩, λ H b ⟨_, ha, _⟩, H _ ha⟩ lemma inter_singleton_ne_empty {s : set α} {a : α} : s ∩ {a} ≠ ∅ ↔ a ∈ s := by finish [set.inter_singleton_eq_empty] lemma inter_singleton_nonempty {s : set α} {a : α} : (s ∩ {a}).nonempty ↔ a ∈ s := ne_empty_iff_nonempty.symm.trans inter_singleton_ne_empty theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp /-- A variant of `image_id` -/ @[simp] lemma image_id' (s : set α) : (λx, x) '' s = s := image_id s theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) lemma nonempty_image (f : α → β) {s : set α} : nonempty s → nonempty (f '' s) | ⟨⟨x, hx⟩⟩ := ⟨⟨f x, mem_image_of_mem f hx⟩⟩ /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) lemma preimage_eq_preimage {f : β → α} (hf : surjective f) : f ⁻¹' s = preimage f t ↔ s = t := iff.intro (assume eq, by rw [← @image_preimage_eq β α f s hf, ← @image_preimage_eq β α f t hf, eq]) (assume eq, eq ▸ rfl) lemma surjective_preimage {f : β → α} (hf : surjective f) : injective (preimage f) := assume s t, (preimage_eq_preimage hf).1 theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma preimage_subset_iff {A : set α} {B : set β} {f : α → β} : f⁻¹' B ⊆ A ↔ (∀ a : α, f a ∈ B → a ∈ A) := iff.rfl lemma image_eq_image {f : α → β} (hf : injective f) : f '' s = f '' t ↔ s = t := iff.symm $ iff.intro (assume eq, eq ▸ rfl) $ assume eq, by rw [← preimage_image_eq s hf, ← preimage_image_eq t hf, eq] lemma image_subset_image_iff {f : α → β} (hf : injective f) : f '' s ⊆ f '' t ↔ s ⊆ t := begin refine (iff.symm $ iff.intro (image_subset f) $ assume h, _), rw [← preimage_image_eq s hf, ← preimage_image_eq t hf], exact preimage_mono h end lemma injective_image {f : α → β} (hf : injective f) : injective (('') f) := assume s t, (image_eq_image hf).1 lemma prod_quotient_preimage_eq_image [s : setoid α] (g : quotient s → β) {h : α → β} (Hh : h = g ∘ quotient.mk) (r : set (β × β)) : {x : quotient s × quotient s | (g x.1, g x.2) ∈ r} = (λ a : α × α, (⟦a.1⟧, ⟦a.2⟧)) '' ((λ a : α × α, (h a.1, h a.2)) ⁻¹' r) := Hh.symm ▸ set.ext (λ ⟨a₁, a₂⟩, ⟨quotient.induction_on₂ a₁ a₂ (λ a₁ a₂ h, ⟨(a₁, a₂), h, rfl⟩), λ ⟨⟨b₁, b₂⟩, h₁, h₂⟩, show (g a₁, g a₂) ∈ r, from have h₃ : ⟦b₁⟧ = a₁ ∧ ⟦b₂⟧ = a₂ := prod.ext_iff.1 h₂, h₃.1 ▸ h₃.2 ▸ h₁⟩) /-- Restriction of `f` to `s` factors through `s.image_factorization f : s → f '' s`. -/ def image_factorization (f : α → β) (s : set α) : s → f '' s := λ p, ⟨f p.1, mem_image_of_mem f p.2⟩ lemma image_factorization_eq {f : α → β} {s : set α} : subtype.val ∘ image_factorization f s = f ∘ subtype.val := funext $ λ p, rfl lemma surjective_onto_image {f : α → β} {s : set α} : surjective (image_factorization f s) := λ ⟨_, ⟨a, ha, rfl⟩⟩, ⟨⟨a, ha⟩, rfl⟩ end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) /-! ### Lemmas about range of a function. -/ section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem exists_range_iff {p : α → Prop} : (∃ a ∈ range f, p a) ↔ (∃ i, p (f i)) := ⟨assume ⟨a, ⟨i, eq⟩, h⟩, ⟨i, eq.symm ▸ h⟩, assume ⟨i, h⟩, ⟨f i, mem_range_self _, h⟩⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id theorem range_inl_union_range_inr : range (@sum.inl α β) ∪ range sum.inr = univ := ext $ λ x, by cases x; simp @[simp] theorem range_quot_mk (r : α → α → Prop) : range (quot.mk r) = univ := range_iff_surjective.2 quot.exists_rep @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := ext $ by simp [image, range] theorem image_subset_range {ι : Type*} (f : ι → β) (s : set ι) : f '' s ⊆ range f := by rw ← image_univ; exact image_subset _ (subset_univ _) theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {s : set α} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff lemma range_comp_subset_range (f : α → β) (g : β → γ) : range (g ∘ f) ⊆ range g := by rw range_comp; apply image_subset_range lemma range_ne_empty_iff_nonempty : range f ≠ ∅ ↔ nonempty ι := ne_empty_iff_exists_mem.trans ⟨λ ⟨y, x, hxy⟩, ⟨x⟩, λ ⟨x⟩, ⟨f x, mem_range_self x⟩⟩ lemma range_ne_empty [h : nonempty ι] (f : ι → α) : range f ≠ ∅ := range_ne_empty_iff_nonempty.2 h @[simp] lemma range_eq_empty {α : Type u} {β : Type v} {f : α → β} : range f = ∅ ↔ ¬ nonempty α := by rw ← set.image_univ; simp [-set.image_univ] theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' (f ⁻¹' t) = t ∩ range f := ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ f ⁻¹' t, by simp [preimage, h_eq, hx]⟩ lemma image_preimage_eq_of_subset {f : α → β} {s : set β} (hs : s ⊆ range f) : f '' (f ⁻¹' s) = s := by rw [image_preimage_eq_inter_range, inter_eq_self_of_subset_left hs] lemma preimage_subset_preimage_iff {s t : set α} {f : β → α} (hs : s ⊆ range f) : f ⁻¹' s ⊆ f ⁻¹' t ↔ s ⊆ t := begin split, { intros h x hx, rcases hs hx with ⟨y, rfl⟩, exact h hx }, intros h x, apply h end lemma preimage_eq_preimage' {s t : set α} {f : β → α} (hs : s ⊆ range f) (ht : t ⊆ range f) : f ⁻¹' s = f ⁻¹' t ↔ s = t := begin split, { intro h, apply subset.antisymm, rw [←preimage_subset_preimage_iff hs, h], rw [←preimage_subset_preimage_iff ht, h] }, rintro rfl, refl end theorem preimage_inter_range {f : α → β} {s : set β} : f ⁻¹' (s ∩ range f) = f ⁻¹' s := set.ext $ λ x, and_iff_left ⟨x, rfl⟩ theorem preimage_image_preimage {f : α → β} {s : set β} : f ⁻¹' (f '' (f ⁻¹' s)) = f ⁻¹' s := by rw [image_preimage_eq_inter_range, preimage_inter_range] @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep lemma range_const_subset {c : α} : range (λx:ι, c) ⊆ {c} := range_subset_iff.2 $ λ x, or.inl rfl @[simp] lemma range_const : ∀ [nonempty ι] {c : α}, range (λx:ι, c) = {c} | ⟨x⟩ c := subset.antisymm range_const_subset $ assume y hy, (mem_singleton_iff.1 hy).symm ▸ mem_range_self x /-- Any map `f : ι → β` factors through a map `range_factorization f : ι → range f`. -/ def range_factorization (f : ι → β) : ι → range f := λ i, ⟨f i, mem_range_self i⟩ lemma range_factorization_eq {f : ι → β} : subtype.val ∘ range_factorization f = f := funext $ λ i, rfl lemma surjective_onto_range : surjective (range_factorization f) := λ ⟨_, ⟨i, rfl⟩⟩, ⟨i, rfl⟩ lemma image_eq_range (f : α → β) (s : set α) : f '' s = range (λ(x : s), f x.1) := by { ext, split, rintro ⟨x, h1, h2⟩, exact ⟨⟨x, h1⟩, h2⟩, rintro ⟨⟨x, h1⟩, h2⟩, exact ⟨x, h1, h2⟩ } @[simp] lemma sum.elim_range {α β γ : Type*} (f : α → γ) (g : β → γ) : range (sum.elim f g) = range f ∪ range g := by simp [set.ext_iff, mem_range] lemma range_ite_subset' {p : Prop} [decidable p] {f g : α → β} : range (if p then f else g) ⊆ range f ∪ range g := begin by_cases h : p, {rw if_pos h, exact subset_union_left _ _}, {rw if_neg h, exact subset_union_right _ _} end lemma range_ite_subset {p : α → Prop} [decidable_pred p] {f g : α → β} : range (λ x, if p x then f x else g x) ⊆ range f ∪ range g := begin rw range_subset_iff, intro x, by_cases h : p x, simp [if_pos h, mem_union, mem_range_self], simp [if_neg h, mem_union, mem_range_self] end end range /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y theorem pairwise_on.mono {s t : set α} {r} (h : t ⊆ s) (hp : pairwise_on s r) : pairwise_on t r := λ x xt y yt, hp x (h xt) y (h yt) theorem pairwise_on.mono' {s : set α} {r r' : α → α → Prop} (H : ∀ a b, r a b → r' a b) (hp : pairwise_on s r) : pairwise_on s r' := λ x xs y ys h, H _ _ (hp x xs y ys h) end set open set /-! ### Image and preimage on subtypes -/ namespace subtype variable {α : Type*} lemma val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ @[simp] lemma val_range {p : α → Prop} : set.range (@subtype.val _ p) = {x | p x} := by rw ← set.image_univ; simp [-set.image_univ, val_image] @[simp] lemma range_val (s : set α) : range (subtype.val : s → α) = s := val_range theorem val_image_subset (s : set α) (t : set (subtype s)) : t.image val ⊆ s := λ x ⟨y, yt, yvaleq⟩, by rw ←yvaleq; exact y.property theorem val_image_univ (s : set α) : @val _ s '' set.univ = s := set.eq_of_subset_of_subset (val_image_subset _ _) (λ x xs, ⟨⟨x, xs⟩, ⟨set.mem_univ _, rfl⟩⟩) theorem image_preimage_val (s t : set α) : (@subtype.val _ s) '' ((@subtype.val _ s) ⁻¹' t) = t ∩ s := begin ext x, simp, split, { rintros ⟨y, ys, yt, yx⟩, rw ←yx, exact ⟨yt, ys⟩ }, rintros ⟨xt, xs⟩, exact ⟨x, xs, xt, rfl⟩ end theorem preimage_val_eq_preimage_val_iff (s t u : set α) : ((@subtype.val _ s) ⁻¹' t = (@subtype.val _ s) ⁻¹' u) ↔ (t ∩ s = u ∩ s) := begin rw [←image_preimage_val, ←image_preimage_val], split, { intro h, rw h }, intro h, exact set.injective_image (val_injective) h end lemma exists_set_subtype {t : set α} (p : set α → Prop) : (∃(s : set t), p (subtype.val '' s)) ↔ ∃(s : set α), s ⊆ t ∧ p s := begin split, { rintro ⟨s, hs⟩, refine ⟨subtype.val '' s, _, hs⟩, convert image_subset_range _ _, rw [range_val] }, rintro ⟨s, hs₁, hs₂⟩, refine ⟨subtype.val ⁻¹' s, _⟩, rw [image_preimage_eq_of_subset], exact hs₂, rw [range_val], exact hs₁ end end subtype namespace set section range variable {α : Type*} @[simp] lemma subtype.val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype.val_image] @[simp] lemma range_coe_subtype (s : set α) : range (coe : s → α) = s := subtype.val_range end range /-! ### Lemmas about cartesian product of sets -/ section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} lemma prod_eq (s : set α) (t : set β) : set.prod s t = prod.fst ⁻¹' s ∩ prod.snd ⁻¹' t := rfl theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl lemma mk_mem_prod {a : α} {b : β} (a_in : a ∈ s) (b_in : b ∈ t) : (a, b) ∈ set.prod s t := ⟨a_in, b_in⟩ lemma prod_subset_iff {P : set (α × β)} : (set.prod s t ⊆ P) ↔ ∀ (x ∈ s) (y ∈ t), (x, y) ∈ P := ⟨λ h _ xin _ yin, h (mk_mem_prod xin yin), λ h _ pin, by { cases mem_prod.1 pin with hs ht, simpa using h _ hs _ ht }⟩ @[simp] theorem prod_empty : set.prod s ∅ = (∅ : set (α × β)) := ext $ by simp [set.prod] @[simp] theorem empty_prod : set.prod ∅ t = (∅ : set (α × β)) := ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := ext $ by simp [range] theorem prod_range_univ_eq {α β γ} {m₁ : α → γ} : set.prod (range m₁) (univ : set β) = range (λp:α×β, (m₁ p.1, p.2)) := ext $ by simp [range] theorem prod_univ_range_eq {α β δ} {m₂ : β → δ} : set.prod (univ : set α) (range m₂) = range (λp:α×β, (p.1, m₂ p.2)) := ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := ext $ by simp [set.prod] theorem nonempty.prod : s.nonempty → t.nonempty → (s.prod t).nonempty | ⟨x, hx⟩ ⟨y, hy⟩ := ⟨(x, y), ⟨hx, hy⟩⟩ theorem nonempty.fst : (s.prod t).nonempty → s.nonempty | ⟨p, hp⟩ := ⟨p.1, hp.1⟩ theorem nonempty.snd : (s.prod t).nonempty → t.nonempty | ⟨p, hp⟩ := ⟨p.2, hp.2⟩ theorem prod_nonempty_iff : (s.prod t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, nonempty.prod h.1 h.2⟩ theorem prod_ne_empty_iff : s.prod t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp only [ne_empty_iff_nonempty, prod_nonempty_iff] theorem prod_eq_empty_iff {s : set α} {t : set β} : set.prod s t = ∅ ↔ (s = ∅ ∨ t = ∅) := suffices (¬ set.prod s t ≠ ∅) ↔ (¬ s ≠ ∅ ∨ ¬ t ≠ ∅), by simpa only [(≠), classical.not_not], by classical; rw [prod_ne_empty_iff, not_and_distrib] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod (@univ α) (@univ β) = univ := ext $ assume ⟨a, b⟩, by simp lemma prod_sub_preimage_iff {W : set γ} {f : α × β → γ} : set.prod s t ⊆ f ⁻¹' W ↔ ∀ a b, a ∈ s → b ∈ t → f (a, b) ∈ W := by simp [subset_def] lemma fst_image_prod_subset (s : set α) (t : set β) : prod.fst '' (set.prod s t) ⊆ s := λ _ h, let ⟨_, ⟨h₂, _⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_fst (s : set α) (t : set β) : set.prod s t ⊆ prod.fst ⁻¹' s := image_subset_iff.1 (fst_image_prod_subset s t) lemma fst_image_prod (s : set β) {t : set α} (ht : t ≠ ∅) : prod.fst '' (set.prod s t) = s := set.subset.antisymm (fst_image_prod_subset _ _) $ λ y y_in, let (⟨x, x_in⟩ : ∃ (x : α), x ∈ t) := set.exists_mem_of_ne_empty ht in ⟨(y, x), ⟨y_in, x_in⟩, rfl⟩ lemma snd_image_prod_subset (s : set α) (t : set β) : prod.snd '' (set.prod s t) ⊆ t := λ _ h, let ⟨_, ⟨_, h₂⟩, h₁⟩ := (set.mem_image _ _ _).1 h in h₁ ▸ h₂ lemma prod_subset_preimage_snd (s : set α) (t : set β) : set.prod s t ⊆ prod.snd ⁻¹' t := image_subset_iff.1 (snd_image_prod_subset s t) lemma snd_image_prod {s : set α} (hs : s ≠ ∅) (t : set β) : prod.snd '' (set.prod s t) = t := set.subset.antisymm (snd_image_prod_subset _ _) $ λ y y_in, let (⟨x, x_in⟩ : ∃ (x : α), x ∈ s) := set.exists_mem_of_ne_empty hs in ⟨(x, y), ⟨x_in, y_in⟩, rfl⟩ /-- A product set is included in a product set if and only factors are included, or a factor of the first set is empty. -/ lemma prod_subset_prod_iff : (set.prod s t ⊆ set.prod s₁ t₁) ↔ (s ⊆ s₁ ∧ t ⊆ t₁) ∨ (s = ∅) ∨ (t = ∅) := begin classical, by_cases h : set.prod s t = ∅, { simp [h, prod_eq_empty_iff.1 h] }, { have st : s ≠ ∅ ∧ t ≠ ∅, by rwa [← ne.def, prod_ne_empty_iff] at h, split, { assume H : set.prod s t ⊆ set.prod s₁ t₁, have h' : s₁ ≠ ∅ ∧ t₁ ≠ ∅ := prod_ne_empty_iff.1 (subset_ne_empty H h), refine or.inl ⟨_, _⟩, show s ⊆ s₁, { have := image_subset (prod.fst : α × β → α) H, rwa [fst_image_prod _ st.2, fst_image_prod _ h'.2] at this }, show t ⊆ t₁, { have := image_subset (prod.snd : α × β → β) H, rwa [snd_image_prod st.1, snd_image_prod h'.1] at this } }, { assume H, simp [st] at H, exact prod_mono H.1 H.2 } } end end prod section pi variables {α : Type*} {π : α → Type*} def pi (i : set α) (s : Πa, set (π a)) : set (Πa, π a) := { f | ∀a∈i, f a ∈ s a } @[simp] lemma pi_empty_index (s : Πa, set (π a)) : pi ∅ s = univ := by ext; simp [pi] @[simp] lemma pi_insert_index (a : α) (i : set α) (s : Πa, set (π a)) : pi (insert a i) s = ((λf, f a) ⁻¹' s a) ∩ pi i s := by ext; simp [pi, or_imp_distrib, forall_and_distrib] @[simp] lemma pi_singleton_index (a : α) (s : Πa, set (π a)) : pi {a} s = ((λf:(Πa, π a), f a) ⁻¹' s a) := by ext; simp [pi] lemma pi_if {p : α → Prop} [h : decidable_pred p] (i : set α) (s t : Πa, set (π a)) : pi i (λa, if p a then s a else t a) = pi {a ∈ i | p a} s ∩ pi {a ∈ i | ¬ p a} t := begin ext f, split, { assume h, split; { rintros a ⟨hai, hpa⟩, simpa [*] using h a } }, { rintros ⟨hs, ht⟩ a hai, by_cases p a; simp [*, pi] at * } end end pi section inclusion variable {α : Type*} /-- `inclusion` is the "identity" function between two subsets `s` and `t`, where `s ⊆ t` -/ def inclusion {s t : set α} (h : s ⊆ t) : s → t := λ x : s, (⟨x, h x.2⟩ : t) @[simp] lemma inclusion_self {s : set α} (x : s) : inclusion (set.subset.refl _) x = x := by cases x; refl @[simp] lemma inclusion_inclusion {s t u : set α} (hst : s ⊆ t) (htu : t ⊆ u) (x : s) : inclusion htu (inclusion hst x) = inclusion (set.subset.trans hst htu) x := by cases x; refl lemma inclusion_injective {s t : set α} (h : s ⊆ t) : function.injective (inclusion h) | ⟨_, _⟩ ⟨_, _⟩ := subtype.ext.2 ∘ subtype.ext.1 end inclusion end set
6ed9143e8e27cf84e9e8dd4bbb8cb4964c71974f
947b78d97130d56365ae2ec264df196ce769371a
/tests/playground/forthelean/ForTheLean/Demo.lean
82504a45382dc4c9c7b21070a477f78ea1f4bbba
[ "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
3,110
lean
-- -*- origami-fold-style: triple-braces -*- import ForTheLean.Prelim new_frontend open Lean open Lean.Elab.Command open Prelim -- {{{ [synonym] syntax variant := "-"? wlexem syntax [synonym] "[synonym " wlexem ("/" (wlexem <|> variant))+ "]" : command @[commandElab synonym] def elabSynonym : CommandElab := fun stx => match_syntax stx with | `([synonym $w:ident/ -$w':ident]) => modifyEnv $ fun env => addSynonym env w.getId (w.getId.appendAfter w'.getId.toString) | `([synonym $w:ident/$w':ident]) => modifyEnv $ fun env => addSynonym env w.getId w'.getId | _ => throwUnsupportedSyntax -- }}} [synonym number/numbers] -- {{{ syntax indef := "A" <|> "a" <|> "An" <|> "an" syntax art := "The" <|> "the" <|> indef syntax notionPattern := art wlexem+ -- all class nouns are added dynamically declare_syntax_cat classNoun syntax "Signature." notionPattern "is" indef (classNoun <|> "notion") "." : command macro_rules | `(Signature. The $words:wlexem* is a notion.) => let words := words.map Syntax.getId; let parsers := words.map mkSyntaxAtom; let desc := mkIdent $ mkNameSimple $ "_".intercalate $ words.toList.map toString; `(axiom $desc:ident : Type syntax_synonyms [$desc] $parsers:syntax* : classNoun @[macro $desc] def expandSig : Macro := fun _ => `($desc)) | `(Signature. The $words:wlexem* is a $n.) => let words := words.map Syntax.getId; let parsers := words.map mkSyntaxAtom; let desc := mkIdent $ mkNameSimple $ "_".intercalate $ words.toList.map toString; `(axiom $desc:ident : $n syntax_synonyms [$desc] $parsers:syntax* : classNoun @[macro $desc] def expandSig : Macro := fun _ => `($desc)) -- }}} Signature. A real number is a notion. -- {{{ -- TODO: should be single character syntax newVar := ident syntax standFor := "stand" "for" syntax standForDenote := standFor <|> "denote" syntax "Let" (sepBy newVar ",") standForDenote (indef)? classNoun "." : command macro_rules | `(Let $vs* denote $indef* $noun.) => `(variables ($(vs.getSepElems.map (fun v => v.getArg 0)):ident* : $noun)) -- }}} Let x,y stand for real numbers. -- {{{ syntax var := ident -- TODO: should be single character syntax uniPredPattern := var "is" wlexem+ var syntax predPattern := uniPredPattern syntax "Signature." predPattern "is" (indef)? "atom" "." : command macro_rules | `(Signature. $x:var is $words:wlexem* $y:var is an atom.) => let words := words.toList.map Syntax.getId; let desc := mkNameSimple $ "_".intercalate $ words.map toString; `(axiom $(mkIdent desc):ident : type_of $(x.getArg 0) → type_of $(y.getArg 0) → Prop) -- }}} Signature. x is greater than y is an atom. Signature. A packing of congruent balls in Euclidean three space is a notion. Signature. The face centered cubic packing is a packing of congruent balls in Euclidean three space. Let P denote a packing of congruent balls in Euclidean three space. -- incomplete from here on Signature. The density of P is a real number. Theorem The_Kepler_conjecture. No packing of congruent balls in Euclidean three space has density greater than the density of the face centered cubic packing.
e2ca81d549e6e54e6b8366c97050d20fcd70d250
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Elab/Declaration.lean
09bc6c6eba6728688e2c4fe4b9afe8e2d75b3906
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,502
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, Sebastian Ullrich -/ import Lean.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef namespace Lean.Elab.Command open Meta /- Auxiliary function for `expandDeclNamespace?` -/ def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) := let (id, optUnivDeclStx) := expandDeclIdCore declId let scpView := extractMacroScopes id match scpView.name with | Name.str Name.anonymous s _ => none | Name.str pre s _ => let nameNew := { scpView with name := Name.mkSimple s }.review if declId.isIdent then some (pre, mkIdentFrom declId nameNew) else some (pre, declId.setArg 0 (mkIdentFrom declId nameNew)) | _ => none /- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/ def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) := if !stx.isOfKind `Lean.Parser.Command.declaration then none else let decl := stx[1] let k := decl.getKind if k == `Lean.Parser.Command.abbrev || k == `Lean.Parser.Command.def || k == `Lean.Parser.Command.theorem || k == `Lean.Parser.Command.constant || k == `Lean.Parser.Command.axiom || k == `Lean.Parser.Command.inductive || k == `Lean.Parser.Command.classInductive || k == `Lean.Parser.Command.structure then match expandDeclIdNamespace? decl[1] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId)) | none => none else if k == `Lean.Parser.Command.instance then let optDeclId := decl[3] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId))) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let (type, _) ← mkForallUsedOnly vars type let (type, _) ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type |>.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let decl := Declaration.axiomDecl { name := declName, lparams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- parser! "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor parser! atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := parser! " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig let ctorModifiers ← elabModifiers ctor[1] if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 2 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName let inferMod := !ctor[3].isNone let (binders, type?) := expandOptDeclSig ctor[4] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } let classes ← getOptDerivingClasses decl[5] pure { ref := decl modifiers := modifiers shortDeclName := name declName := declName levelNames := levelNames binders := binders type? := type? ctors := ctors derivingClasses := classes } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => match expandDeclNamespace? stx with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns:ident $newStx end $ns:ident) withMacroExpansion stx newStx $ elabCommand newStx | none => do let modifiers ← elabModifiers stx[0] let decl := stx[1] let declKind := decl.getKind if declKind == `Lean.Parser.Command.«axiom» then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.«inductive» then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.«structure» then elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] else throwError "unexpected declaration" /- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == `Lean.Parser.Command.variable || k == `Lean.Parser.Command.variables || k == `Lean.Parser.Command.universe || k == `Lean.Parser.Command.universes || k == `Lean.Parser.Command.check || k == `Lean.Parser.Command.set_option || k == `Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 @[builtinMacro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut ns? := none let mut elemsNew := #[] for elem in stx[1].getArgs do match ns?, expandDeclNamespace? elem with | _, none => elemsNew := elemsNew.push elem | none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem | some nsCurr, some (nsNew, elem) => if nsCurr == nsNew then elemsNew := elemsNew.push elem else Macro.throwErrorAt elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration" match ns? with | some ns => let ns := mkIdentFrom stx ns let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns:ident $stxNew end $ns:ident) | none => Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then pure $ stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtinCommandElab «mutual»] def elabMutual : CommandElab := fun stx => do if isMutualInductive stx then elabMutualInductive stx[1].getArgs else if isMutualDef stx then elabMutualDef stx[1].getArgs else throwError "invalid mutual block" /- parser! "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let attrs ← elabAttrs stx[2] let idents := stx[4].getArgs for ident in idents do withRef ident $ liftTermElabM none do let declName ← resolveGlobalConstNoOverload ident.getId Term.applyAttributes declName attrs def expandInitCmd (builtin : Bool) : Macro := fun stx => let optHeader := stx[1] let doSeq := stx[2] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn]constant $id : $type) @[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro := expandInitCmd (builtin := false) @[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro := expandInitCmd (builtin := true) end Lean.Elab.Command
71b4ae17d3a37c1a3664b7d855138f8c7a36c8bc
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/algebra/big_operators/order.lean
2cc7dd2b6bc0f9c4a869c92764b9c255fd29afe5
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,946
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 algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∏` and `∑` operations. -/ open_locale big_operators variables {ι α β M N G k R : Type*} namespace finset section variables [comm_monoid M] [ordered_comm_monoid N] /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ x in s, g x) ≤ ∏ x in s, f (g x)`. -/ @[to_additive le_sum_nonempty_of_subadditive_on_pred] lemma le_prod_nonempty_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) (s : finset ι) (hs_nonempty : s.nonempty) (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul _ _ _) _, { simp [hs_nonempty.ne_empty], }, { exact multiset.forall_mem_map_iff.mpr hs, }, rw multiset.map_map, refl, end /-- Let `{x | p x}` be an additive subsemigroup of an additive commutative monoid `M`. Let `f : M → N` be a map subadditive on `{x | p x}`, i.e., `p x → p y → f (x + y) ≤ f x + f y`. Let `g i`, `i ∈ s`, be a nonempty finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∑ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_nonempty_of_subadditive] lemma le_prod_nonempty_of_submultiplicative (f : M → N) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) {s : finset ι} (hs : s.nonempty) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := le_prod_nonempty_of_submultiplicative_on_pred f (λ i, true) (λ x y _ _, h_mul x y) (λ _ _ _ _, trivial) g s hs (λ _ _, trivial) /-- If `f : M → N` is a subadditive function, `f (x + y) ≤ f x + f y` and `g i`, `i ∈ s`, is a nonempty finite family of elements of `M`, then `f (∑ i in s, g i) ≤ ∑ i in s, f (g i)`. -/ add_decl_doc le_sum_nonempty_of_subadditive /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map such that `f 1 = 1` and `f` is submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive_on_pred] lemma le_prod_of_submultiplicative_on_pred (f : M → N) (p : M → Prop) (h_one : f 1 = 1) (h_mul : ∀ x y, p x → p y → f (x * y) ≤ f x * f y) (hp_mul : ∀ x y, p x → p y → p (x * y)) (g : ι → M) {s : finset ι} (hs : ∀ i ∈ s, p (g i)) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin rcases eq_empty_or_nonempty s with rfl|hs_nonempty, { simp [h_one] }, { exact le_prod_nonempty_of_submultiplicative_on_pred f p h_mul hp_mul g s hs_nonempty hs, }, end /-- Let `{x | p x}` be a subsemigroup of a commutative monoid `M`. Let `f : M → N` be a map such that `f 1 = 1` and `f` is submultiplicative on `{x | p x}`, i.e., `p x → p y → f (x * y) ≤ f x * f y`. Let `g i`, `i ∈ s`, be a finite family of elements of `M` such that `∀ i ∈ s, p (g i)`. Then `f (∏ x in s, g x) ≤ ∏ x in s, f (g x)`. -/ add_decl_doc le_sum_of_subadditive_on_pred /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y`, `f 1 = 1`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ @[to_additive le_sum_of_subadditive] lemma le_prod_of_submultiplicative (f : M → N) (h_one : f 1 = 1) (h_mul : ∀ x y, f (x * y) ≤ f x * f y) (s : finset ι) (g : ι → M) : f (∏ i in s, g i) ≤ ∏ i in s, f (g i) := begin refine le_trans (multiset.le_prod_of_submultiplicative f h_one h_mul _) _, rw multiset.map_map, refl, end /-- If `f : M → N` is a submultiplicative function, `f (x * y) ≤ f x * f y`, `f 1 = 1`, and `g i`, `i ∈ s`, is a finite family of elements of `M`, then `f (∏ i in s, g i) ≤ ∏ i in s, f (g i)`. -/ add_decl_doc le_sum_of_subadditive variables {f g : ι → N} {s t : finset ι} /-- In an ordered commutative monoid, if each factor `f i` of one finite product is less than or equal to the corresponding factor `g i` of another finite product, then `∏ i in s, f i ≤ ∏ i in s, g i`. -/ @[to_additive sum_le_sum] lemma prod_le_prod'' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin classical, induction s using finset.induction_on with i s hi ihs h, { refl }, { simp only [prod_insert hi], exact mul_le_mul' (h _ (mem_insert_self _ _)) (ihs $ λ j hj, h j (mem_insert_of_mem hj)) } end /-- In an ordered additive commutative monoid, if each summand `f i` of one finite sum is less than or equal to the corresponding summand `g i` of another finite sum, then `∑ i in s, f i ≤ ∑ i in s, g i`. -/ add_decl_doc sum_le_sum @[to_additive sum_nonneg] lemma one_le_prod' (h : ∀i ∈ s, 1 ≤ f i) : 1 ≤ (∏ i in s, f i) := le_trans (by rw prod_const_one) (prod_le_prod'' h) @[to_additive sum_nonpos] lemma prod_le_one' (h : ∀i ∈ s, f i ≤ 1) : (∏ i in s, f i) ≤ 1 := (prod_le_prod'' h).trans_eq (by rw prod_const_one) @[to_additive sum_le_sum_of_subset_of_nonneg] lemma prod_le_prod_of_subset_of_one_le' (h : s ⊆ t) (hf : ∀ i ∈ t, i ∉ s → 1 ≤ f i) : ∏ i in s, f i ≤ ∏ i in t, f i := by classical; calc (∏ i in s, f i) ≤ (∏ i in t \ s, f i) * (∏ i in s, f i) : le_mul_of_one_le_left' $ one_le_prod' $ by simpa only [mem_sdiff, and_imp] ... = ∏ i in t \ s ∪ s, f i : (prod_union sdiff_disjoint).symm ... = ∏ i in t, f i : by rw [sdiff_union_of_subset h] @[to_additive sum_mono_set_of_nonneg] lemma prod_mono_set_of_one_le' (hf : ∀ x, 1 ≤ f x) : monotone (λ s, ∏ x in s, f x) := λ s t hst, prod_le_prod_of_subset_of_one_le' hst $ λ x _ _, hf x @[to_additive sum_le_univ_sum_of_nonneg] lemma prod_le_univ_prod_of_one_le' [fintype ι] {s : finset ι} (w : ∀ x, 1 ≤ f x) : ∏ x in s, f x ≤ ∏ x, f x := prod_le_prod_of_subset_of_one_le' (subset_univ s) (λ a _ _, w a) @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_one_le' : (∀ i ∈ s, 1 ≤ f i) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ i ∈ s, 1 ≤ f i, from λ _, H _ ∘ mem_insert_of_mem, rw [prod_insert ha, mul_eq_one_iff' (H _ $ mem_insert_self _ _) (one_le_prod' this), forall_mem_insert, ih this] end @[to_additive sum_eq_zero_iff_of_nonneg] lemma prod_eq_one_iff_of_le_one' : (∀ i ∈ s, f i ≤ 1) → (∏ i in s, f i = 1 ↔ ∀ i ∈ s, f i = 1) := @prod_eq_one_iff_of_one_le' _ (order_dual N) _ _ _ @[to_additive single_le_sum] lemma single_le_prod' (hf : ∀ i ∈ s, 1 ≤ f i) {a} (h : a ∈ s) : f a ≤ (∏ x in s, f x) := calc f a = ∏ i in {a}, f i : prod_singleton.symm ... ≤ ∏ i in s, f i : prod_le_prod_of_subset_of_one_le' (singleton_subset_iff.2 h) $ λ i hi _, hf i hi variables {ι' : Type*} [decidable_eq ι'] @[to_additive sum_fiberwise_le_sum_of_sum_fiber_nonneg] lemma prod_fiberwise_le_prod_of_one_le_prod_fiber' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (1 : N) ≤ ∏ x in s.filter (λ x, g x = y), f x) : ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x ≤ ∏ x in s, f x := calc (∏ y in t, ∏ x in s.filter (λ x, g x = y), f x) ≤ (∏ y in t ∪ s.image g, ∏ x in s.filter (λ x, g x = y), f x) : prod_le_prod_of_subset_of_one_le' (subset_union_left _ _) $ λ y hyts, h y ... = ∏ x in s, f x : prod_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ @[to_additive sum_le_sum_fiberwise_of_sum_fiber_nonpos] lemma prod_le_prod_fiberwise_of_prod_fiber_le_one' {t : finset ι'} {g : ι → ι'} {f : ι → N} (h : ∀ y ∉ t, (∏ x in s.filter (λ x, g x = y), f x) ≤ 1) : (∏ x in s, f x) ≤ ∏ y in t, ∏ x in s.filter (λ x, g x = y), f x := @prod_fiberwise_le_prod_of_one_le_prod_fiber' _ (order_dual N) _ _ _ _ _ _ _ h end lemma abs_sum_le_sum_abs {G : Type*} [linear_ordered_add_comm_group G] (f : ι → G) (s : finset ι) : abs (∑ i in s, f i) ≤ ∑ i in s, abs (f i) := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_prod {R : Type*} [linear_ordered_comm_ring R] {f : ι → R} {s : finset ι} : abs (∏ x in s, f x) = ∏ x in s, abs (f x) := (abs_hom.to_monoid_hom : R →* R).map_prod _ _ section pigeonhole variable [decidable_eq β] theorem card_le_mul_card_image_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to {f : α → β} {s : finset α} {t : finset β} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card {f : α → β} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn @[to_additive] lemma prod_le_of_forall_le {α β : Type*} [ordered_comm_monoid β] (s : finset α) (f : α → β) (n : β) (h : ∀ (x ∈ s), f x ≤ n) : s.prod f ≤ n ^ s.card := begin refine (multiset.prod_le_of_forall_le (s.val.map f) n _).trans _, { simpa using h }, { simpa } end end pigeonhole section canonically_ordered_monoid variables [canonically_ordered_monoid M] {f : ι → M} {s t : finset ι} @[simp, to_additive sum_eq_zero_iff] lemma prod_eq_one_iff' : ∏ x in s, f x = 1 ↔ ∀ x ∈ s, f x = 1 := prod_eq_one_iff_of_one_le' $ λ x hx, one_le (f x) @[to_additive sum_le_sum_of_subset] lemma prod_le_prod_of_subset' (h : s ⊆ t) : ∏ x in s, f x ≤ ∏ x in t, f x := prod_le_prod_of_subset_of_one_le' h $ assume x h₁ h₂, one_le _ @[to_additive sum_mono_set] lemma prod_mono_set' (f : ι → M) : monotone (λ s, ∏ x in s, f x) := λ s₁ s₂ hs, prod_le_prod_of_subset' hs @[to_additive sum_le_sum_of_ne_zero] lemma prod_le_prod_of_ne_one' (h : ∀ x ∈ s, f x ≠ 1 → x ∈ t) : ∏ x in s, f x ≤ ∏ x in t, f x := by classical; calc ∏ x in s, f x = (∏ x in s.filter (λ x, f x = 1), f x) * ∏ x in s.filter (λ x, f x ≠ 1), f x : by rw [← prod_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∏ x in t, f x) : mul_le_of_le_one_of_le (prod_le_one' $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (prod_le_prod_of_subset' $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive sum_lt_sum] theorem prod_lt_prod' (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, prod_insert (not_mem_erase _ _), prod_insert (not_mem_erase _ _)], exact mul_lt_mul_of_lt_of_le hlt (prod_le_prod'' $ λ j hj, Hle j $ mem_of_mem_erase hj) end @[to_additive sum_lt_sum_of_nonempty] lemma prod_lt_prod_of_nonempty' (hs : s.nonempty) (Hlt : ∀ i ∈ s, f i < g i) : ∏ i in s, f i < ∏ i in s, g i := begin apply prod_lt_prod', { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end @[to_additive sum_lt_sum_of_subset] lemma prod_lt_prod_of_subset' (h : s ⊆ t) {i : ι} (ht : i ∈ t) (hs : i ∉ s) (hlt : 1 < f i) (hle : ∀ j ∈ t, j ∉ s → 1 ≤ f j) : ∏ j in s, f j < ∏ j in t, f j := by classical; calc ∏ j in s, f j < ∏ j in insert i s, f j : begin rw prod_insert hs, exact lt_mul_of_one_lt_left' (∏ j in s, f j) hlt, end ... ≤ ∏ j in t, f j : begin apply prod_le_prod_of_subset_of_one_le', { simp [finset.insert_subset, h, ht] }, { assume x hx h'x, simp only [mem_insert, not_or_distrib] at h'x, exact hle x hx h'x.2 } end @[to_additive single_lt_sum] lemma single_lt_prod' {i j : ι} (hij : j ≠ i) (hi : i ∈ s) (hj : j ∈ s) (hlt : 1 < f j) (hle : ∀ k ∈ s, k ≠ i → 1 ≤ f k) : f i < ∏ k in s, f k := calc f i = ∏ k in {i}, f k : prod_singleton.symm ... < ∏ k in s, f k : prod_lt_prod_of_subset' (singleton_subset_iff.2 hi) hj (mt mem_singleton.1 hij) hlt $ λ k hks hki, hle k hks (mt mem_singleton.2 hki) end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_comm_monoid M] {f g : ι → M} {s t : finset ι} @[to_additive exists_lt_of_sum_lt] theorem exists_lt_of_prod_lt' (Hlt : ∏ i in s, f i < ∏ i in s, g i) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact prod_le_prod'' Hle end @[to_additive exists_le_of_sum_le] theorem exists_le_of_prod_le' (hs : s.nonempty) (Hle : ∏ i in s, f i ≤ ∏ i in s, g i) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, exact prod_lt_prod_of_nonempty' hs Hlt end @[to_additive exists_pos_of_sum_zero_of_exists_nonzero] lemma exists_one_lt_of_prod_one_of_exists_ne_one' (f : ι → M) (h₁ : ∏ i in s, f i = 1) (h₂ : ∃ i ∈ s, f i ≠ 1) : ∃ i ∈ s, 1 < f i := begin contrapose! h₁, obtain ⟨i, m, i_ne⟩ : ∃ i ∈ s, f i ≠ 1 := h₂, apply ne_of_lt, calc ∏ j in s, f j < ∏ j in s, 1 : prod_lt_prod' h₁ ⟨i, m, (h₁ i m).lt_of_ne i_ne⟩ ... = 1 : prod_const_one end end linear_ordered_cancel_comm_monoid section ordered_comm_semiring variables [ordered_comm_semiring R] {f g : ι → R} {s t : finset ι} open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg (h0 : ∀ i ∈ s, 0 ≤ f i) : 0 ≤ ∏ i in s, f i := prod_induction f (λ i, 0 ≤ i) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos [nontrivial R] (h0 : ∀ i ∈ s, 0 < f i) : 0 < ∏ i in s, f i := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /-- If all `f i`, `i ∈ s`, are nonnegative and each `f i` is less than or equal to `g i`, then the product of `f i` is less than or equal to the product of `g i`. See also `finset.prod_le_prod''` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_prod (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin induction s using finset.induction with a s has ih h, { simp }, { simp only [prod_insert has], apply mul_le_mul, { exact h1 a (mem_insert_self a s) }, { apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H) }, { apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)) }, { apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } } end /-- If each `f i`, `i ∈ s` belongs to `[0, 1]`, then their product is less than or equal to one. See also `finset.prod_le_one'` for the case of an ordered commutative multiplicative monoid. -/ lemma prod_le_one (h0 : ∀ i ∈ s, 0 ≤ f i) (h1 : ∀ i ∈ s, f i ≤ 1) : ∏ i in s, f i ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `ordered_comm_semiring`. -/ lemma prod_add_prod_le {i : ι} {f g h : ι → R} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply_assumption; assumption }; apply prod_le_prod; simp * { contextual := tt } }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, exact le_trans (hg j h1j) (hgf j h1j h2j) } end end ordered_comm_semiring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring R] {f g h : ι → R} {s : finset ι} {i : ι} lemma prod_le_prod' (h : ∀ i ∈ s, f i ≤ g i) : ∏ i in s, f i ≤ ∏ i in s, g i := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply mul_le_mul', { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [prod_eq_mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace fintype variables [fintype ι] @[mono, to_additive sum_mono] lemma prod_mono' [ordered_comm_monoid M] : monotone (λ f : ι → M, ∏ i, f i) := λ f g hfg, finset.prod_le_prod'' $ λ x _, hfg x @[to_additive sum_strict_mono] lemma prod_strict_mono' [ordered_cancel_comm_monoid M] : strict_mono (λ f : ι → M, ∏ x, f x) := λ f g hfg, let ⟨hle, i, hlt⟩ := pi.lt_def.mp hfg in finset.prod_lt_prod' (λ i _, hle i) ⟨i, finset.mem_univ i, hlt⟩ end fintype namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring R] [nontrivial R] [decidable_eq R] {s : finset ι} {f : ι → with_top R} (h : ∀ i ∈ s, f i < ⊤) : ∏ i in s, f i < ⊤ := prod_induction f (λ a, a < ⊤) (λ a b, mul_lt_top) (coe_lt_top 1) h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : (∀ i ∈ s, f i < ⊤) → (∑ i in s, f i) < ⊤ := sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i = ⊤ ↔ ∃ i ∈ s, f i = ⊤ := begin classical, split, { contrapose!, exact λ h, (sum_lt_top $ λ i hi, lt_top_iff_ne_top.2 (h i hi)).ne }, { rintro ⟨i, his, hi⟩, rw [sum_eq_add_sum_diff_singleton his, hi, top_add] } end /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [ordered_add_comm_monoid M] {s : finset ι} {f : ι → with_top M} : ∑ i in s, f i < ⊤ ↔ ∀ i ∈ s, f i < ⊤ := by simp only [lt_top_iff_ne_top, ne.def, sum_eq_top_iff, not_exists] end with_top
5be580e4de8ce18ff228af32ef4751b35253492b
423cba856b0cf4755b74f3fea3f0a0c5656379fd
/src/pipes/basic.lean
44451359aa788077077d135f624978d645bf837e
[]
no_license
cipher1024/lean-pipes
e221aafa8f127ab8f2dabe12897427eefd762b36
3db1d792b987113b07578f21de26c23826809e0c
refs/heads/master
1,609,627,565,606
1,526,931,011,000
1,526,931,011,000
99,382,224
0
0
null
null
null
null
UTF-8
Lean
false
false
15,954
lean
import data.coinductive import .tactic universes u v w local prefix `♯`:0 := cast (by simp [*] <|> cc <|> solve_by_elim) open nat function /- TODO: - [X] corec - [ ] main pipe composition - [ ] Prove that pipes form a monad - [ ] recursion - [ ] stdio - [ ] example with IO - [ ] Provide utilities - [ ] Prove that pipes form a category -/ /- coinductive proxy (x x' y y' : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) | ret {} : α → proxy | action : ∀ β, m β → (β → proxy) → proxy | yield : y → (y' → proxy) → proxy | await : x' → (x → proxy) → proxy | think : proxy → proxy -/ section parameters (x x' y y' : Type u) (m : Type u → Type v) variable (α : Type u) inductive proxy_node : Type (max u v+1) | ret {} : α → proxy_node | action {} {β : Type u} : m β → proxy_node | yield {} : y' → proxy_node | await {} : x → proxy_node | think {} : proxy_node -- variables {α} def proxy_nxt : proxy_node α → Type u | (proxy_node.ret _) := ulift empty | (@proxy_node.action _ _ _ _ β _) := β | (proxy_node.yield _) := y | (proxy_node.await _) := x' | (proxy_node.think) := punit def proxy : Type (max u v+1) := cofix (proxy_nxt α) inductive proxy_v_mut_rec (var : Type w) (α : Type u) : bool → Type (max (u+1) v w) | ret {} : α → proxy_v_mut_rec tt | action {} : ∀ β, m β → (β → proxy_v_mut_rec ff) → proxy_v_mut_rec tt | yield {} : y' → (y → proxy_v_mut_rec ff) → proxy_v_mut_rec tt | await {} : x → (x' → proxy_v_mut_rec ff) → proxy_v_mut_rec tt | think {} : proxy_v_mut_rec ff → proxy_v_mut_rec tt | hole {} : var → proxy_v_mut_rec ff | more {} : proxy_v_mut_rec tt → proxy_v_mut_rec ff abbreviation proxy_v (var α) := proxy_v_mut_rec var α tt abbreviation proxy_leaf_v (var α) := proxy_v_mut_rec var α ff abbreviation proxy_cons : Type (max u v+1) := proxy_v (proxy α) α abbreviation proxy_leaf : Type (max u v+1) := proxy_leaf_v (proxy α) α abbreviation proxy_mut (b : bool) : Type (max u v+1) := proxy_v_mut_rec (proxy α) α b end namespace proxy_v export proxy_v_mut_rec (ret action yield await think) end proxy_v namespace proxy export proxy_v_mut_rec (ret action yield await think) end proxy namespace proxy_leaf_v export proxy_v_mut_rec (more hole) end proxy_leaf_v namespace proxy_leaf export proxy_v_mut_rec (more hole) end proxy_leaf namespace proxy section defs def X := ulift empty abbreviation pipe (a b : Type u) := proxy punit a punit b abbreviation producer (a : Type u) := proxy X punit punit a abbreviation producer' (a : Type u) (m α) := ∀ {y y'}, proxy y y' punit a m α abbreviation consumer (a : Type u) := proxy punit a punit X abbreviation consumer' (a : Type u) (m α) := ∀ {y y'}, proxy punit a y y' m α parameters {x x' y y' : Type u} parameters {m : Type u → Type v} variables {α β γ : Type u} open nat proxy_v proxy_leaf_v def empty.rec' {α : Sort*} : X → α := ulift.rec (empty.rec _) notation `⊗` := punit.star def of_cons : Π {b}, proxy_mut x x' y y' m α b → proxy x x' y y' m α | tt (ret i) := cofix.mk (proxy_node.ret i) empty.rec' | tt (action β cmd f) := cofix.mk (proxy_node.action cmd) (λ i, of_cons (f i)) | tt (yield o f) := cofix.mk (proxy_node.yield o) (λ i, of_cons (f i)) | tt (await o f) := cofix.mk (proxy_node.await o) (λ i, of_cons (f i)) | tt (think cmd) := cofix.mk (proxy_node.think) (λ _, of_cons cmd) | ff (hole x) := x | ff (more t) := of_cons t def to_cons : proxy x x' y y' m α → proxy_cons x x' y y' m α := cofix.cases $ λ node, match node with | (proxy_node.ret i) := λ f, ret i | (proxy_node.action cmd) := λ f, action _ cmd (λ i, hole $ f i) | (proxy_node.yield o) := λ f, yield o (λ i, hole $ f i) | (proxy_node.await o) := λ f, await o (λ i, hole $ f i) | proxy_node.think := λ f, think (hole $ f punit.star) end @[simp] lemma to_cons_mk_ret (r : α) (ch : ulift empty → cofix (proxy_nxt x x' y y' m α)) : to_cons (cofix.mk (proxy_node.ret r) ch) = ret r := sorry @[simp] lemma to_cons_mk_action {β} (cmd : m β) (ch : β → cofix (proxy_nxt x x' y y' m α)) : to_cons (cofix.mk (proxy_node.action cmd) ch) = action β cmd (λ i, hole $ ch i) := sorry @[simp] lemma to_cons_mk_yield (o : y') (ch : y → cofix (proxy_nxt x x' y y' m α)) : to_cons (cofix.mk (proxy_node.yield o) ch) = yield o (λ i, hole $ ch i) := sorry @[simp] lemma to_cons_mk_await (o : x) (ch : x' → cofix (proxy_nxt x x' y y' m α)) : to_cons (cofix.mk (proxy_node.await o) ch) = await o (λ i, hole $ ch i) := sorry @[simp] lemma to_cons_mk_think (ch : punit → cofix (proxy_nxt x x' y y' m α)) : to_cons (cofix.mk proxy_node.think ch) = think (hole $ ch ⊗) := sorry open ulift -- corec -- #check @cofix.corec universes w' protected def corec_aux {S : Type w} : proxy_v x x' y y' m S α → Σ i, proxy_nxt x x' y y' m α i → proxy_leaf_v x x' y y' m S α | (ret i) := ⟨ proxy_node.ret i, empty.rec' ⟩ | (action β cmd f) := ⟨ proxy_node.action cmd, f ⟩ | (yield o f) := ⟨ proxy_node.yield o, f ⟩ | (await o f) := ⟨ proxy_node.await o, f ⟩ | (think f) := ⟨ proxy_node.think, λ _, f ⟩ open cofix protected def head : proxy_cons x x' y y' m α → proxy_node x y' m α | (ret i) := proxy_node.ret i | (action β m f) := proxy_node.action m | (yield o f) := proxy_node.yield o | (await o f) := proxy_node.await o | (think f) := proxy_node.think protected def children : Π c : proxy_cons x x' y y' m α, proxy_nxt x x' y y' m α (head c) → proxy x x' y y' m α | (ret i) := empty.rec' | (action β m f) := of_cons ∘ f | (yield o f) := of_cons ∘ f | (await o f) := of_cons ∘ f | (think f) := λ _, of_cons f lemma head_to_cons (p : proxy x x' y y' m α) : proxy.head (to_cons p) = cofix.head p := by { co_cases p ; cases i ; simp [to_cons,proxy.head], } lemma children_to_cons (p : proxy x x' y y' m α) (i) : proxy.children (to_cons p) (cast (by simp [head_to_cons]) i) = cofix.children p i := sorry lemma of_cons_to_cons (p : proxy x x' y y' m α) : of_cons (to_cons p) = p := sorry inductive proxy_eq : proxy_cons x x' y y' m α → proxy_cons x x' y y' m α → Prop | ret (i : α) : proxy_eq (ret i) (ret i) | act (β cmd) (f f' : β → proxy_cons x x' y y' m α) (step : ∀ (FR : proxy_cons x x' y y' m α → proxy_cons x x' y y' m α → Prop), reflexive FR → FR (action β cmd (more ∘ f)) (action β cmd (more ∘ f')) → ∀ i, FR (f i) (f' i)) : proxy_eq (action β cmd (more ∘ f)) (action β cmd (more ∘ f')) | yield (o f f') (step : ∀ (FR : proxy_cons x x' y y' m α → proxy_cons x x' y y' m α → Prop), reflexive FR → FR (yield o (more ∘ f)) (yield o (more ∘ f')) → ∀ i, FR (f i) (f' i)) : proxy_eq (yield o $ more ∘ f) (yield o $ more ∘ f') | await (o f f') (step : ∀ (FR : proxy_cons x x' y y' m α → proxy_cons x x' y y' m α → Prop), reflexive FR → FR (await o (more ∘ f)) (await o (more ∘ f')) → ∀ i, FR (f i) (f' i)) : proxy_eq (await o $ more ∘ f) (await o $ more ∘ f') | think (f f') (step : ∀ (FR : proxy_cons x x' y y' m α → proxy_cons x x' y y' m α → Prop), reflexive FR → FR (think (more f)) (think (more f')) → FR f f') : proxy_eq (think $ more f) (think $ more f') protected lemma coinduction_eq (p₀ p₁ : proxy x x' y y' m α) (H : proxy_eq (to_cons p₀) (to_cons p₁)) : p₀ = p₁ := begin rw [← of_cons_to_cons p₀,← of_cons_to_cons p₁], revert H, generalize : to_cons p₀ = pp₀, generalize : to_cons p₁ = pp₁, intros H, apply cofix.coinduction, cases H ; simp [of_cons], cases H ; introv Hrefl Hfr Hij, { apply empty.rec' i, }, repeat { revert i j, rw [of_cons,children_mk,of_cons,children_mk], simp [proxy_nxt,head_mk,of_cons], intros, simp [of_cons] at Hfr, subst i, apply H_step (λ a b, FR (of_cons a) (of_cons b)) _ Hfr, intro, apply Hrefl, }, end protected def corec {S : Type w} (f : Π z : Type w, (S → proxy_leaf_v x x' y y' m z α) → S → proxy_v x x' y y' m z α) (s : S) : proxy x x' y y' m α := cofix.corec (λ s' : proxy_leaf_v x x' y y' m S α, match s' with | (hole s') := proxy.corec_aux (f _ hole s') | (more t) := proxy.corec_aux t end ) (hole s) protected def corec₂ {S₀ : Type w} {S₁ : Type w'} (f : Π z, (S₀ → S₁ → proxy_leaf_v x x' y y' m z α) → S₀ → S₁ → proxy_v x x' y y' m z α) (s₀ : S₀) (s₁ : S₁) : proxy x x' y y' m α := @proxy.corec α (S₀ × S₁) (λ z g s, f z (curry g) s.1 s.2) (s₀, s₁) end defs section seq open ulift proxy_v proxy_leaf_v parameters {m : Type u → Type v} variables {x x' y y' z z' α : Type u} def of_leaf : proxy_leaf x x' y y' m α → proxy_cons x x' y y' m α | (hole x) := to_cons x | (more x) := x def seq_push : proxy x x' y y' m α → proxy y y' z z' m α → proxy x x' z z' m α := λ a b, proxy.corec₂ (λ k (seq_push : proxy_leaf x x' y y' m α → proxy_leaf y y' z z' m α → proxy_leaf_v x x' z z' m k α) a b, match of_leaf a with | (ret i) := ret i | (action β cmd f) := action β cmd (λ i, seq_push (f i) b) | (yield o f) := match of_leaf b with | (ret i') := ret i' | (action β' cmd' f') := action β' cmd' $ λ i, seq_push a (f' i) | (yield o' f') := yield o' $ λ i, seq_push a (f' i) | (await o' f') := think $ seq_push (f o') (f' o) | (think f) := think $ seq_push a f end | (await o f) := await o $ λ i, seq_push (f i) b | (think f) := think $ seq_push f b end ) (hole a) (hole b) def seq_pull : proxy x x' y y' m α → proxy y y' z z' m α → proxy x x' z z' m α := λ a b, proxy.corec₂ (λ k (seq_pull : proxy_leaf x x' y y' m α → proxy_leaf y y' z z' m α → proxy_leaf_v x x' z z' m k α) a b, match of_leaf b with | (ret i) := ret i | (action β cmd f) := action β cmd (λ i, seq_pull a (f i)) | (await o f) := match of_leaf a with | (ret i') := ret i' | (action β' cmd' f') := action β' cmd' $ λ i, seq_pull (f' i) b | (await o' f') := await o' $ λ i, seq_pull (f' i) b | (yield o' f') := think $ seq_pull (f' o) (f o') | (think f) := think $ seq_pull f b end | (yield o f) := yield o $ λ i, seq_pull a (f i) | (think f) := think $ seq_pull a f end ) (hole a) (hole b) def const (i : y) : producer y m α := proxy.corec (λ z const _, yield i $ λ _, const ⊗) ⊗ def of_list : list y → producer y m punit := proxy.corec (λ z of_list (xs : list y), match xs with | i::xs := yield i $ λ _, of_list xs | [] := ret ⊗ end) def diverge : proxy x x' y y' m α := proxy.corec (λ z diverge _, think $ diverge ⊗) punit.star def map (f : x → y) : pipe x y m α := proxy.corec (λ z map u, await ⊗ $ λ i, more $ yield (f i) $ λ _, map ⊗) punit.star def mmap (f : x → m y) : pipe x y m α := proxy.corec (λ z map u, await ⊗ $ λ i, more $ action y (f i) $ λ r, more $ yield r $ λ _, map ⊗) punit.star def cat : pipe x x m α := map id -- EXAMPLE HERE end seq infixr ` >-> `:70 := seq_pull section lemmas parameters {m : Type u → Type v} variables {x x' y y' z z' α : Type u} open cofix lemma cat_seq (p : pipe x y m α) : cat >-> p = p := sorry lemma seq_cat (p : pipe x y m α) : p >-> cat = p := sorry lemma const_map (a : x) (f : x → y) : const a >-> map f = (const (f a) : producer y m α) := sorry lemma of_list_map (xs : list x) (f : x → y) : of_list xs >-> map f = (of_list (xs.map f) : producer y m punit) := sorry lemma map_seq_map (f : x → y) (g : y → z) : map f >-> map g = (proxy.map (g ∘ f) : pipe x z m α) := sorry lemma mmap_seq_mmap [monad m] (f : x → m y) (g : y → m z) : mmap f >-> mmap g = (mmap (λ i, f i >>= g) : pipe x z m α) := sorry -- protected def return (i : α) : proxy_cons x x' y y' m α := -- coind.corec (λ _, ⟨proxy₁.ret i,empty.rec'⟩) () -- section atomic -- variable cmd : proxy₁ x x' y y' m α -- variable h : proxy₂ cmd = α -- def s_atomic -- : option (proxy₂ cmd) → -- (Σ (y_1 : proxy₁ x x' y y' m α), proxy₂ y_1 → option (proxy₂ cmd)) -- | none := ⟨ cmd , some ⟩ -- | (some x) := ⟨ proxy₁.ret (cast h x), ulift.rec (empty.rec _) ⟩ -- def atomic : proxy x x' y y' m α := -- coind.corec.{(max u v+1) u u} -- (s_atomic cmd h) (@none $ proxy₂ cmd) -- end atomic -- section action -- variables (cmd : m α) -- protected def action : proxy x x' y y' m α := -- atomic (proxy₁.action cmd) rfl -- end action -- protected def lift (cmd : m α) : proxy x x' y y' m α := -- proxy.action cmd -- section await -- variables (i : x') -- protected def request : proxy x x' y y' m x := -- atomic (proxy₁.await i) rfl -- end await -- section yield -- variables (i : y) -- protected def respond : proxy x x' y y' m y' := -- atomic (proxy₁.yield i) rfl -- end yield -- section bind -- variables (cmd : proxy x x' y y' m α) -- variables (f : α → proxy x x' y y' m β) -- def state (α β : Type*) := proxy x x' y y' m α ⊕ proxy x x' y y' m β -- def t (α β) := (Σ (y_1 : proxy₁ x x' y y' m β), proxy₂ y_1 → state α β) -- def bind_aux' : Π (i : proxy₁ x x' y y' m α), -- (proxy₂ i → proxy x x' y y' m α) → -- t α β -- | (proxy₁.action m) xs := ⟨ proxy₁.action m, sum.inl ∘ xs⟩ -- | (proxy₁.ret r) xs := ⟨ coind.head (f r), sum.inr ∘ coind.children (f r) ⟩ -- | (proxy₁.await x) xs := ⟨ proxy₁.await x, sum.inl ∘ xs⟩ -- | (proxy₁.yield x) xs := ⟨ proxy₁.yield x, sum.inl ∘ xs⟩ -- | (proxy₁.think) xs := ⟨ proxy₁.think, sum.inl ∘ xs⟩ -- def bind_aux -- : state α β → t α β -- | (sum.inl param) := -- @coind.cases_on _ _ (λ _, t α β) param (bind_aux' f) -- | (sum.inr param) := -- ⟨ coind.head param, sum.inr ∘ coind.children param ⟩ -- protected def bind : proxy x x' y y' m β := -- coind.corec (bind_aux f) (sum.inl cmd) -- end bind -- instance : has_pure (proxy x x' y y' m) := -- ⟨ @proxy.return ⟩ -- instance : has_bind (proxy x x' y y' m) := -- ⟨ @proxy.bind ⟩ -- section -- variables (z : proxy x x' y y' m α) -- protected lemma id_map -- : z >>= (pure ∘ id) = z := -- sorry -- example (p : ℕ → Prop) (h : p 17) : ∃ i, p i := -- begin -- split, -- tactic.swap, -- abstract hh { exact 17 }, -- apply h, -- end -- end -- section -- variables (z : α) -- variables (f : α → proxy x x' y y' m β) -- protected lemma pure_bind -- : pure z >>= f = f z := -- sorry -- end -- section -- variables (z : proxy x x' y y' m α) -- variables (f : α → proxy x x' y y' m β) -- variables (g : β → proxy x x' y y' m γ) -- protected lemma bind_assoc -- : z >>= f >>= g = z >>= (λ i, f i >>= g) := -- sorry -- end -- instance : monad (proxy x x' y y' m) := -- { bind := @proxy.bind -- , pure := @proxy.return -- , id_map := @proxy.id_map -- , pure_bind := @proxy.pure_bind -- , bind_assoc := @proxy.bind_assoc } -- end proxy -- variables {γ x x' y y' : Type u} -- variables {m : Type u → Type v} -- variables {α β : Type u} -- protected def await : proxy x punit y y' m x := -- proxy.request punit.star -- protected def yield (i : y) : proxy x x' y punit m punit := -- proxy.respond i -- end proxy end lemmas end proxy
b1988ddfa157f5eacd6f37d8fdade1098ab61b64
80746c6dba6a866de5431094bf9f8f841b043d77
/src/topology/algebra/infinite_sum.lean
263ccbce764396d70673a50a74d3089f2b674396
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
21,230
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 Infinite sum over a topological monoid This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. -/ import logic.function algebra.big_operators data.set data.finset topology.metric_space.basic topology.algebra.topological_structures noncomputable theory open lattice finset filter function classical local attribute [instance] prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} section is_sum variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset α` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is still invariant under reordering, and a absolute sum operator. This is based on Mario Carneiro's infinite sum in Metamath. -/ def is_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, s.sum f) at_top (nhds a) /-- `has_sum f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def has_sum (f : β → α) : Prop := ∃a, is_sum f a /-- `tsum f` is the sum of `f` it exists, or 0 otherwise -/ def tsum (f : β → α) := if h : has_sum f then classical.some h else 0 notation `∑` binders `, ` r:(scoped f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma is_sum_tsum (ha : has_sum f) : is_sum f (∑b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum_spec (ha : is_sum f a) : has_sum f := ⟨a, ha⟩ lemma is_sum_zero : is_sum (λb, 0 : β → α) 0 := by simp [is_sum, tendsto_const_nhds] lemma has_sum_zero : has_sum (λb, 0 : β → α) := has_sum_spec is_sum_zero lemma is_sum_add (hf : is_sum f a) (hg : is_sum g b) : is_sum (λb, f b + g b) (a + b) := by simp [is_sum, sum_add_distrib]; exact tendsto_add hf hg lemma has_sum_add (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b + g b) := has_sum_spec $ is_sum_add (is_sum_tsum hf)(is_sum_tsum hg) lemma is_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, is_sum (f i) (a i)) → is_sum (λb, s.sum $ λi, f i b) (s.sum a) := finset.induction_on s (by simp [is_sum_zero]) (by simp [is_sum_add] {contextual := tt}) lemma has_sum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) : has_sum (λb, s.sum $ λi, f i b) := has_sum_spec $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi lemma is_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : is_sum f (s.sum f) := tendsto_infi' s $ tendsto_cong tendsto_const_nhds $ assume t (ht : s ⊆ t), show s.sum f = t.sum f, from sum_subset ht $ assume x _, hf _ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f := has_sum_spec $ is_sum_sum_of_ne_finset_zero hf lemma is_sum_ite (b : β) (a : α) : is_sum (λb', if b' = b then a else 0) a := suffices is_sum (λb', if b' = b then a else 0) (({b} : finset β).sum (λb', if b' = b then a else 0)), from by simpa, is_sum_sum_of_ne_finset_zero $ assume b' hb, have b' ≠ b, by simpa using hb, by rw [if_neg this] lemma is_sum_of_iso {j : γ → β} {i : β → γ} (hf : is_sum f a) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a := have ∀x y, j x = j y → x = y, from assume x y h, have i (j x) = i (j y), by rw [h], by rwa [h₁, h₁] at this, have (λs:finset γ, s.sum (f ∘ j)) = (λs:finset β, s.sum f) ∘ (λs:finset γ, s.image j), from funext $ assume s, (sum_image $ assume x _ y _, this x y).symm, show tendsto (λs:finset γ, s.sum (f ∘ j)) at_top (nhds a), by rw [this]; apply (tendsto_finset_image_at_top_at_top h₂).comp hf lemma is_sum_iff_is_sum_of_iso {j : γ → β} (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : is_sum (f ∘ j) a ↔ is_sum f a := iff.intro (assume hfj, have is_sum ((f ∘ j) ∘ i) a, from is_sum_of_iso hfj h₂ h₁, by simp [(∘), h₂] at this; assumption) (assume hf, is_sum_of_iso hf h₁ h₂) lemma is_sum_hom (g : α → γ) [add_comm_monoid γ] [topological_space γ] [topological_add_monoid γ] [is_add_monoid_hom g] (h₃ : continuous g) (hf : is_sum f a) : is_sum (g ∘ f) (g a) := have (λs:finset β, s.sum (g ∘ f)) = g ∘ (λs:finset β, s.sum f), from funext $ assume s, sum_hom g, show tendsto (λs:finset β, s.sum (g ∘ f)) at_top (nhds (g a)), by rw [this]; exact hf.comp (continuous_iff_tendsto.mp h₃ a) lemma tendsto_sum_nat_of_is_sum {f : ℕ → α} (h : is_sum f a) : tendsto (λn:ℕ, (range n).sum f) at_top (nhds a) := suffices map (λ (n : ℕ), sum (range n) f) at_top ≤ map (λ (s : finset ℕ), sum s f) at_top, from le_trans this h, assume s (hs : {t : finset ℕ | t.sum f ∈ s} ∈ at_top.sets), let ⟨t, ht⟩ := mem_at_top_sets.mp hs, ⟨n, hn⟩ := @exists_nat_subset_range t in mem_at_top_sets.mpr ⟨n, assume n' hn', ht _ $ finset.subset.trans hn $ range_subset.mpr hn'⟩ lemma is_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (hf : ∀b, is_sum (λc, f ⟨b, c⟩) (g b)) (ha : is_sum f a) : is_sum g a := assume s' hs', let ⟨s, hs, hss', hsc⟩ := nhds_is_closed hs', ⟨u, hu⟩ := mem_at_top_sets.mp $ ha $ hs, fsts := u.image sigma.fst, snds := λb, u.bind (λp, (if h : p.1 = b then {cast (congr_arg γ h) p.2} else ∅ : finset (γ b))) in have u_subset : u ⊆ fsts.sigma snds, from subset_iff.mpr $ assume ⟨b, c⟩ hu, have hb : b ∈ fsts, from finset.mem_image.mpr ⟨_, hu, rfl⟩, have hc : c ∈ snds b, from mem_bind.mpr ⟨_, hu, by simp; refl⟩, by simp [mem_sigma, hb, hc] , mem_at_top_sets.mpr $ exists.intro fsts $ assume bs (hbs : fsts ⊆ bs), have h : ∀cs : Π b ∈ bs, finset (γ b), (⋂b (hb : b ∈ bs), (λp:Πb, finset (γ b), p b) ⁻¹' {cs' | cs b hb ⊆ cs' }) ∩ (λp, bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) ⁻¹' s ≠ ∅, from assume cs, let cs' := λb, (if h : b ∈ bs then cs b h else ∅) ∪ snds b in have sum_eq : bs.sum (λb, (cs' b).sum (λc, f ⟨b, c⟩)) = (bs.sigma cs').sum f, from sum_sigma.symm, have (bs.sigma cs').sum f ∈ s, from hu _ $ finset.subset.trans u_subset $ sigma_mono hbs $ assume b, @finset.subset_union_right (γ b) _ _ _, set.ne_empty_iff_exists_mem.mpr $ exists.intro cs' $ by simp [sum_eq, this]; { intros b hb, simp [cs', hb, finset.subset_union_right] }, have tendsto (λp:(Πb:β, finset (γ b)), bs.sum (λb, (p b).sum (λc, f ⟨b, c⟩))) (⨅b (h : b ∈ bs), at_top.comap (λp, p b)) (nhds (bs.sum g)), from tendsto_finset_sum bs $ assume c hc, tendsto_infi' c $ tendsto_infi' hc $ tendsto_comap.comp (hf c), have bs.sum g ∈ s, from mem_of_closed_of_tendsto' this hsc $ forall_sets_neq_empty_iff_neq_bot.mp $ by simp [mem_inf_sets, exists_imp_distrib, and_imp, forall_and_distrib, filter.mem_infi_sets_finset, mem_comap_sets, skolem, mem_at_top_sets, and_comm]; from assume s₁ s₂ s₃ hs₁ hs₃ p hs₂ p' hp cs hp', have (⋂b (h : b ∈ bs), (λp:(Πb, finset (γ b)), p b) ⁻¹' {cs' | cs b h ⊆ cs' }) ≤ (⨅b∈bs, p b), from infi_le_infi $ assume b, infi_le_infi $ assume hb, le_trans (set.preimage_mono $ hp' b hb) (hp b hb), neq_bot_of_le_neq_bot (h _) (le_trans (set.inter_subset_inter (le_trans this hs₂) hs₃) hs₁), hss' this lemma has_sum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (hf : ∀b, has_sum (λc, f ⟨b, c⟩)) (ha : has_sum f) : has_sum (λb, ∑c, f ⟨b, c⟩):= has_sum_spec $ is_sum_sigma (assume b, is_sum_tsum $ hf b) (is_sum_tsum ha) end is_sum section is_sum_iff_is_sum_of_iso_ne_zero variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] variables {f : β → α} {g : γ → α} {a : α} lemma is_sum_of_is_sum (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (hf : is_sum g a) : is_sum f a := suffices at_top.map (λs:finset β, s.sum f) ≤ at_top.map (λs:finset γ, s.sum g), from le_trans this hf, by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma is_sum_iff_is_sum (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ u'.sum g = v'.sum f) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ v'.sum f = u'.sum g) : is_sum f a ↔ is_sum g a := ⟨is_sum_of_is_sum h₂, is_sum_of_is_sum h₁⟩ variables (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) include hi hj hji hij hgj lemma is_sum_of_is_sum_ne_zero : is_sum g a → is_sum f a := have j_inj : ∀x y (hx : f x ≠ 0) (hy : f y ≠ 0), (j hx = j hy ↔ x = y), from assume x y hx hy, ⟨assume h, have i (hj hx) = i (hj hy), by simp [h], by rwa [hij, hij] at this; assumption, by simp {contextual := tt}⟩, let ii : finset γ → finset β := λu, u.bind $ λc, if h : g c = 0 then ∅ else {i h} in let jj : finset β → finset γ := λv, v.bind $ λb, if h : f b = 0 then ∅ else {j h} in is_sum_of_is_sum $ assume u, exists.intro (ii u) $ assume v hv, exists.intro (u ∪ jj v) $ and.intro (subset_union_left _ _) $ have ∀c:γ, c ∈ u ∪ jj v → c ∉ jj v → g c = 0, from assume c hc hnc, classical.by_contradiction $ assume h : g c ≠ 0, have c ∈ u, from (finset.mem_union.1 hc).resolve_right hnc, have i h ∈ v, from hv $ by simp [mem_bind]; existsi c; simp [h, this], have j (hi h) ∈ jj v, by simp [mem_bind]; existsi i h; simp [h, hi, this], by rw [hji h] at this; exact hnc this, calc (u ∪ jj v).sum g = (jj v).sum g : (sum_subset (subset_union_right _ _) this).symm ... = v.sum _ : sum_bind $ by intros x hx y hy hxy; by_cases f x = 0; by_cases f y = 0; simp [*] ... = v.sum f : sum_congr rfl $ by intros x hx; by_cases f x = 0; simp [*] lemma is_sum_iff_is_sum_of_ne_zero : is_sum f a ↔ is_sum g a := iff.intro (is_sum_of_is_sum_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji]) (is_sum_of_is_sum_ne_zero i hi j hj hji hij hgj) lemma has_sum_iff_has_sum_ne_zero : has_sum g ↔ has_sum f := exists_congr $ assume a, is_sum_iff_is_sum_of_ne_zero j hj i hi hij hji $ assume b hb, by rw [←hgj (hi _), hji] end is_sum_iff_is_sum_of_iso_ne_zero section tsum variables [add_comm_monoid α] [topological_space α] [topological_add_monoid α] [t2_space α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_unique : is_sum f a₁ → is_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique at_top_ne_bot lemma tsum_eq_is_sum (ha : is_sum f a) : (∑b, f b) = a := is_sum_unique (is_sum_tsum ⟨a, ha⟩) ha lemma is_sum_iff_of_has_sum (h : has_sum f) : is_sum f a ↔ (∑b, f b) = a := iff.intro tsum_eq_is_sum (assume eq, eq ▸ is_sum_tsum h) @[simp] lemma tsum_zero : (∑b:β, 0:α) = 0 := tsum_eq_is_sum is_sum_zero lemma tsum_add (hf : has_sum f) (hg : has_sum g) : (∑b, f b + g b) = (∑b, f b) + (∑b, g b) := tsum_eq_is_sum $ is_sum_add (is_sum_tsum hf) (is_sum_tsum hg) lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, has_sum (f i)) : (∑b, s.sum (λi, f i b)) = s.sum (λi, ∑b, f i b) := tsum_eq_is_sum $ is_sum_sum $ assume i hi, is_sum_tsum $ hf i hi lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : (∑b, f b) = s.sum f := tsum_eq_is_sum $ is_sum_sum_of_ne_finset_zero hf lemma tsum_fintype [fintype β] (f : β → α) : (∑b, f b) = finset.univ.sum f := tsum_eq_sum $ λ a h, h.elim (mem_univ _) lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : (∑b, f b) = f b := calc (∑b, f b) = (finset.singleton b).sum f : tsum_eq_sum $ by simp [hf] {contextual := tt} ... = f b : by simp lemma tsum_sigma [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (h₁ : ∀b, has_sum (λc, f ⟨b, c⟩)) (h₂ : has_sum f) : (∑p, f p) = (∑b c, f ⟨b, c⟩):= (tsum_eq_is_sum $ is_sum_sigma (assume b, is_sum_tsum $ h₁ b) $ is_sum_tsum h₂).symm @[simp] lemma tsum_ite (b : β) (a : α) : (∑b', if b' = b then a else 0) = a := tsum_eq_is_sum (is_sum_ite b a) lemma tsum_eq_tsum_of_is_sum_iff_is_sum {f : β → α} {g : γ → α} (h : ∀{a}, is_sum f a ↔ is_sum g a) : (∑b, f b) = (∑c, g c) := by_cases (assume : ∃a, is_sum f a, let ⟨a, hfa⟩ := this in have hga : is_sum g a, from h.mp hfa, by rw [tsum_eq_is_sum hfa, tsum_eq_is_sum hga]) (assume hf : ¬ has_sum f, have hg : ¬ has_sum g, from assume ⟨a, hga⟩, hf ⟨a, h.mpr hga⟩, by simp [tsum, hf, hg]) lemma tsum_eq_tsum_of_ne_zero {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0) (j : Π⦃b⦄, f b ≠ 0 → γ) (hj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0) (hji : ∀⦃c⦄ (h : g c ≠ 0), j (hi h) = c) (hij : ∀⦃b⦄ (h : f b ≠ 0), i (hj h) = b) (hgj : ∀⦃b⦄ (h : f b ≠ 0), g (j h) = f b) : (∑i, f i) = (∑j, g j) := tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_ne_zero i hi j hj hji hij hgj lemma tsum_eq_tsum_of_ne_zero_bij {f : β → α} {g : γ → α} (i : Π⦃c⦄, g c ≠ 0 → β) (h₁ : ∀⦃c₁ c₂⦄ (h₁ : g c₁ ≠ 0) (h₂ : g c₂ ≠ 0), i h₁ = i h₂ → c₁ = c₂) (h₂ : ∀⦃b⦄, f b ≠ 0 → ∃c (h : g c ≠ 0), i h = b) (h₃ : ∀⦃c⦄ (h : g c ≠ 0), f (i h) = g c) : (∑i, f i) = (∑j, g j) := have hi : ∀⦃c⦄ (h : g c ≠ 0), f (i h) ≠ 0, from assume c h, by simp [h₃, h], let j : Π⦃b⦄, f b ≠ 0 → γ := λb h, some $ h₂ h in have hj : ∀⦃b⦄ (h : f b ≠ 0), ∃(h : g (j h) ≠ 0), i h = b, from assume b h, some_spec $ h₂ h, have hj₁ : ∀⦃b⦄ (h : f b ≠ 0), g (j h) ≠ 0, from assume b h, let ⟨h₁, _⟩ := hj h in h₁, have hj₂ : ∀⦃b⦄ (h : f b ≠ 0), i (hj₁ h) = b, from assume b h, let ⟨h₁, h₂⟩ := hj h in h₂, tsum_eq_tsum_of_ne_zero i hi j hj₁ (assume c h, h₁ (hj₁ _) h $ hj₂ _) hj₂ (assume b h, by rw [←h₃ (hj₁ _), hj₂]) lemma tsum_eq_tsum_of_iso (j : γ → β) (i : β → γ) (h₁ : ∀x, i (j x) = x) (h₂ : ∀x, j (i x) = x) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_is_sum_iff_is_sum $ assume a, is_sum_iff_is_sum_of_iso i h₁ h₂ lemma tsum_equiv (j : γ ≃ β) : (∑c, f (j c)) = (∑b, f b) := tsum_eq_tsum_of_iso j j.symm (by simp) (by simp) end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_neg : is_sum f a → is_sum (λb, - f b) (- a) := is_sum_hom has_neg.neg continuous_neg' lemma has_sum_neg (hf : has_sum f) : has_sum (λb, - f b) := has_sum_spec $ is_sum_neg $ is_sum_tsum $ hf lemma is_sum_sub (hf : is_sum f a₁) (hg : is_sum g a₂) : is_sum (λb, f b - g b) (a₁ - a₂) := by simp; exact is_sum_add hf (is_sum_neg hg) lemma has_sum_sub (hf : has_sum f) (hg : has_sum g) : has_sum (λb, f b - g b) := has_sum_spec $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg) section tsum variables [t2_space α] lemma tsum_neg (hf : has_sum f) : (∑b, - f b) = - (∑b, f b) := tsum_eq_is_sum $ is_sum_neg $ is_sum_tsum $ hf lemma tsum_sub (hf : has_sum f) (hg : has_sum g) : (∑b, f b - g b) = (∑b, f b) - (∑b, g b) := tsum_eq_is_sum $ is_sum_sub (is_sum_tsum hf) (is_sum_tsum hg) end tsum end topological_group section topological_semiring variables [semiring α] [topological_space α] [topological_semiring α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_mul_left (a₂) : is_sum f a₁ → is_sum (λb, a₂ * f b) (a₂ * a₁) := is_sum_hom _ (continuous_mul continuous_const continuous_id) lemma is_sum_mul_right (a₂) (hf : is_sum f a₁) : is_sum (λb, f b * a₂) (a₁ * a₂) := @is_sum_hom _ _ _ _ _ _ f a₁ (λa, a * a₂) _ _ _ _ (continuous_mul continuous_id continuous_const) hf lemma has_sum_mul_left (a) (hf : has_sum f) : has_sum (λb, a * f b) := has_sum_spec $ is_sum_mul_left _ $ is_sum_tsum hf lemma has_sum_mul_right (a) (hf : has_sum f) : has_sum (λb, f b * a) := has_sum_spec $ is_sum_mul_right _ $ is_sum_tsum hf section tsum variables [t2_space α] lemma tsum_mul_left (a) (hf : has_sum f) : (∑b, a * f b) = a * (∑b, f b) := tsum_eq_is_sum $ is_sum_mul_left _ $ is_sum_tsum hf lemma tsum_mul_right (a) (hf : has_sum f) : (∑b, f b * a) = (∑b, f b) * a := tsum_eq_is_sum $ is_sum_mul_right _ $ is_sum_tsum hf end tsum end topological_semiring section order_topology variables [ordered_comm_monoid α] [topological_space α] [ordered_topology α] [topological_add_monoid α] variables {f g : β → α} {a a₁ a₂ : α} lemma is_sum_le (h : ∀b, f b ≤ g b) (hf : is_sum f a₁) (hg : is_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto at_top_ne_bot hf hg $ univ_mem_sets' $ assume s, sum_le_sum' $ assume b _, h b lemma tsum_le_tsum (h : ∀b, f b ≤ g b) (hf : has_sum f) (hg : has_sum g) : (∑b, f b) ≤ (∑b, g b) := is_sum_le h (is_sum_tsum hf) (is_sum_tsum hg) end order_topology section uniform_group variables [add_comm_group α] [uniform_space α] [complete_space α] [uniform_add_group α] variables {f g : β → α} {a a₁ a₂ : α} /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma has_sum_of_has_sum_of_sub {f' : β → α} (hf : has_sum f) (h : ∀b, f' b = 0 ∨ f' b = f b) : has_sum f' := let ⟨a, hf⟩ := hf in suffices cauchy (at_top.map (λs:finset β, s.sum f')), from complete_space.complete this, ⟨map_ne_bot at_top_ne_bot, assume s' hs', have ∃t∈(@uniformity α _).sets, ∀{a₁ a₂ a₃ a₄}, (a₁, a₂) ∈ t → (a₃, a₄) ∈ t → (a₁ - a₃, a₂ - a₄) ∈ s', begin have h : {p:(α×α)×(α×α)| (p.1.1 - p.1.2, p.2.1 - p.2.2) ∈ s'} ∈ (@uniformity (α × α) _).sets, from uniform_continuous_sub' hs', rw [uniformity_prod_eq_prod, filter.mem_map, mem_prod_same_iff] at h, rcases h with ⟨t, ht, h⟩, exact ⟨t, ht, assume a₁ a₂ a₃ a₄ h₁ h₂, @h ((a₁, a₂), (a₃, a₄)) ⟨h₁, h₂⟩⟩ end, let ⟨s, hs, hss'⟩ := this in have cauchy (at_top.map (λs:finset β, s.sum f)), from cauchy_downwards cauchy_nhds (map_ne_bot at_top_ne_bot) hf, have ∃t, ∀u₁ u₂:finset β, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f, u₂.sum f) ∈ s, by simp [cauchy_iff, mem_at_top_sets, and.assoc, and.left_comm, and.comm] at this; from let ⟨t, ht, u, hu⟩ := this s hs in ⟨u, assume u₁ u₂ h₁ h₂, ht $ set.prod_mk_mem_set_prod_eq.mpr ⟨hu _ h₁, hu _ h₂⟩⟩, let ⟨t, ht⟩ := this in let d := (t.filter (λb, f' b = 0)).sum f in have eq : ∀{u}, t ⊆ u → (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = u.sum f', from assume u hu, have t ∪ u.filter (λb, f' b ≠ 0) = t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0), from finset.ext.2 $ assume b, by by_cases f' b = 0; simp [h, subset_iff.mp hu, iff_def, or_imp_distrib] {contextual := tt}, calc (t ∪ u.filter (λb, f' b ≠ 0)).sum f - d = (t.filter (λb, f' b = 0) ∪ u.filter (λb, f' b ≠ 0)).sum f - d : by rw [this] ... = (d + (u.filter (λb, f' b ≠ 0)).sum f) - d : by rw [sum_union]; exact (finset.ext.2 $ by simp {contextual := tt}) ... = (u.filter (λb, f' b ≠ 0)).sum f : by simp ... = (u.filter (λb, f' b ≠ 0)).sum f' : sum_congr rfl $ assume b, by have h := h b; cases h with h h; simp [*] ... = u.sum f' : by apply sum_subset; by simp [subset_iff, not_not] {contextual := tt}, have ∀{u₁ u₂}, t ⊆ u₁ → t ⊆ u₂ → (u₁.sum f', u₂.sum f') ∈ s', from assume u₁ u₂ h₁ h₂, have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f) ∈ s, from ht _ _ (subset_union_left _ _) (subset_union_left _ _), have ((t ∪ u₁.filter (λb, f' b ≠ 0)).sum f - d, (t ∪ u₂.filter (λb, f' b ≠ 0)).sum f - d) ∈ s', from hss' this $ refl_mem_uniformity hs, by rwa [eq h₁, eq h₂] at this, mem_prod_same_iff.mpr ⟨(λu:finset β, u.sum f') '' {u | t ⊆ u}, image_mem_map $ mem_at_top t, assume ⟨a₁, a₂⟩ ⟨⟨t₁, h₁, eq₁⟩, ⟨t₂, h₂, eq₂⟩⟩, by simp at eq₁ eq₂; rw [←eq₁, ←eq₂]; exact this h₁ h₂⟩⟩ end uniform_group
43acae82743f37a21f206051e896421f73e31989
626e312b5c1cb2d88fca108f5933076012633192
/src/analysis/normed_space/linear_isometry.lean
6d09f8ed8abf694ec95e957f274dba956aa8479b
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,001
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 analysis.normed_space.basic import linear_algebra.finite_dimensional /-! # Linear isometries In this file we define `linear_isometry R E F` (notation: `E →ₗᵢ[R] F`) to be a linear isometric embedding of `E` into `F` and `linear_isometry_equiv` (notation: `E ≃ₗᵢ[R] F`) to be a linear isometric equivalence between `E` and `F`. We also prove some trivial lemmas and provide convenience constructors. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory for `semi_normed_space` and we specialize to `normed_space` when needed. -/ open function set variables {R E F G G' E₁ : Type*} [semiring R] [semi_normed_group E] [semi_normed_group F] [semi_normed_group G] [semi_normed_group G'] [module R E] [module R F] [module R G] [module R G'] [normed_group E₁] [module R E₁] /-- An `R`-linear isometric embedding of one normed `R`-module into another. -/ structure linear_isometry (R E F : Type*) [semiring R] [semi_normed_group E] [semi_normed_group F] [module R E] [module R F] extends E →ₗ[R] F := (norm_map' : ∀ x, ∥to_linear_map x∥ = ∥x∥) notation E ` →ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry R E F namespace linear_isometry /-- We use `f₁` when we need the domain to be a `normed_space`. -/ variables (f : E →ₗᵢ[R] F) (f₁ : E₁ →ₗᵢ[R] F) instance : has_coe_to_fun (E →ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_to_linear_map : ⇑f.to_linear_map = f := rfl lemma to_linear_map_injective : injective (to_linear_map : (E →ₗᵢ[R] F) → (E →ₗ[R] F)) | ⟨f, _⟩ ⟨g, _⟩ rfl := rfl lemma coe_fn_injective : injective (λ (f : E →ₗᵢ[R] F) (x : E), f x) := linear_map.coe_injective.comp to_linear_map_injective @[ext] lemma ext {f g : E →ₗᵢ[R] F} (h : ∀ x, f x = g x) : f = g := coe_fn_injective $ funext h @[simp] lemma map_zero : f 0 = 0 := f.to_linear_map.map_zero @[simp] lemma map_add (x y : E) : f (x + y) = f x + f y := f.to_linear_map.map_add x y @[simp] lemma map_sub (x y : E) : f (x - y) = f x - f y := f.to_linear_map.map_sub x y @[simp] lemma map_smul (c : R) (x : E) : f (c • x) = c • f x := f.to_linear_map.map_smul c x @[simp] lemma norm_map (x : E) : ∥f x∥ = ∥x∥ := f.norm_map' x @[simp] lemma nnnorm_map (x : E) : nnnorm (f x) = nnnorm x := nnreal.eq $ f.norm_map x protected lemma isometry : isometry f := f.to_linear_map.to_add_monoid_hom.isometry_of_norm f.norm_map @[simp] lemma dist_map (x y : E) : dist (f x) (f y) = dist x y := f.isometry.dist_eq x y @[simp] lemma edist_map (x y : E) : edist (f x) (f y) = edist x y := f.isometry.edist_eq x y protected lemma injective : injective f₁ := f₁.isometry.injective @[simp] lemma map_eq_iff {x y : E₁} : f₁ x = f₁ y ↔ x = y := f₁.injective.eq_iff lemma map_ne {x y : E₁} (h : x ≠ y) : f₁ x ≠ f₁ y := f₁.injective.ne h protected lemma lipschitz : lipschitz_with 1 f := f.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 f := f.isometry.antilipschitz @[continuity] protected lemma continuous : continuous f := f.isometry.continuous lemma ediam_image (s : set E) : emetric.diam (f '' s) = emetric.diam s := f.isometry.ediam_image s lemma ediam_range : emetric.diam (range f) = emetric.diam (univ : set E) := f.isometry.ediam_range lemma diam_image (s : set E) : metric.diam (f '' s) = metric.diam s := f.isometry.diam_image s lemma diam_range : metric.diam (range f) = metric.diam (univ : set E) := f.isometry.diam_range /-- Interpret a linear isometry as a continuous linear map. -/ def to_continuous_linear_map : E →L[R] F := ⟨f.to_linear_map, f.continuous⟩ @[simp] lemma coe_to_continuous_linear_map : ⇑f.to_continuous_linear_map = f := rfl @[simp] lemma comp_continuous_iff {α : Type*} [topological_space α] {g : α → E} : continuous (f ∘ g) ↔ continuous g := f.isometry.comp_continuous_iff /-- The identity linear isometry. -/ def id : E →ₗᵢ[R] E := ⟨linear_map.id, λ x, rfl⟩ @[simp] lemma coe_id : ⇑(id : E →ₗᵢ[R] E) = _root_.id := rfl @[simp] lemma id_apply (x : E) : (id : E →ₗᵢ[R] E) x = x := rfl @[simp] lemma id_to_linear_map : (id.to_linear_map : E →ₗ[R] E) = linear_map.id := rfl instance : inhabited (E →ₗᵢ[R] E) := ⟨id⟩ /-- Composition of linear isometries. -/ def comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : E →ₗᵢ[R] G := ⟨g.to_linear_map.comp f.to_linear_map, λ x, (g.norm_map _).trans (f.norm_map _)⟩ @[simp] lemma coe_comp (g : F →ₗᵢ[R] G) (f : E →ₗᵢ[R] F) : ⇑(g.comp f) = g ∘ f := rfl @[simp] lemma id_comp : (id : F →ₗᵢ[R] F).comp f = f := ext $ λ x, rfl @[simp] lemma comp_id : f.comp id = f := ext $ λ x, rfl lemma comp_assoc (f : G →ₗᵢ[R] G') (g : F →ₗᵢ[R] G) (h : E →ₗᵢ[R] F) : (f.comp g).comp h = f.comp (g.comp h) := rfl instance : monoid (E →ₗᵢ[R] E) := { one := id, mul := comp, mul_assoc := comp_assoc, one_mul := id_comp, mul_one := comp_id } @[simp] lemma coe_one : ⇑(1 : E →ₗᵢ[R] E) = id := rfl @[simp] lemma coe_mul (f g : E →ₗᵢ[R] E) : ⇑(f * g) = f ∘ g := rfl end linear_isometry namespace submodule variables {R' : Type*} [ring R'] [module R' E] (p : submodule R' E) /-- `submodule.subtype` as a `linear_isometry`. -/ def subtypeₗᵢ : p →ₗᵢ[R'] E := ⟨p.subtype, λ x, rfl⟩ @[simp] lemma coe_subtypeₗᵢ : ⇑p.subtypeₗᵢ = p.subtype := rfl @[simp] lemma subtypeₗᵢ_to_linear_map : p.subtypeₗᵢ.to_linear_map = p.subtype := rfl /-- `submodule.subtype` as a `continuous_linear_map`. -/ def subtypeL : p →L[R'] E := p.subtypeₗᵢ.to_continuous_linear_map @[simp] lemma coe_subtypeL : (p.subtypeL : p →ₗ[R'] E) = p.subtype := rfl @[simp] lemma coe_subtypeL' : ⇑p.subtypeL = p.subtype := rfl @[simp] lemma range_subtypeL : p.subtypeL.range = p := range_subtype _ @[simp] lemma ker_subtypeL : p.subtypeL.ker = ⊥ := ker_subtype _ end submodule /-- A linear isometric equivalence between two normed vector spaces. -/ structure linear_isometry_equiv (R E F : Type*) [semiring R] [semi_normed_group E] [semi_normed_group F] [module R E] [module R F] extends E ≃ₗ[R] F := (norm_map' : ∀ x, ∥to_linear_equiv x∥ = ∥x∥) notation E ` ≃ₗᵢ[`:25 R:25 `] `:0 F:0 := linear_isometry_equiv R E F namespace linear_isometry_equiv variables (e : E ≃ₗᵢ[R] F) instance : has_coe_to_fun (E ≃ₗᵢ[R] F) := ⟨_, λ f, f.to_fun⟩ @[simp] lemma coe_mk (e : E ≃ₗ[R] F) (he : ∀ x, ∥e x∥ = ∥x∥) : ⇑(mk e he) = e := rfl @[simp] lemma coe_to_linear_equiv (e : E ≃ₗᵢ[R] F) : ⇑e.to_linear_equiv = e := rfl lemma to_linear_equiv_injective : injective (to_linear_equiv : (E ≃ₗᵢ[R] F) → (E ≃ₗ[R] F)) | ⟨e, _⟩ ⟨_, _⟩ rfl := rfl @[ext] lemma ext {e e' : E ≃ₗᵢ[R] F} (h : ∀ x, e x = e' x) : e = e' := to_linear_equiv_injective $ linear_equiv.ext h /-- Construct a `linear_isometry_equiv` from a `linear_equiv` and two inequalities: `∀ x, ∥e x∥ ≤ ∥x∥` and `∀ y, ∥e.symm y∥ ≤ ∥y∥`. -/ def of_bounds (e : E ≃ₗ[R] F) (h₁ : ∀ x, ∥e x∥ ≤ ∥x∥) (h₂ : ∀ y, ∥e.symm y∥ ≤ ∥y∥) : E ≃ₗᵢ[R] F := ⟨e, λ x, le_antisymm (h₁ x) $ by simpa only [e.symm_apply_apply] using h₂ (e x)⟩ @[simp] lemma norm_map (x : E) : ∥e x∥ = ∥x∥ := e.norm_map' x /-- Reinterpret a `linear_isometry_equiv` as a `linear_isometry`. -/ def to_linear_isometry : E →ₗᵢ[R] F := ⟨e.1, e.2⟩ @[simp] lemma coe_to_linear_isometry : ⇑e.to_linear_isometry = e := rfl protected lemma isometry : isometry e := e.to_linear_isometry.isometry /-- Reinterpret a `linear_isometry_equiv` as an `isometric`. -/ def to_isometric : E ≃ᵢ F := ⟨e.to_linear_equiv.to_equiv, e.isometry⟩ @[simp] lemma coe_to_isometric : ⇑e.to_isometric = e := rfl lemma range_eq_univ (e : E ≃ₗᵢ[R] F) : set.range e = set.univ := by { rw ← coe_to_isometric, exact isometric.range_eq_univ _, } /-- Reinterpret a `linear_isometry_equiv` as an `homeomorph`. -/ def to_homeomorph : E ≃ₜ F := e.to_isometric.to_homeomorph @[simp] lemma coe_to_homeomorph : ⇑e.to_homeomorph = e := rfl protected lemma continuous : continuous e := e.isometry.continuous protected lemma continuous_at {x} : continuous_at e x := e.continuous.continuous_at protected lemma continuous_on {s} : continuous_on e s := e.continuous.continuous_on protected lemma continuous_within_at {s x} : continuous_within_at e s x := e.continuous.continuous_within_at /-- Interpret a `linear_isometry_equiv` as a continuous linear equiv. -/ def to_continuous_linear_equiv : E ≃L[R] F := { .. e.to_linear_isometry.to_continuous_linear_map, .. e.to_homeomorph } @[simp] lemma coe_to_continuous_linear_equiv : ⇑e.to_continuous_linear_equiv = e := rfl variables (R E) /-- Identity map as a `linear_isometry_equiv`. -/ def refl : E ≃ₗᵢ[R] E := ⟨linear_equiv.refl R E, λ x, rfl⟩ variables {R E} instance : inhabited (E ≃ₗᵢ[R] E) := ⟨refl R E⟩ @[simp] lemma coe_refl : ⇑(refl R E) = id := rfl /-- The inverse `linear_isometry_equiv`. -/ def symm : F ≃ₗᵢ[R] E := ⟨e.to_linear_equiv.symm, λ x, (e.norm_map _).symm.trans $ congr_arg norm $ e.to_linear_equiv.apply_symm_apply x⟩ @[simp] lemma apply_symm_apply (x : F) : e (e.symm x) = x := e.to_linear_equiv.apply_symm_apply x @[simp] lemma symm_apply_apply (x : E) : e.symm (e x) = x := e.to_linear_equiv.symm_apply_apply x @[simp] lemma map_eq_zero_iff {x : E} : e x = 0 ↔ x = 0 := e.to_linear_equiv.map_eq_zero_iff @[simp] lemma symm_symm : e.symm.symm = e := ext $ λ x, rfl @[simp] lemma to_linear_equiv_symm : e.to_linear_equiv.symm = e.symm.to_linear_equiv := rfl @[simp] lemma to_isometric_symm : e.to_isometric.symm = e.symm.to_isometric := rfl @[simp] lemma to_homeomorph_symm : e.to_homeomorph.symm = e.symm.to_homeomorph := rfl /-- Composition of `linear_isometry_equiv`s as a `linear_isometry_equiv`. -/ def trans (e' : F ≃ₗᵢ[R] G) : E ≃ₗᵢ[R] G := ⟨e.to_linear_equiv.trans e'.to_linear_equiv, λ x, (e'.norm_map _).trans (e.norm_map _)⟩ @[simp] lemma coe_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp] lemma trans_refl : e.trans (refl R F) = e := ext $ λ x, rfl @[simp] lemma refl_trans : (refl R E).trans e = e := ext $ λ x, rfl @[simp] lemma trans_symm : e.trans e.symm = refl R E := ext e.symm_apply_apply @[simp] lemma symm_trans : e.symm.trans e = refl R F := ext e.apply_symm_apply @[simp] lemma coe_symm_trans (e₁ : E ≃ₗᵢ[R] F) (e₂ : F ≃ₗᵢ[R] G) : ⇑(e₁.trans e₂).symm = e₁.symm ∘ e₂.symm := rfl lemma trans_assoc (eEF : E ≃ₗᵢ[R] F) (eFG : F ≃ₗᵢ[R] G) (eGG' : G ≃ₗᵢ[R] G') : eEF.trans (eFG.trans eGG') = (eEF.trans eFG).trans eGG' := rfl instance : group (E ≃ₗᵢ[R] E) := { mul := λ e₁ e₂, e₂.trans e₁, one := refl _ _, inv := symm, one_mul := trans_refl, mul_one := refl_trans, mul_assoc := λ _ _ _, trans_assoc _ _ _, mul_left_inv := trans_symm } @[simp] lemma coe_one : ⇑(1 : E ≃ₗᵢ[R] E) = id := rfl @[simp] lemma coe_mul (e e' : E ≃ₗᵢ[R] E) : ⇑(e * e') = e ∘ e' := rfl @[simp] lemma coe_inv (e : E ≃ₗᵢ[R] E) : ⇑(e⁻¹) = e.symm := rfl /-- Reinterpret a `linear_isometry_equiv` as a `continuous_linear_equiv`. -/ instance : has_coe_t (E ≃ₗᵢ[R] F) (E ≃L[R] F) := ⟨λ e, ⟨e.to_linear_equiv, e.continuous, e.to_isometric.symm.continuous⟩⟩ instance : has_coe_t (E ≃ₗᵢ[R] F) (E →L[R] F) := ⟨λ e, ↑(e : E ≃L[R] F)⟩ @[simp] lemma coe_coe : ⇑(e : E ≃L[R] F) = e := rfl @[simp] lemma coe_coe' : ((e : E ≃L[R] F) : E →L[R] F) = e := rfl @[simp] lemma coe_coe'' : ⇑(e : E →L[R] F) = e := rfl @[simp] lemma map_zero : e 0 = 0 := e.1.map_zero @[simp] lemma map_add (x y : E) : e (x + y) = e x + e y := e.1.map_add x y @[simp] lemma map_sub (x y : E) : e (x - y) = e x - e y := e.1.map_sub x y @[simp] lemma map_smul (c : R) (x : E) : e (c • x) = c • e x := e.1.map_smul c x @[simp] lemma nnnorm_map (x : E) : nnnorm (e x) = nnnorm x := e.to_linear_isometry.nnnorm_map x @[simp] lemma dist_map (x y : E) : dist (e x) (e y) = dist x y := e.to_linear_isometry.dist_map x y @[simp] lemma edist_map (x y : E) : edist (e x) (e y) = edist x y := e.to_linear_isometry.edist_map x y protected lemma bijective : bijective e := e.1.bijective protected lemma injective : injective e := e.1.injective protected lemma surjective : surjective e := e.1.surjective @[simp] lemma map_eq_iff {x y : E} : e x = e y ↔ x = y := e.injective.eq_iff lemma map_ne {x y : E} (h : x ≠ y) : e x ≠ e y := e.injective.ne h protected lemma lipschitz : lipschitz_with 1 e := e.isometry.lipschitz protected lemma antilipschitz : antilipschitz_with 1 e := e.isometry.antilipschitz @[simp] lemma ediam_image (s : set E) : emetric.diam (e '' s) = emetric.diam s := e.isometry.ediam_image s @[simp] lemma diam_image (s : set E) : metric.diam (e '' s) = metric.diam s := e.isometry.diam_image s variables {α : Type*} [topological_space α] @[simp] lemma comp_continuous_on_iff {f : α → E} {s : set α} : continuous_on (e ∘ f) s ↔ continuous_on f s := e.isometry.comp_continuous_on_iff @[simp] lemma comp_continuous_iff {f : α → E} : continuous (e ∘ f) ↔ continuous f := e.isometry.comp_continuous_iff variables (R) /-- The negation operation on a normed space `E`, considered as a linear isometry equivalence. -/ def neg : E ≃ₗᵢ[R] E := { norm_map' := norm_neg, .. linear_equiv.neg R } variables {R} @[simp] lemma coe_neg : (neg R : E → E) = λ x, -x := rfl @[simp] lemma symm_neg : (neg R : E ≃ₗᵢ[R] E).symm = neg R := rfl end linear_isometry_equiv namespace linear_isometry open finite_dimensional linear_map variables {R₁ : Type*} [field R₁] [module R₁ E₁] [module R₁ F] [finite_dimensional R₁ E₁] [finite_dimensional R₁ F] /-- A linear isometry between finite dimensional spaces of equal dimension can be upgraded to a linear isometry equivalence. -/ noncomputable def to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : E₁ ≃ₗᵢ[R₁] F := { to_linear_equiv := li.to_linear_map.linear_equiv_of_ker_eq_bot (ker_eq_bot_of_injective li.injective) h, norm_map' := li.norm_map' } @[simp] lemma coe_to_linear_isometry_equiv (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) : (li.to_linear_isometry_equiv h : E₁ → F) = li := rfl @[simp] lemma to_linear_isometry_equiv_apply (li : E₁ →ₗᵢ[R₁] F) (h : finrank R₁ E₁ = finrank R₁ F) (x : E₁) : (li.to_linear_isometry_equiv h) x = li x := rfl end linear_isometry
a381a176f45ef55e54ae9e469ec88ddaa9a80bd3
94e33a31faa76775069b071adea97e86e218a8ee
/src/category_theory/limits/comma.lean
503cf89bb4d86bb2804be3d690facd36b5aa0bcf
[ "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,351
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.creates import category_theory.limits.unit import category_theory.limits.preserves.basic import category_theory.structured_arrow import category_theory.arrow /-! # Limits and colimits in comma categories We build limits in the comma category `comma L R` provided that the two source categories have limits and `R` preserves them. This is used to construct limits in the arrow category, structured arrow category and under category, and show that the appropriate forgetful functors create limits. The duals of all the above are also given. -/ namespace category_theory open category limits universes v u₁ u₂ u₃ variables {J : Type v} [small_category J] variables {A : Type u₁} [category.{v} A] variables {B : Type u₂} [category.{v} B] variables {T : Type u₃} [category.{v} T] namespace comma variables {L : A ⥤ T} {R : B ⥤ T} variables (F : J ⥤ comma L R) /-- (Implementation). An auxiliary cone which is useful in order to construct limits in the comma category. -/ @[simps] def limit_auxiliary_cone (c₁ : cone (F ⋙ fst L R)) : cone ((F ⋙ snd L R) ⋙ R) := (cones.postcompose (whisker_left F (comma.nat_trans L R) : _)).obj (L.map_cone c₁) /-- If `R` preserves the appropriate limit, then given a cone for `F ⋙ fst L R : J ⥤ L` and a limit cone for `F ⋙ snd L R : J ⥤ R` we can build a cone for `F` which will turn out to be a limit cone. -/ @[simps] def cone_of_preserves [preserves_limit (F ⋙ snd L R) R] (c₁ : cone (F ⋙ fst L R)) {c₂ : cone (F ⋙ snd L R)} (t₂ : is_limit c₂) : cone F := { X := { left := c₁.X, right := c₂.X, hom := (is_limit_of_preserves R t₂).lift (limit_auxiliary_cone _ c₁) }, π := { app := λ j, { left := c₁.π.app j, right := c₂.π.app j, w' := ((is_limit_of_preserves R t₂).fac (limit_auxiliary_cone F c₁) j).symm }, naturality' := λ j₁ j₂ t, by ext; dsimp; simp [←c₁.w t, ←c₂.w t] } } /-- Provided that `R` preserves the appropriate limit, then the cone in `cone_of_preserves` is a limit. -/ def cone_of_preserves_is_limit [preserves_limit (F ⋙ snd L R) R] {c₁ : cone (F ⋙ fst L R)} (t₁ : is_limit c₁) {c₂ : cone (F ⋙ snd L R)} (t₂ : is_limit c₂) : is_limit (cone_of_preserves F c₁ t₂) := { lift := λ s, { left := t₁.lift ((fst L R).map_cone s), right := t₂.lift ((snd L R).map_cone s), w' := (is_limit_of_preserves R t₂).hom_ext $ λ j, begin rw [cone_of_preserves_X_hom, assoc, assoc, (is_limit_of_preserves R t₂).fac, limit_auxiliary_cone_π_app, ←L.map_comp_assoc, t₁.fac, R.map_cone_π_app, ←R.map_comp, t₂.fac], exact (s.π.app j).w, end }, uniq' := λ s m w, comma_morphism.ext _ _ (t₁.uniq ((fst L R).map_cone s) _ (λ j, by simp [←w])) (t₂.uniq ((snd L R).map_cone s) _ (λ j, by simp [←w])) } /-- (Implementation). An auxiliary cocone which is useful in order to construct colimits in the comma category. -/ @[simps] def colimit_auxiliary_cocone (c₂ : cocone (F ⋙ snd L R)) : cocone ((F ⋙ fst L R) ⋙ L) := (cocones.precompose (whisker_left F (comma.nat_trans L R) : _)).obj (R.map_cocone c₂) /-- If `L` preserves the appropriate colimit, then given a colimit cocone for `F ⋙ fst L R : J ⥤ L` and a cocone for `F ⋙ snd L R : J ⥤ R` we can build a cocone for `F` which will turn out to be a colimit cocone. -/ @[simps] def cocone_of_preserves [preserves_colimit (F ⋙ fst L R) L] {c₁ : cocone (F ⋙ fst L R)} (t₁ : is_colimit c₁) (c₂ : cocone (F ⋙ snd L R)) : cocone F := { X := { left := c₁.X, right := c₂.X, hom := (is_colimit_of_preserves L t₁).desc (colimit_auxiliary_cocone _ c₂) }, ι := { app := λ j, { left := c₁.ι.app j, right := c₂.ι.app j, w' := ((is_colimit_of_preserves L t₁).fac (colimit_auxiliary_cocone _ c₂) j) }, naturality' := λ j₁ j₂ t, by ext; dsimp; simp [←c₁.w t, ←c₂.w t] } } /-- Provided that `L` preserves the appropriate colimit, then the cocone in `cocone_of_preserves` is a colimit. -/ def cocone_of_preserves_is_colimit [preserves_colimit (F ⋙ fst L R) L] {c₁ : cocone (F ⋙ fst L R)} (t₁ : is_colimit c₁) {c₂ : cocone (F ⋙ snd L R)} (t₂ : is_colimit c₂) : is_colimit (cocone_of_preserves F t₁ c₂) := { desc := λ s, { left := t₁.desc ((fst L R).map_cocone s), right := t₂.desc ((snd L R).map_cocone s), w' := (is_colimit_of_preserves L t₁).hom_ext $ λ j, begin rw [cocone_of_preserves_X_hom, (is_colimit_of_preserves L t₁).fac_assoc, colimit_auxiliary_cocone_ι_app, assoc, ←R.map_comp, t₂.fac, L.map_cocone_ι_app, ←L.map_comp_assoc, t₁.fac], exact (s.ι.app j).w, end }, uniq' := λ s m w, comma_morphism.ext _ _ (t₁.uniq ((fst L R).map_cocone s) _ (by simp [←w])) (t₂.uniq ((snd L R).map_cocone s) _ (by simp [←w])) } instance has_limit (F : J ⥤ comma L R) [has_limit (F ⋙ fst L R)] [has_limit (F ⋙ snd L R)] [preserves_limit (F ⋙ snd L R) R] : has_limit F := has_limit.mk ⟨_, cone_of_preserves_is_limit _ (limit.is_limit _) (limit.is_limit _)⟩ instance has_limits_of_shape [has_limits_of_shape J A] [has_limits_of_shape J B] [preserves_limits_of_shape J R] : has_limits_of_shape J (comma L R) := {} instance has_limits [has_limits A] [has_limits B] [preserves_limits R] : has_limits (comma L R) := ⟨infer_instance⟩ instance has_colimit (F : J ⥤ comma L R) [has_colimit (F ⋙ fst L R)] [has_colimit (F ⋙ snd L R)] [preserves_colimit (F ⋙ fst L R) L] : has_colimit F := has_colimit.mk ⟨_, cocone_of_preserves_is_colimit _ (colimit.is_colimit _) (colimit.is_colimit _)⟩ instance has_colimits_of_shape [has_colimits_of_shape J A] [has_colimits_of_shape J B] [preserves_colimits_of_shape J L] : has_colimits_of_shape J (comma L R) := {} instance has_colimits [has_colimits A] [has_colimits B] [preserves_colimits L] : has_colimits (comma L R) := ⟨infer_instance⟩ end comma namespace arrow instance has_limit (F : J ⥤ arrow T) [i₁ : has_limit (F ⋙ left_func)] [i₂ : has_limit (F ⋙ right_func)] : has_limit F := @@comma.has_limit _ _ _ _ _ i₁ i₂ _ instance has_limits_of_shape [has_limits_of_shape J T] : has_limits_of_shape J (arrow T) := {} instance has_limits [has_limits T] : has_limits (arrow T) := ⟨infer_instance⟩ instance has_colimit (F : J ⥤ arrow T) [i₁ : has_colimit (F ⋙ left_func)] [i₂ : has_colimit (F ⋙ right_func)] : has_colimit F := @@comma.has_colimit _ _ _ _ _ i₁ i₂ _ instance has_colimits_of_shape [has_colimits_of_shape J T] : has_colimits_of_shape J (arrow T) := {} instance has_colimits [has_colimits T] : has_colimits (arrow T) := ⟨infer_instance⟩ end arrow namespace structured_arrow variables {X : T} {G : A ⥤ T} (F : J ⥤ structured_arrow X G) instance has_limit [i₁ : has_limit (F ⋙ proj X G)] [i₂ : preserves_limit (F ⋙ proj X G) G] : has_limit F := @@comma.has_limit _ _ _ _ _ _ i₁ i₂ instance has_limits_of_shape [has_limits_of_shape J A] [preserves_limits_of_shape J G] : has_limits_of_shape J (structured_arrow X G) := {} instance has_limits [has_limits A] [preserves_limits G] : has_limits (structured_arrow X G) := ⟨infer_instance⟩ noncomputable instance creates_limit [i : preserves_limit (F ⋙ proj X G) G] : creates_limit F (proj X G) := creates_limit_of_reflects_iso $ λ c t, { lifted_cone := @@comma.cone_of_preserves _ _ _ _ _ i punit_cone t, makes_limit := comma.cone_of_preserves_is_limit _ punit_cone_is_limit _, valid_lift := cones.ext (iso.refl _) $ λ j, (id_comp _).symm } noncomputable instance creates_limits_of_shape [preserves_limits_of_shape J G] : creates_limits_of_shape J (proj X G) := {} noncomputable instance creates_limits [preserves_limits G] : creates_limits (proj X G : _) := ⟨⟩ end structured_arrow namespace costructured_arrow variables {G : A ⥤ T} {X : T} (F : J ⥤ costructured_arrow G X) instance has_colimit [i₁ : has_colimit (F ⋙ proj G X)] [i₂ : preserves_colimit (F ⋙ proj G X) G] : has_colimit F := @@comma.has_colimit _ _ _ _ _ i₁ _ i₂ instance has_colimits_of_shape [has_colimits_of_shape J A] [preserves_colimits_of_shape J G] : has_colimits_of_shape J (costructured_arrow G X) := {} instance has_colimits [has_colimits A] [preserves_colimits G] : has_colimits (costructured_arrow G X) := ⟨infer_instance⟩ noncomputable instance creates_colimit [i : preserves_colimit (F ⋙ proj G X) G] : creates_colimit F (proj G X) := creates_colimit_of_reflects_iso $ λ c t, { lifted_cocone := @@comma.cocone_of_preserves _ _ _ _ _ i t punit_cocone, makes_colimit := comma.cocone_of_preserves_is_colimit _ _ punit_cocone_is_colimit, valid_lift := cocones.ext (iso.refl _) $ λ j, comp_id _ } noncomputable instance creates_colimits_of_shape [preserves_colimits_of_shape J G] : creates_colimits_of_shape J (proj G X) := {} noncomputable instance creates_colimits [preserves_colimits G] : creates_colimits (proj G X : _) := ⟨⟩ end costructured_arrow end category_theory
b1d2b983a8a93055e481c115f2a67aab0b85a278
94e33a31faa76775069b071adea97e86e218a8ee
/src/probability/independence.lean
220694ebf6dadfc4fe6070fdcece6a208e8d0284
[ "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
31,953
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import algebra.big_operators.intervals import measure_theory.constructions.pi /-! # Independence of sets of sets and measure spaces (σ-algebras) * A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of π-systems. * A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. I.e., `m : ι → measurable_space α` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i)`. * Independence of sets (or events in probabilistic parlance) is defined as independence of the measurable space structures they generate: a set `s` generates the measurable space structure with measurable sets `∅, s, sᶜ, univ`. * Independence of functions (or random variables) is also defined as independence of the measurable space structures they generate: a function `f` for which we have a measurable space `m` on the codomain generates `measurable_space.comap f m`. ## Main statements * `Indep_sets.Indep`: if π-systems are independent as sets of sets, then the measurable space structures they generate are independent. * `indep_sets.indep`: variant with two π-systems. ## Implementation notes We provide one main definition of independence: * `Indep_sets`: independence of a family of sets of sets `pi : ι → set (set α)`. Three other independence notions are defined using `Indep_sets`: * `Indep`: independence of a family of measurable space structures `m : ι → measurable_space α`, * `Indep_set`: independence of a family of sets `s : ι → set α`, * `Indep_fun`: independence of a family of functions. For measurable spaces `m : Π (i : ι), measurable_space (β i)`, we consider functions `f : Π (i : ι), α → β i`. Additionally, we provide four corresponding statements for two measurable space structures (resp. sets of sets, sets, functions) instead of a family. These properties are denoted by the same names as for a family, but without a capital letter, for example `indep_fun` is the version of `Indep_fun` for two functions. The definition of independence for `Indep_sets` uses finite sets (`finset`). An alternative and equivalent way of defining independence would have been to use countable sets. TODO: prove that equivalence. Most of the definitions and lemma in this file list all variables instead of using the `variables` keyword at the beginning of a section, for example `lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} ...` . This is intentional, to be able to control the order of the `measurable_space` variables. Indeed when defining `μ` in the example above, the measurable space used is the last one defined, here `[measurable_space α]`, and not `m₁` or `m₂`. ## References * Williams, David. Probability with martingales. Cambridge university press, 1991. Part A, Chapter 4. -/ open measure_theory measurable_space open_locale big_operators classical measure_theory namespace probability_theory section definitions /-- A family of sets of sets `π : ι → set (set α)` is independent with respect to a measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ π i_1, ..., f i_n ∈ π i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. It will be used for families of pi_systems. -/ def Indep_sets {α ι} [measurable_space α] (π : ι → set (set α)) (μ : measure α . volume_tac) : Prop := ∀ (s : finset ι) {f : ι → set α} (H : ∀ i, i ∈ s → f i ∈ π i), μ (⋂ i ∈ s, f i) = ∏ i in s, μ (f i) /-- Two sets of sets `s₁, s₂` are independent with respect to a measure `μ` if for any sets `t₁ ∈ p₁, t₂ ∈ s₂`, then `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep_sets {α} [measurable_space α] (s1 s2 : set (set α)) (μ : measure α . volume_tac) : Prop := ∀ t1 t2 : set α, t1 ∈ s1 → t2 ∈ s2 → μ (t1 ∩ t2) = μ t1 * μ t2 /-- A family of measurable space structures (i.e. of σ-algebras) is independent with respect to a measure `μ` (typically defined on a finer σ-algebra) if the family of sets of measurable sets they define is independent. `m : ι → measurable_space α` is independent with respect to measure `μ` if for any finite set of indices `s = {i_1, ..., i_n}`, for any sets `f i_1 ∈ m i_1, ..., f i_n ∈ m i_n`, then `μ (⋂ i in s, f i) = ∏ i in s, μ (f i) `. -/ def Indep {α ι} (m : ι → measurable_space α) [measurable_space α] (μ : measure α . volume_tac) : Prop := Indep_sets (λ x, {s | measurable_set[m x] s}) μ /-- Two measurable space structures (or σ-algebras) `m₁, m₂` are independent with respect to a measure `μ` (defined on a third σ-algebra) if for any sets `t₁ ∈ m₁, t₂ ∈ m₂`, `μ (t₁ ∩ t₂) = μ (t₁) * μ (t₂)` -/ def indep {α} (m₁ m₂ : measurable_space α) [measurable_space α] (μ : measure α . volume_tac) : Prop := indep_sets {s | measurable_set[m₁] s} {s | measurable_set[m₂] s} μ /-- A family of sets is independent if the family of measurable space structures they generate is independent. For a set `s`, the generated measurable space has measurable sets `∅, s, sᶜ, univ`. -/ def Indep_set {α ι} [measurable_space α] (s : ι → set α) (μ : measure α . volume_tac) : Prop := Indep (λ i, generate_from {s i}) μ /-- Two sets are independent if the two measurable space structures they generate are independent. For a set `s`, the generated measurable space structure has measurable sets `∅, s, sᶜ, univ`. -/ def indep_set {α} [measurable_space α] (s t : set α) (μ : measure α . volume_tac) : Prop := indep (generate_from {s}) (generate_from {t}) μ /-- A family of functions defined on the same space `α` and taking values in possibly different spaces, each with a measurable space structure, is independent if the family of measurable space structures they generate on `α` is independent. For a function `g` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap g m`. -/ def Indep_fun {α ι} [measurable_space α] {β : ι → Type*} (m : Π (x : ι), measurable_space (β x)) (f : Π (x : ι), α → β x) (μ : measure α . volume_tac) : Prop := Indep (λ x, measurable_space.comap (f x) (m x)) μ /-- Two functions are independent if the two measurable space structures they generate are independent. For a function `f` with codomain having measurable space structure `m`, the generated measurable space structure is `measurable_space.comap f m`. -/ def indep_fun {α β γ} [measurable_space α] [mβ : measurable_space β] [mγ : measurable_space γ] (f : α → β) (g : α → γ) (μ : measure α . volume_tac) : Prop := indep (measurable_space.comap f mβ) (measurable_space.comap g mγ) μ end definitions section indep lemma indep_sets.symm {α} {s₁ s₂ : set (set α)} [measurable_space α] {μ : measure α} (h : indep_sets s₁ s₂ μ) : indep_sets s₂ s₁ μ := by { intros t1 t2 ht1 ht2, rw [set.inter_comm, mul_comm], exact h t2 t1 ht2 ht1, } lemma indep.symm {α} {m₁ m₂ : measurable_space α} [measurable_space α] {μ : measure α} (h : indep m₁ m₂ μ) : indep m₂ m₁ μ := indep_sets.symm h lemma indep_sets_of_indep_sets_of_le_left {α} {s₁ s₂ s₃: set (set α)} [measurable_space α] {μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h31 : s₃ ⊆ s₁) : indep_sets s₃ s₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (set.mem_of_subset_of_mem h31 ht1) ht2 lemma indep_sets_of_indep_sets_of_le_right {α} {s₁ s₂ s₃: set (set α)} [measurable_space α] {μ : measure α} (h_indep : indep_sets s₁ s₂ μ) (h32 : s₃ ⊆ s₂) : indep_sets s₁ s₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (set.mem_of_subset_of_mem h32 ht2) lemma indep_of_indep_of_le_left {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α] {μ : measure α} (h_indep : indep m₁ m₂ μ) (h31 : m₃ ≤ m₁) : indep m₃ m₂ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (h31 _ ht1) ht2 lemma indep_of_indep_of_le_right {α} {m₁ m₂ m₃: measurable_space α} [measurable_space α] {μ : measure α} (h_indep : indep m₁ m₂ μ) (h32 : m₃ ≤ m₂) : indep m₁ m₃ μ := λ t1 t2 ht1 ht2, h_indep t1 t2 ht1 (h32 _ ht2) lemma indep_sets.union {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α} (h₁ : indep_sets s₁ s' μ) (h₂ : indep_sets s₂ s' μ) : indep_sets (s₁ ∪ s₂) s' μ := begin intros t1 t2 ht1 ht2, cases (set.mem_union _ _ _).mp ht1 with ht1₁ ht1₂, { exact h₁ t1 t2 ht1₁ ht2, }, { exact h₂ t1 t2 ht1₂ ht2, }, end @[simp] lemma indep_sets.union_iff {α} [measurable_space α] {s₁ s₂ s' : set (set α)} {μ : measure α} : indep_sets (s₁ ∪ s₂) s' μ ↔ indep_sets s₁ s' μ ∧ indep_sets s₂ s' μ := ⟨λ h, ⟨indep_sets_of_indep_sets_of_le_left h (set.subset_union_left s₁ s₂), indep_sets_of_indep_sets_of_le_left h (set.subset_union_right s₁ s₂)⟩, λ h, indep_sets.union h.left h.right⟩ lemma indep_sets.Union {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)} {μ : measure α} (hyp : ∀ n, indep_sets (s n) s' μ) : indep_sets (⋃ n, s n) s' μ := begin intros t1 t2 ht1 ht2, rw set.mem_Union at ht1, cases ht1 with n ht1, exact hyp n t1 t2 ht1 ht2, end lemma indep_sets.inter {α} [measurable_space α] {s₁ s' : set (set α)} (s₂ : set (set α)) {μ : measure α} (h₁ : indep_sets s₁ s' μ) : indep_sets (s₁ ∩ s₂) s' μ := λ t1 t2 ht1 ht2, h₁ t1 t2 ((set.mem_inter_iff _ _ _).mp ht1).left ht2 lemma indep_sets.Inter {α ι} [measurable_space α] {s : ι → set (set α)} {s' : set (set α)} {μ : measure α} (h : ∃ n, indep_sets (s n) s' μ) : indep_sets (⋂ n, s n) s' μ := by {intros t1 t2 ht1 ht2, cases h with n h, exact h t1 t2 (set.mem_Inter.mp ht1 n) ht2 } lemma indep_sets_singleton_iff {α} [measurable_space α] {s t : set α} {μ : measure α} : indep_sets {s} {t} μ ↔ μ (s ∩ t) = μ s * μ t := ⟨λ h, h s t rfl rfl, λ h s1 t1 hs1 ht1, by rwa [set.mem_singleton_iff.mp hs1, set.mem_singleton_iff.mp ht1]⟩ end indep /-! ### Deducing `indep` from `Indep` -/ section from_Indep_to_indep lemma Indep_sets.indep_sets {α ι} {s : ι → set (set α)} [measurable_space α] {μ : measure α} (h_indep : Indep_sets s μ) {i j : ι} (hij : i ≠ j) : indep_sets (s i) (s j) μ := begin intros t₁ t₂ ht₁ ht₂, have hf_m : ∀ (x : ι), x ∈ {i, j} → (ite (x=i) t₁ t₂) ∈ s x, { intros x hx, cases finset.mem_insert.mp hx with hx hx, { simp [hx, ht₁], }, { simp [finset.mem_singleton.mp hx, hij.symm, ht₂], }, }, have h1 : t₁ = ite (i = i) t₁ t₂, by simp only [if_true, eq_self_iff_true], have h2 : t₂ = ite (j = i) t₁ t₂, by simp only [hij.symm, if_false], have h_inter : (⋂ (t : ι) (H : t ∈ ({i, j} : finset ι)), ite (t = i) t₁ t₂) = (ite (i = i) t₁ t₂) ∩ (ite (j = i) t₁ t₂), by simp only [finset.set_bInter_singleton, finset.set_bInter_insert], have h_prod : (∏ (t : ι) in ({i, j} : finset ι), μ (ite (t = i) t₁ t₂)) = μ (ite (i = i) t₁ t₂) * μ (ite (j = i) t₁ t₂), by simp only [hij, finset.prod_singleton, finset.prod_insert, not_false_iff, finset.mem_singleton], rw h1, nth_rewrite 1 h2, nth_rewrite 3 h2, rw [←h_inter, ←h_prod, h_indep {i, j} hf_m], end lemma Indep.indep {α ι} {m : ι → measurable_space α} [measurable_space α] {μ : measure α} (h_indep : Indep m μ) {i j : ι} (hij : i ≠ j) : indep (m i) (m j) μ := begin change indep_sets ((λ x, measurable_set[m x]) i) ((λ x, measurable_set[m x]) j) μ, exact Indep_sets.indep_sets h_indep hij, end lemma Indep_fun.indep_fun {α ι : Type*} {m₀ : measurable_space α} {μ : measure α} {β : ι → Type*} {m : Π x, measurable_space (β x)} {f : Π i, α → β i} (hf_Indep : Indep_fun m f μ) {i j : ι} (hij : i ≠ j) : indep_fun (f i) (f j) μ := hf_Indep.indep hij end from_Indep_to_indep /-! ## π-system lemma Independence of measurable spaces is equivalent to independence of generating π-systems. -/ section from_measurable_spaces_to_sets_of_sets /-! ### Independence of measurable space structures implies independence of generating π-systems -/ lemma Indep.Indep_sets {α ι} [measurable_space α] {μ : measure α} {m : ι → measurable_space α} {s : ι → set (set α)} (hms : ∀ n, m n = generate_from (s n)) (h_indep : Indep m μ) : Indep_sets s μ := λ S f hfs, h_indep S $ λ x hxS, ((hms x).symm ▸ measurable_set_generate_from (hfs x hxS) : measurable_set[m x] (f x)) lemma indep.indep_sets {α} [measurable_space α] {μ : measure α} {s1 s2 : set (set α)} (h_indep : indep (generate_from s1) (generate_from s2) μ) : indep_sets s1 s2 μ := λ t1 t2 ht1 ht2, h_indep t1 t2 (measurable_set_generate_from ht1) (measurable_set_generate_from ht2) end from_measurable_spaces_to_sets_of_sets section from_pi_systems_to_measurable_spaces /-! ### Independence of generating π-systems implies independence of measurable space structures -/ private lemma indep_sets.indep_aux {α} {m2 : measurable_space α} {m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h2 : m2 ≤ m) (hp2 : is_pi_system p2) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) {t1 t2 : set α} (ht1 : t1 ∈ p1) (ht2m : measurable_set[m2] t2) : μ (t1 ∩ t2) = μ t1 * μ t2 := begin let μ_inter := μ.restrict t1, let ν := (μ t1) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t1 μ ⟨measure_lt_top μ t1⟩, rw [set.inter_comm, ←@measure.restrict_apply α _ μ t1 t2 (h2 t2 ht2m)], refine ext_on_measurable_space_of_generate_finite m p2 (λ t ht, _) h2 hpm2 hp2 h_univ ht2m, have ht2 : measurable_set[m] t, { refine h2 _ _, rw hpm2, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht2, measure.smul_apply, set.inter_comm], exact hyp t1 t ht1 ht, end lemma indep_sets.indep {α} {m1 m2 : measurable_space α} {m : measurable_space α} {μ : measure α} [is_probability_measure μ] {p1 p2 : set (set α)} (h1 : m1 ≤ m) (h2 : m2 ≤ m) (hp1 : is_pi_system p1) (hp2 : is_pi_system p2) (hpm1 : m1 = generate_from p1) (hpm2 : m2 = generate_from p2) (hyp : indep_sets p1 p2 μ) : indep m1 m2 μ := begin intros t1 t2 ht1 ht2, let μ_inter := μ.restrict t2, let ν := (μ t2) • μ, have h_univ : μ_inter set.univ = ν set.univ, by rw [measure.restrict_apply_univ, measure.smul_apply, smul_eq_mul, measure_univ, mul_one], haveI : is_finite_measure μ_inter := @restrict.is_finite_measure α _ t2 μ ⟨measure_lt_top μ t2⟩, rw [mul_comm, ←@measure.restrict_apply α _ μ t2 t1 (h1 t1 ht1)], refine ext_on_measurable_space_of_generate_finite m p1 (λ t ht, _) h1 hpm1 hp1 h_univ ht1, have ht1 : measurable_set[m] t, { refine h1 _ _, rw hpm1, exact measurable_set_generate_from ht, }, rw [measure.restrict_apply ht1, measure.smul_apply, smul_eq_mul, mul_comm], exact indep_sets.indep_aux h2 hp2 hpm2 hyp ht ht2, end variables {α ι : Type*} {m0 : measurable_space α} {μ : measure α} lemma Indep_sets.pi_Union_Inter_singleton {π : ι → set (set α)} {a : ι} {S : finset ι} (hp_ind : Indep_sets π μ) (haS : a ∉ S) : indep_sets (pi_Union_Inter π {S}) (π a) μ := begin rintros t1 t2 ⟨s, hs_mem, ft1, hft1_mem, ht1_eq⟩ ht2_mem_pia, rw set.mem_singleton_iff at hs_mem, subst hs_mem, let f := λ n, ite (n = a) t2 (ite (n ∈ s) (ft1 n) set.univ), have h_f_mem : ∀ n ∈ insert a s, f n ∈ π n, { intros n hn_mem_insert, simp_rw f, cases (finset.mem_insert.mp hn_mem_insert) with hn_mem hn_mem, { simp [hn_mem, ht2_mem_pia], }, { have hn_ne_a : n ≠ a, by { rintro rfl, exact haS hn_mem, }, simp [hn_ne_a, hn_mem, hft1_mem n hn_mem], }, }, have h_f_mem_pi : ∀ n ∈ s, f n ∈ π n, from λ x hxS, h_f_mem x (by simp [hxS]), have h_t1 : t1 = ⋂ n ∈ s, f n, { suffices h_forall : ∀ n ∈ s, f n = ft1 n, { rw ht1_eq, congr' with n x, congr' with hns y, simp only [(h_forall n hns).symm], }, intros n hnS, have hn_ne_a : n ≠ a, by { rintro rfl, exact haS hnS, }, simp_rw [f, if_pos hnS, if_neg hn_ne_a], }, have h_μ_t1 : μ t1 = ∏ n in s, μ (f n), by rw [h_t1, ←hp_ind s h_f_mem_pi], have h_t2 : t2 = f a, by { simp_rw [f], simp, }, have h_μ_inter : μ (t1 ∩ t2) = ∏ n in insert a s, μ (f n), { have h_t1_inter_t2 : t1 ∩ t2 = ⋂ n ∈ insert a s, f n, by rw [h_t1, h_t2, finset.set_bInter_insert, set.inter_comm], rw [h_t1_inter_t2, ←hp_ind (insert a s) h_f_mem], }, rw [h_μ_inter, finset.prod_insert haS, h_t2, mul_comm, h_μ_t1], end /-- Auxiliary lemma for `Indep_sets.Indep`. -/ theorem Indep_sets.Indep_aux [is_probability_measure μ] (m : ι → measurable_space α) (h_le : ∀ i, m i ≤ m0) (π : ι → set (set α)) (h_pi : ∀ n, is_pi_system (π n)) (hp_univ : ∀ i, set.univ ∈ π i) (h_generate : ∀ i, m i = generate_from (π i)) (h_ind : Indep_sets π μ) : Indep m μ := begin refine finset.induction (by simp [measure_univ]) _, intros a S ha_notin_S h_rec f hf_m, have hf_m_S : ∀ x ∈ S, measurable_set[m x] (f x) := λ x hx, hf_m x (by simp [hx]), rw [finset.set_bInter_insert, finset.prod_insert ha_notin_S, ←h_rec hf_m_S], let p := pi_Union_Inter π {S}, set m_p := generate_from p with hS_eq_generate, have h_indep : indep m_p (m a) μ, { have hp : is_pi_system p := is_pi_system_pi_Union_Inter π h_pi {S} (sup_closed_singleton S), have h_le' : ∀ i, generate_from (π i) ≤ m0 := λ i, (h_generate i).symm.trans_le (h_le i), have hm_p : m_p ≤ m0 := generate_from_pi_Union_Inter_le π h_le' {S}, exact indep_sets.indep hm_p (h_le a) hp (h_pi a) hS_eq_generate (h_generate a) (h_ind.pi_Union_Inter_singleton ha_notin_S), }, refine h_indep.symm (f a) (⋂ n ∈ S, f n) (hf_m a (finset.mem_insert_self a S)) _, have h_le_p : ∀ i ∈ S, m i ≤ m_p, { intros n hn, rw [hS_eq_generate, h_generate n], exact le_generate_from_pi_Union_Inter {S} hp_univ (set.mem_singleton _) hn, }, have h_S_f : ∀ i ∈ S, measurable_set[m_p] (f i) := λ i hi, (h_le_p i hi) (f i) (hf_m_S i hi), exact S.measurable_set_bInter h_S_f, end /-- The measurable space structures generated by independent pi-systems are independent. -/ theorem Indep_sets.Indep [is_probability_measure μ] (m : ι → measurable_space α) (h_le : ∀ i, m i ≤ m0) (π : ι → set (set α)) (h_pi : ∀ n, is_pi_system (π n)) (h_generate : ∀ i, m i = generate_from (π i)) (h_ind : Indep_sets π μ) : Indep m μ := begin -- We want to apply `Indep_sets.Indep_aux`, but `π i` does not contain `univ`, hence we replace -- `π` with a new augmented pi-system `π'`, and prove all hypotheses for that pi-system. let π' := λ i, insert set.univ (π i), have h_subset : ∀ i, π i ⊆ π' i := λ i, set.subset_insert _ _, have h_pi' : ∀ n, is_pi_system (π' n) := λ n, (h_pi n).insert_univ, have h_univ' : ∀ i, set.univ ∈ π' i, from λ i, set.mem_insert _ _, have h_gen' : ∀ i, m i = generate_from (π' i), { intros i, rw [h_generate i, generate_from_insert_univ (π i)], }, have h_ind' : Indep_sets π' μ, { intros S f hfπ', let S' := finset.filter (λ i, f i ≠ set.univ) S, have h_mem : ∀ i ∈ S', f i ∈ π i, { intros i hi, simp_rw [S', finset.mem_filter] at hi, cases hfπ' i hi.1, { exact absurd h hi.2, }, { exact h, }, }, have h_left : (⋂ i ∈ S, f i) = ⋂ i ∈ S', f i, { ext1 x, simp only [set.mem_Inter, finset.mem_filter, ne.def, and_imp], split, { exact λ h i hiS hif, h i hiS, }, { intros h i hiS, by_cases hfi_univ : f i = set.univ, { rw hfi_univ, exact set.mem_univ _, }, { exact h i hiS hfi_univ, }, }, }, have h_right : ∏ i in S, μ (f i) = ∏ i in S', μ (f i), { rw ← finset.prod_filter_mul_prod_filter_not S (λ i, f i ≠ set.univ), simp only [ne.def, finset.filter_congr_decidable, not_not], suffices : ∏ x in finset.filter (λ x, f x = set.univ) S, μ (f x) = 1, { rw [this, mul_one], }, calc ∏ x in finset.filter (λ x, f x = set.univ) S, μ (f x) = ∏ x in finset.filter (λ x, f x = set.univ) S, μ set.univ : finset.prod_congr rfl (λ x hx, by { rw finset.mem_filter at hx, rw hx.2, }) ... = ∏ x in finset.filter (λ x, f x = set.univ) S, 1 : finset.prod_congr rfl (λ _ _, measure_univ) ... = 1 : finset.prod_const_one, }, rw [h_left, h_right], exact h_ind S' h_mem, }, exact Indep_sets.Indep_aux m h_le π' h_pi' h_univ' h_gen' h_ind', end end from_pi_systems_to_measurable_spaces section indep_set /-! ### Independence of measurable sets We prove the following equivalences on `indep_set`, for measurable sets `s, t`. * `indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t`, * `indep_set s t μ ↔ indep_sets {s} {t} μ`. -/ variables {α : Type*} [measurable_space α] {s t : set α} (S T : set (set α)) lemma indep_set_iff_indep_sets_singleton (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ indep_sets {s} {t} μ := ⟨indep.indep_sets, λ h, indep_sets.indep (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (generate_from_le (λ u hu, by rwa set.mem_singleton_iff.mp hu)) (is_pi_system.singleton s) (is_pi_system.singleton t) rfl rfl h⟩ lemma indep_set_iff_measure_inter_eq_mul (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] : indep_set s t μ ↔ μ (s ∩ t) = μ s * μ t := (indep_set_iff_indep_sets_singleton hs_meas ht_meas μ).trans indep_sets_singleton_iff lemma indep_sets.indep_set_of_mem (hs : s ∈ S) (ht : t ∈ T) (hs_meas : measurable_set s) (ht_meas : measurable_set t) (μ : measure α . volume_tac) [is_probability_measure μ] (h_indep : indep_sets S T μ) : indep_set s t μ := (indep_set_iff_measure_inter_eq_mul hs_meas ht_meas μ).mpr (h_indep s t hs ht) end indep_set section indep_fun /-! ### Independence of random variables -/ variables {α β β' γ γ' : Type*} {mα : measurable_space α} {μ : measure α} {f : α → β} {g : α → β'} lemma indep_fun_iff_measure_inter_preimage_eq_mul {mβ : measurable_space β} {mβ' : measurable_space β'} : indep_fun f g μ ↔ ∀ s t, measurable_set s → measurable_set t → μ (f ⁻¹' s ∩ g ⁻¹' t) = μ (f ⁻¹' s) * μ (g ⁻¹' t) := begin split; intro h, { refine λ s t hs ht, h (f ⁻¹' s) (g ⁻¹' t) ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩, }, { rintros _ _ ⟨s, hs, rfl⟩ ⟨t, ht, rfl⟩, exact h s t hs ht, }, end lemma Indep_fun_iff_measure_inter_preimage_eq_mul {ι : Type*} {β : ι → Type*} (m : Π x, measurable_space (β x)) (f : Π i, α → β i) : Indep_fun m f μ ↔ ∀ (S : finset ι) {sets : Π i : ι, set (β i)} (H : ∀ i, i ∈ S → measurable_set[m i] (sets i)), μ (⋂ i ∈ S, (f i) ⁻¹' (sets i)) = ∏ i in S, μ ((f i) ⁻¹' (sets i)) := begin refine ⟨λ h S sets h_meas, h _ (λ i hi_mem, ⟨sets i, h_meas i hi_mem, rfl⟩), _⟩, intros h S setsα h_meas, let setsβ : (Π i : ι, set (β i)) := λ i, dite (i ∈ S) (λ hi_mem, (h_meas i hi_mem).some) (λ _, set.univ), have h_measβ : ∀ i ∈ S, measurable_set[m i] (setsβ i), { intros i hi_mem, simp_rw [setsβ, dif_pos hi_mem], exact (h_meas i hi_mem).some_spec.1, }, have h_preim : ∀ i ∈ S, setsα i = (f i) ⁻¹' (setsβ i), { intros i hi_mem, simp_rw [setsβ, dif_pos hi_mem], exact (h_meas i hi_mem).some_spec.2.symm, }, have h_left_eq : μ (⋂ i ∈ S, setsα i) = μ (⋂ i ∈ S, (f i) ⁻¹' (setsβ i)), { congr' with i x, simp only [set.mem_Inter], split; intros h hi_mem; specialize h hi_mem, { rwa h_preim i hi_mem at h, }, { rwa h_preim i hi_mem, }, }, have h_right_eq : (∏ i in S, μ (setsα i)) = ∏ i in S, μ ((f i) ⁻¹' (setsβ i)), { refine finset.prod_congr rfl (λ i hi_mem, _), rw h_preim i hi_mem, }, rw [h_left_eq, h_right_eq], exact h S h_measβ, end lemma indep_fun_iff_indep_set_preimage {mβ : measurable_space β} {mβ' : measurable_space β'} [is_probability_measure μ] (hf : measurable f) (hg : measurable g) : indep_fun f g μ ↔ ∀ s t, measurable_set s → measurable_set t → indep_set (f ⁻¹' s) (g ⁻¹' t) μ := begin refine indep_fun_iff_measure_inter_preimage_eq_mul.trans _, split; intros h s t hs ht; specialize h s t hs ht, { rwa indep_set_iff_measure_inter_eq_mul (hf hs) (hg ht) μ, }, { rwa ← indep_set_iff_measure_inter_eq_mul (hf hs) (hg ht) μ, }, end lemma indep_fun.ae_eq {mβ : measurable_space β} {f g f' g' : α → β} (hfg : indep_fun f g μ) (hf : f =ᵐ[μ] f') (hg : g =ᵐ[μ] g') : indep_fun f' g' μ := begin rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, have h1 : f ⁻¹' A =ᵐ[μ] f' ⁻¹' A := hf.fun_comp A, have h2 : g ⁻¹' B =ᵐ[μ] g' ⁻¹' B := hg.fun_comp B, rw [←measure_congr h1, ←measure_congr h2, ←measure_congr (h1.inter h2)], exact hfg _ _ ⟨_, hA, rfl⟩ ⟨_, hB, rfl⟩ end lemma indep_fun.comp {mβ : measurable_space β} {mβ' : measurable_space β'} {mγ : measurable_space γ} {mγ' : measurable_space γ'} {φ : β → γ} {ψ : β' → γ'} (hfg : indep_fun f g μ) (hφ : measurable φ) (hψ : measurable ψ) : indep_fun (φ ∘ f) (ψ ∘ g) μ := begin rintro _ _ ⟨A, hA, rfl⟩ ⟨B, hB, rfl⟩, apply hfg, { exact ⟨φ ⁻¹' A, hφ hA, set.preimage_comp.symm⟩ }, { exact ⟨ψ ⁻¹' B, hψ hB, set.preimage_comp.symm⟩ } end /-- If `f` is a family of mutually independent random variables (`Indep_fun m f μ`) and `S, T` are two disjoint finite index sets, then the tuple formed by `f i` for `i ∈ S` is independent of the tuple `(f i)_i` for `i ∈ T`. -/ lemma Indep_fun.indep_fun_finset [is_probability_measure μ] {ι : Type*} {β : ι → Type*} {m : Π i, measurable_space (β i)} {f : Π i, α → β i} (S T : finset ι) (hST : disjoint S T) (hf_Indep : Indep_fun m f μ) (hf_meas : ∀ i, measurable (f i)) : indep_fun (λ a (i : S), f i a) (λ a (i : T), f i a) μ := begin -- We introduce π-systems, build from the π-system of boxes which generates `measurable_space.pi`. let πSβ := (set.pi (set.univ : set S) '' (set.pi (set.univ : set S) (λ i, {s : set (β i) | measurable_set[m i] s}))), let πS := {s : set α | ∃ t ∈ πSβ, (λ a (i : S), f i a) ⁻¹' t = s}, have hπS_pi : is_pi_system πS := is_pi_system_pi.comap (λ a i, f i a), have hπS_gen : measurable_space.pi.comap (λ a (i : S), f i a) = generate_from πS, { rw [generate_from_pi.symm, comap_generate_from], { congr' with s, simp only [set.mem_image, set.mem_set_of_eq, exists_prop], }, { exact finset.fintype_coe_sort S, }, }, let πTβ := (set.pi (set.univ : set T) '' (set.pi (set.univ : set T) (λ i, {s : set (β i) | measurable_set[m i] s}))), let πT := {s : set α | ∃ t ∈ πTβ, (λ a (i : T), f i a) ⁻¹' t = s}, have hπT_pi : is_pi_system πT := is_pi_system_pi.comap (λ a i, f i a), have hπT_gen : measurable_space.pi.comap (λ a (i : T), f i a) = generate_from πT, { rw [generate_from_pi.symm, comap_generate_from], { congr' with s, simp only [set.mem_image, set.mem_set_of_eq, exists_prop], }, { exact finset.fintype_coe_sort T, }, }, -- To prove independence, we prove independence of the generating π-systems. refine indep_sets.indep (measurable.comap_le (measurable_pi_iff.mpr (λ i, hf_meas i))) (measurable.comap_le (measurable_pi_iff.mpr (λ i, hf_meas i))) hπS_pi hπT_pi hπS_gen hπT_gen _, rintros _ _ ⟨s, ⟨sets_s, hs1, hs2⟩, rfl⟩ ⟨t, ⟨sets_t, ht1, ht2⟩, rfl⟩, simp only [set.mem_univ_pi, set.mem_set_of_eq] at hs1 ht1, rw [← hs2, ← ht2], let sets_s' : (Π i : ι, set (β i)) := λ i, dite (i ∈ S) (λ hi, sets_s ⟨i, hi⟩) (λ _, set.univ), have h_sets_s'_eq : ∀ {i} (hi : i ∈ S), sets_s' i = sets_s ⟨i, hi⟩, { intros i hi, simp_rw [sets_s', dif_pos hi], }, have h_sets_s'_univ : ∀ {i} (hi : i ∈ T), sets_s' i = set.univ, { intros i hi, simp_rw [sets_s', dif_neg (finset.disjoint_right.mp hST hi)], }, let sets_t' : (Π i : ι, set (β i)) := λ i, dite (i ∈ T) (λ hi, sets_t ⟨i, hi⟩) (λ _, set.univ), have h_sets_t'_univ : ∀ {i} (hi : i ∈ S), sets_t' i = set.univ, { intros i hi, simp_rw [sets_t', dif_neg (finset.disjoint_left.mp hST hi)], }, have h_meas_s' : ∀ i ∈ S, measurable_set (sets_s' i), { intros i hi, rw h_sets_s'_eq hi, exact hs1 _, }, have h_meas_t' : ∀ i ∈ T, measurable_set (sets_t' i), { intros i hi, simp_rw [sets_t', dif_pos hi], exact ht1 _, }, have h_eq_inter_S : (λ (a : α) (i : ↥S), f ↑i a) ⁻¹' set.pi set.univ sets_s = ⋂ i ∈ S, (f i) ⁻¹' (sets_s' i), { ext1 x, simp only [set.mem_preimage, set.mem_univ_pi, set.mem_Inter], split; intro h, { intros i hi, rw [h_sets_s'_eq hi], exact h ⟨i, hi⟩, }, { rintros ⟨i, hi⟩, specialize h i hi, rw [h_sets_s'_eq hi] at h, exact h, }, }, have h_eq_inter_T : (λ (a : α) (i : ↥T), f ↑i a) ⁻¹' set.pi set.univ sets_t = ⋂ i ∈ T, (f i) ⁻¹' (sets_t' i), { ext1 x, simp only [set.mem_preimage, set.mem_univ_pi, set.mem_Inter], split; intro h, { intros i hi, simp_rw [sets_t', dif_pos hi], exact h ⟨i, hi⟩, }, { rintros ⟨i, hi⟩, specialize h i hi, simp_rw [sets_t', dif_pos hi] at h, exact h, }, }, rw Indep_fun_iff_measure_inter_preimage_eq_mul at hf_Indep, rw [h_eq_inter_S, h_eq_inter_T, hf_Indep S h_meas_s', hf_Indep T h_meas_t'], have h_Inter_inter : (⋂ i ∈ S, (f i) ⁻¹' (sets_s' i)) ∩ (⋂ i ∈ T, (f i) ⁻¹' (sets_t' i)) = ⋂ i ∈ (S ∪ T), (f i) ⁻¹' (sets_s' i ∩ sets_t' i), { ext1 x, simp only [set.mem_inter_eq, set.mem_Inter, set.mem_preimage, finset.mem_union], split; intro h, { intros i hi, cases hi, { rw h_sets_t'_univ hi, exact ⟨h.1 i hi, set.mem_univ _⟩, }, { rw h_sets_s'_univ hi, exact ⟨set.mem_univ _, h.2 i hi⟩, }, }, { exact ⟨λ i hi, (h i (or.inl hi)).1, λ i hi, (h i (or.inr hi)).2⟩, }, }, rw [h_Inter_inter, hf_Indep (S ∪ T)], swap, { intros i hi_mem, rw finset.mem_union at hi_mem, cases hi_mem, { rw [h_sets_t'_univ hi_mem, set.inter_univ], exact h_meas_s' i hi_mem, }, { rw [h_sets_s'_univ hi_mem, set.univ_inter], exact h_meas_t' i hi_mem, }, }, rw finset.prod_union hST, congr' 1, { refine finset.prod_congr rfl (λ i hi, _), rw [h_sets_t'_univ hi, set.inter_univ], }, { refine finset.prod_congr rfl (λ i hi, _), rw [h_sets_s'_univ hi, set.univ_inter], }, end end indep_fun end probability_theory
4db8fd40cf6490dade6287ed17a4307dace574d6
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/set_theory/ordinal_notation.lean
41e78c71d0bfec58063b7f01d48a4a765f91a9a3
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
35,750
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Ordinal notations (constructive ordinal arithmetic for ordinals < ε₀). -/ import set_theory.ordinal data.pnat open ordinal local notation `ω` := omega.{0} /-- Recursive definition of an ordinal notation. `zero` denotes the ordinal 0, and `oadd e n a` is intended to refer to `ω^e * n + a`. For this to be valid Cantor normal form, we must have the exponents decrease to the right, but we can't state this condition until we've defined `repr`, so it is a separate definition `NF`. -/ @[derive decidable_eq] inductive onote : Type | zero : onote | oadd : onote → ℕ+ → onote → onote namespace onote /-- Notation for 0 -/ instance : has_zero onote := ⟨zero⟩ @[simp] theorem zero_def : zero = 0 := rfl /-- Notation for 1 -/ instance : has_one onote := ⟨oadd 0 1 0⟩ /-- Notation for ω -/ def omega : onote := oadd 1 1 0 /-- The ordinal denoted by a notation -/ @[simp] noncomputable def repr : onote → ordinal.{0} | 0 := 0 | (oadd e n a) := ω ^ repr e * n + repr a def to_string_aux1 (e : onote) (n : ℕ) (s : string) : string := if e = 0 then _root_.to_string n else (if e = 1 then "ω" else "ω^(" ++ s ++ ")") ++ if n = 1 then "" else "*" ++ _root_.to_string n /-- Print an ordinal notation -/ def to_string : onote → string | zero := "0" | (oadd e n 0) := to_string_aux1 e n (to_string e) | (oadd e n a) := to_string_aux1 e n (to_string e) ++ " + " ++ to_string a /-- Print an ordinal notation -/ def repr' : onote → string | zero := "0" | (oadd e n a) := "(oadd " ++ repr' e ++ " " ++ _root_.to_string (n:ℕ) ++ " " ++ repr' a ++ ")" instance : has_to_string onote := ⟨to_string⟩ instance : has_repr onote := ⟨repr'⟩ instance : preorder onote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } theorem lt_def {x y : onote} : x < y ↔ repr x < repr y := iff.rfl theorem le_def {x y : onote} : x ≤ y ↔ repr x ≤ repr y := iff.rfl /-- Convert a `nat` into an ordinal -/ @[simp] def of_nat : ℕ → onote | 0 := 0 | (nat.succ n) := oadd 0 n.succ_pnat 0 @[simp] theorem of_nat_one : of_nat 1 = 1 := rfl @[simp] theorem repr_of_nat (n : ℕ) : repr (of_nat n) = n := by cases n; simp @[simp] theorem repr_one : repr 1 = 1 := by simpa using repr_of_nat 1 theorem omega_le_oadd (e n a) : ω ^ repr e ≤ repr (oadd e n a) := begin unfold repr, refine le_trans _ (le_add_right _ _), simpa using (mul_le_mul_iff_left $ power_pos (repr e) omega_pos).2 (nat_cast_le.2 n.2) end theorem oadd_pos (e n a) : 0 < oadd e n a := @lt_of_lt_of_le _ _ _ _ _ (power_pos _ omega_pos) (omega_le_oadd _ _ _) /-- Compare ordinal notations -/ def cmp : onote → onote → ordering | 0 0 := ordering.eq | _ 0 := ordering.gt | 0 _ := ordering.lt | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) := (cmp e₁ e₂).or_else $ (_root_.cmp (n₁:ℕ) n₂).or_else (cmp a₁ a₂) theorem eq_of_cmp_eq : ∀ {o₁ o₂}, cmp o₁ o₂ = ordering.eq → o₁ = o₂ | 0 0 h := rfl | (oadd e n a) 0 h := by injection h | 0 (oadd e n a) h := by injection h | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h := begin revert h, simp [cmp], cases h₁ : cmp e₁ e₂; intro h; try {cases h}, have := eq_of_cmp_eq h₁, subst e₂, revert h, cases h₂ : _root_.cmp (n₁:ℕ) n₂; intro h; try {cases h}, have := eq_of_cmp_eq h, subst a₂, rw [_root_.cmp, cmp_using_eq_eq] at h₂, have := subtype.eq (eq_of_incomp h₂), subst n₂, simp end theorem zero_lt_one : (0 : onote) < 1 := by rw [lt_def, repr, repr_one]; exact zero_lt_one /-- `NF_below o b` says that `o` is a normal form ordinal notation satisfying `repr o < ω ^ b`. -/ inductive NF_below : onote → ordinal.{0} → Prop | zero {b} : NF_below 0 b | oadd' {e n a eb b} : NF_below e eb → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b /-- A normal form ordinal notation has the form ω ^ a₁ * n₁ + ω ^ a₂ * n₂ + ... ω ^ aₖ * nₖ where `a₁ > a₂ > ... > aₖ` and all the `aᵢ` are also in normal form. We will essentially only be interested in normal form ordinal notations, but to avoid complicating the algorithms we define everything over general ordinal notations and only prove correctness with normal form as an invariant. -/ @[class] def NF (o : onote) := Exists (NF_below o) instance NF.zero : NF 0 := ⟨0, NF_below.zero⟩ theorem NF_below.oadd {e n a b} : NF e → NF_below a (repr e) → repr e < b → NF_below (oadd e n a) b | ⟨eb, h⟩ := NF_below.oadd' h theorem NF_below.fst {e n a b} (h : NF_below (oadd e n a) b) : NF e := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact ⟨_, h₁⟩ theorem NF.fst {e n a} : NF (oadd e n a) → NF e | ⟨b, h⟩ := h.fst theorem NF_below.snd {e n a b} (h : NF_below (oadd e n a) b) : NF_below a (repr e) := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₂ theorem NF.snd' {e n a} : NF (oadd e n a) → NF_below a (repr e) | ⟨b, h⟩ := h.snd theorem NF.snd {e n a} (h : NF (oadd e n a)) : NF a := ⟨_, h.snd'⟩ theorem NF.oadd {e a} (h₁ : NF e) (n) (h₂ : NF_below a (repr e)) : NF (oadd e n a) := ⟨_, NF_below.oadd h₁ h₂ (ordinal.lt_succ_self _)⟩ instance NF.oadd_zero (e n) [h : NF e] : NF (oadd e n 0) := h.oadd _ NF_below.zero theorem NF_below.lt {e n a b} (h : NF_below (oadd e n a) b) : repr e < b := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact h₃ theorem NF_below_zero : ∀ {o}, NF_below o 0 ↔ o = 0 | 0 := ⟨λ _, rfl, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, (not_le_of_lt h.lt).elim (zero_le _), λ e, e.symm ▸ NF_below.zero⟩ theorem NF.zero_of_zero {e n a} (h : NF (oadd e n a)) (e0 : e = 0) : a = 0 := by simpa [e0, NF_below_zero] using h.snd' theorem NF_below.repr_lt {o b} (h : NF_below o b) : repr o < ω ^ b := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH, { exact power_pos _ omega_pos }, { rw repr, refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 IH) _, rw ← mul_succ, refine le_trans (mul_le_mul_left _ $ ordinal.succ_le.2 $ nat_lt_omega _) _, rw ← power_succ, exact power_le_power_right omega_pos (ordinal.succ_le.2 h₃) } end theorem NF_below.mono {o b₁ b₂} (bb : b₁ ≤ b₂) (h : NF_below o b₁) : NF_below o b₂ := begin induction h with _ e n a eb b h₁ h₂ h₃ _ IH; constructor, exacts [h₁, h₂, lt_of_lt_of_le h₃ bb] end theorem NF.below_of_lt {e n a b} (H : repr e < b) : NF (oadd e n a) → NF_below (oadd e n a) b | ⟨b', h⟩ := by cases h with _ _ _ _ eb _ h₁ h₂ h₃; exact NF_below.oadd' h₁ h₂ H theorem NF.below_of_lt' : ∀ {o b}, repr o < ω ^ b → NF o → NF_below o b | 0 b H _ := NF_below.zero | (oadd e n a) b H h := h.below_of_lt $ (power_lt_power_iff_right one_lt_omega).1 $ (lt_of_le_of_lt (omega_le_oadd _ _ _) H) theorem NF_below_of_nat : ∀ n, NF_below (of_nat n) 1 | 0 := NF_below.zero | (nat.succ n) := NF_below.oadd NF.zero NF_below.zero ordinal.zero_lt_one instance NF_of_nat (n) : NF (of_nat n) := ⟨_, NF_below_of_nat n⟩ instance NF_one : NF 1 := by rw ← of_nat_one; apply_instance theorem oadd_lt_oadd_1 {e₁ n₁ o₁ e₂ n₂ o₂} (h₁ : NF (oadd e₁ n₁ o₁)) (h₂ : NF (oadd e₂ n₂ o₂)) (h : e₁ < e₂) : oadd e₁ n₁ o₁ < oadd e₂ n₂ o₂ := @lt_of_lt_of_le _ _ _ _ _ ((h₁.below_of_lt h).repr_lt) (omega_le_oadd _ _ _) theorem oadd_lt_oadd_2 {e n₁ o₁ n₂ o₂} (h₁ : NF (oadd e n₁ o₁)) (h₂ : NF (oadd e n₂ o₂)) (h : (n₁:ℕ) < n₂) : oadd e n₁ o₁ < oadd e n₂ o₂ := begin simp [lt_def], refine lt_of_lt_of_le ((ordinal.add_lt_add_iff_left _).2 h₁.snd'.repr_lt) (le_trans _ (le_add_right _ _)), rwa [← mul_succ, mul_le_mul_iff_left (power_pos _ omega_pos), ordinal.succ_le, nat_cast_lt] end theorem oadd_lt_oadd_3 {e n a₁ a₂} (h₁ : NF (oadd e n a₁)) (h₂ : NF (oadd e n a₂)) (h : a₁ < a₂) : oadd e n a₁ < oadd e n a₂ := begin rw lt_def, unfold repr, exact (ordinal.add_lt_add_iff_left _).2 h end theorem cmp_compares : ∀ (a b : onote) [NF a] [NF b], (cmp a b).compares a b | 0 0 h₁ h₂ := rfl | (oadd e n a) 0 h₁ h₂ := oadd_pos _ _ _ | 0 (oadd e n a) h₁ h₂ := oadd_pos _ _ _ | o₁@(oadd e₁ n₁ a₁) o₂@(oadd e₂ n₂ a₂) h₁ h₂ := begin rw cmp, have IHe := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, case ordering.lt { exact oadd_lt_oadd_1 h₁ h₂ IHe }, case ordering.gt { exact oadd_lt_oadd_1 h₂ h₁ IHe }, change e₁ = e₂ at IHe, subst IHe, unfold _root_.cmp, cases nh : cmp_using (<) (n₁:ℕ) n₂, case ordering.lt { rw cmp_using_eq_lt at nh, exact oadd_lt_oadd_2 h₁ h₂ nh }, case ordering.gt { rw cmp_using_eq_gt at nh, exact oadd_lt_oadd_2 h₂ h₁ nh }, rw cmp_using_eq_eq at nh, have := subtype.eq (eq_of_incomp nh), subst n₂, have IHa := @cmp_compares _ _ h₁.snd h₂.snd, cases cmp a₁ a₂, case ordering.lt { exact oadd_lt_oadd_3 h₁ h₂ IHa }, case ordering.gt { exact oadd_lt_oadd_3 h₂ h₁ IHa }, change a₁ = a₂ at IHa, subst IHa, exact rfl end theorem repr_inj {a b} [NF a] [NF b] : repr a = repr b ↔ a = b := ⟨match cmp a b, cmp_compares a b with | ordering.lt, (h : repr a < repr b), e := (ne_of_lt h e).elim | ordering.gt, (h : repr a > repr b), e := (ne_of_gt h e).elim | ordering.eq, h, e := h end, congr_arg _⟩ theorem NF.of_dvd_omega_power {b e n a} (h : NF (oadd e n a)) (d : ω ^ b ∣ repr (oadd e n a)) : b ≤ repr e ∧ ω ^ b ∣ repr a := begin have := mt repr_inj.1 (λ h, by injection h : oadd e n a ≠ 0), have L := le_of_not_lt (λ l, not_le_of_lt (h.below_of_lt l).repr_lt (le_of_dvd this d)), simp at d, exact ⟨L, (dvd_add_iff $ dvd_mul_of_dvd _ $ power_dvd_power _ L).1 d⟩ end theorem NF.of_dvd_omega {e n a} (h : NF (oadd e n a)) : ω ∣ repr (oadd e n a) → repr e ≠ 0 ∧ ω ∣ repr a := by rw [← power_one ω, ← one_le_iff_ne_zero]; exact h.of_dvd_omega_power /-- `top_below b o` asserts that the largest exponent in `o`, if it exists, is less than `b`. This is an auxiliary definition for decidability of `NF`. -/ def top_below (b) : onote → Prop | 0 := true | (oadd e n a) := cmp e b = ordering.lt instance decidable_top_below : decidable_rel top_below := by intros b o; cases o; delta top_below; apply_instance theorem NF_below_iff_top_below {b} [NF b] : ∀ {o}, NF_below o (repr b) ↔ NF o ∧ top_below b o | 0 := ⟨λ h, ⟨⟨_, h⟩, trivial⟩, λ _, NF_below.zero⟩ | (oadd e n a) := ⟨λ h, ⟨⟨_, h⟩, (@cmp_compares _ b h.fst _).eq_lt.2 h.lt⟩, λ ⟨h₁, h₂⟩, h₁.below_of_lt $ (@cmp_compares _ b h₁.fst _).eq_lt.1 h₂⟩ instance decidable_NF : decidable_pred NF | 0 := is_true NF.zero | (oadd e n a) := begin have := decidable_NF e, have := decidable_NF a, resetI, apply decidable_of_iff (NF e ∧ NF a ∧ top_below e a), abstract { rw ← and_congr_right (λ h, @NF_below_iff_top_below _ h _), exact ⟨λ ⟨h₁, h₂⟩, NF.oadd h₁ n h₂, λ h, ⟨h.fst, h.snd'⟩⟩ }, end /-- Addition of ordinal notations (correct only for normal input) -/ def add : onote → onote → onote | 0 o := o | (oadd e n a) o := match add a o with | 0 := oadd e n 0 | o'@(oadd e' n' a') := match cmp e e' with | ordering.lt := o' | ordering.eq := oadd e (n + n') a' | ordering.gt := oadd e n o' end end instance : has_add onote := ⟨add⟩ @[simp] theorem zero_add (o : onote) : 0 + o = o := rfl theorem oadd_add (e n a o) : oadd e n a + o = add._match_1 e n (a + o) := rfl /-- Subtraction of ordinal notations (correct only for normal input) -/ def sub : onote → onote → onote | 0 o := 0 | o 0 := o | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := match cmp e₁ e₂ with | ordering.lt := 0 | ordering.gt := o₁ | ordering.eq := match (n₁:ℕ) - n₂ with | 0 := if n₁ = n₂ then sub a₁ a₂ else 0 | (nat.succ k) := oadd e₁ k.succ_pnat a₁ end end instance : has_sub onote := ⟨sub⟩ theorem add_NF_below {b} : ∀ {o₁ o₂}, NF_below o₁ b → NF_below o₂ b → NF_below (o₁ + o₂) b | 0 o h₁ h₂ := h₂ | (oadd e n a) o h₁ h₂ := begin have h' := add_NF_below (h₁.snd.mono $ le_of_lt h₁.lt) h₂, simp [oadd_add], cases a + o with e' n' a', { exact NF_below.oadd h₁.fst NF_below.zero h₁.lt }, simp [add], have := @cmp_compares _ _ h₁.fst h'.fst, cases cmp e e'; simp [add], { exact h' }, { simp at this, subst e', exact NF_below.oadd h'.fst h'.snd h'.lt }, { exact NF_below.oadd h₁.fst (NF.below_of_lt this ⟨_, h'⟩) h₁.lt } end instance add_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ + o₂) | ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := (b₁.le_total b₂).elim (λ h, ⟨b₂, add_NF_below (h₁.mono h) h₂⟩) (λ h, ⟨b₁, add_NF_below h₁ (h₂.mono h)⟩) @[simp] theorem repr_add : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ + o₂) = repr o₁ + repr o₂ | 0 o h₁ h₂ := by simp | (oadd e n a) o h₁ h₂ := begin haveI := h₁.snd, have h' := repr_add a o, conv at h' in (_+o) {simp [(+)]}, have nf := onote.add_NF a o, conv at nf in (_+o) {simp [(+)]}, conv in (_+o) {simp [(+), add]}, cases add a o with e' n' a'; simp [add, h'.symm], have := h₁.fst, have := nf.fst, have ee := cmp_compares e e', cases cmp e e'; simp [add], { rw [← add_assoc, @add_absorp _ (repr e') (ω ^ repr e' * (n':ℕ))], { have := (h₁.below_of_lt ee).repr_lt, unfold repr at this, exact lt_of_le_of_lt (le_add_right _ _) this }, { simpa using (mul_le_mul_iff_left $ power_pos (repr e') omega_pos).2 (nat_cast_le.2 n'.pos) } }, { change e = e' at ee, subst e', rw [← add_assoc, ← ordinal.mul_add, ← nat.cast_add] } end theorem sub_NF_below : ∀ {o₁ o₂ b}, NF_below o₁ b → NF o₂ → NF_below (o₁ - o₂) b | 0 o b h₁ h₂ := by cases o; exact NF_below.zero | (oadd e n a) 0 b h₁ h₂ := h₁ | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) b h₁ h₂ := begin have h' := sub_NF_below h₁.snd h₂.snd, simp [has_sub.sub, sub] at h' ⊢, have := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂; simp [sub], { apply NF_below.zero }, { simp at this, subst e₂, cases mn : (n₁:ℕ) - n₂; simp [sub], { by_cases en : n₁ = n₂; simp [en], { exact h'.mono (le_of_lt h₁.lt) }, { exact NF_below.zero } }, { exact NF_below.oadd h₁.fst h₁.snd h₁.lt } }, { exact h₁ } end instance sub_NF (o₁ o₂) : ∀ [NF o₁] [NF o₂], NF (o₁ - o₂) | ⟨b₁, h₁⟩ h₂ := ⟨b₁, sub_NF_below h₁ h₂⟩ @[simp] theorem repr_sub : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ - o₂) = repr o₁ - repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_sub _).symm | (oadd e n a) 0 h₁ h₂ := (ordinal.sub_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin haveI := h₁.snd, haveI := h₂.snd, have h' := repr_sub a₁ a₂, conv at h' in (a₁-a₂) {simp [has_sub.sub]}, have nf := onote.sub_NF a₁ a₂, conv at nf in (a₁-a₂) {simp [has_sub.sub]}, conv in (_-oadd _ _ _) {simp [has_sub.sub, sub]}, have ee := @cmp_compares _ _ h₁.fst h₂.fst, cases cmp e₁ e₂, { rw [sub_eq_zero_iff_le.2], {refl}, exact le_of_lt (oadd_lt_oadd_1 h₁ h₂ ee) }, { change e₁ = e₂ at ee, subst e₂, unfold sub._match_1, cases mn : (n₁:ℕ) - n₂; dsimp only [sub._match_2], { by_cases en : n₁ = n₂, { simp [en], rwa [add_sub_add_cancel] }, { simp [en, -repr], exact (sub_eq_zero_iff_le.2 $ le_of_lt $ oadd_lt_oadd_2 h₁ h₂ $ lt_of_le_of_ne (nat.sub_eq_zero_iff_le.1 mn) (mt pnat.eq en)).symm } }, { simp [nat.succ_pnat, -nat.cast_succ], rw [(nat.sub_eq_iff_eq_add $ le_of_lt $ nat.lt_of_sub_eq_succ mn).1 mn, add_comm, nat.cast_add, ordinal.mul_add, add_assoc, add_sub_add_cancel], refine (ordinal.sub_eq_of_add_eq $ add_absorp h₂.snd'.repr_lt $ le_trans _ (le_add_right _ _)).symm, simpa using mul_le_mul_left _ (nat_cast_le.2 $ nat.succ_pos _) } }, { exact (ordinal.sub_eq_of_add_eq $ add_absorp (h₂.below_of_lt ee).repr_lt $ omega_le_oadd _ _ _).symm } end /-- Multiplication of ordinal notations (correct only for normal input) -/ def mul : onote → onote → onote | 0 _ := 0 | _ 0 := 0 | o₁@(oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) := if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (mul o₁ a₂) instance : has_mul onote := ⟨mul⟩ @[simp] theorem zero_mul (o : onote) : 0 * o = 0 := by cases o; refl @[simp] theorem mul_zero (o : onote) : o * 0 = 0 := by cases o; refl theorem oadd_mul (e₁ n₁ a₁ e₂ n₂ a₂) : oadd e₁ n₁ a₁ * oadd e₂ n₂ a₂ = if e₂ = 0 then oadd e₁ (n₁ * n₂) a₁ else oadd (e₁ + e₂) n₂ (oadd e₁ n₁ a₁ * a₂) := rfl theorem oadd_mul_NF_below {e₁ n₁ a₁ b₁} (h₁ : NF_below (oadd e₁ n₁ a₁) b₁) : ∀ {o₂ b₂}, NF_below o₂ b₂ → NF_below (oadd e₁ n₁ a₁ * o₂) (repr e₁ + b₂) | 0 b₂ h₂ := NF_below.zero | (oadd e₂ n₂ a₂) b₂ h₂ := begin have IH := oadd_mul_NF_below h₂.snd, by_cases e0 : e₂ = 0; simp [e0, oadd_mul], { apply NF_below.oadd h₁.fst h₁.snd, simpa using (add_lt_add_iff_left (repr e₁)).2 (lt_of_le_of_lt (ordinal.zero_le _) h₂.lt) }, { haveI := h₁.fst, haveI := h₂.fst, apply NF_below.oadd, apply_instance, { rwa repr_add }, { rw [repr_add, ordinal.add_lt_add_iff_left], exact h₂.lt } } end instance mul_NF : ∀ o₁ o₂ [NF o₁] [NF o₂], NF (o₁ * o₂) | 0 o h₁ h₂ := by cases o; exact NF.zero | (oadd e n a) o ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ := ⟨_, oadd_mul_NF_below hb₁ hb₂⟩ @[simp] theorem repr_mul : ∀ o₁ o₂ [NF o₁] [NF o₂], repr (o₁ * o₂) = repr o₁ * repr o₂ | 0 o h₁ h₂ := by cases o; exact (ordinal.zero_mul _).symm | (oadd e₁ n₁ a₁) 0 h₁ h₂ := (ordinal.mul_zero _).symm | (oadd e₁ n₁ a₁) (oadd e₂ n₂ a₂) h₁ h₂ := begin have IH : repr (mul _ _) = _ := @repr_mul _ _ h₁ h₂.snd, conv {to_lhs, simp [(*)]}, have ao : repr a₁ + ω ^ repr e₁ * (n₁:ℕ) = ω ^ repr e₁ * (n₁:ℕ), { apply add_absorp h₁.snd'.repr_lt, simpa using (mul_le_mul_iff_left $ power_pos _ omega_pos).2 (nat_cast_le.2 n₁.2) }, by_cases e0 : e₂ = 0; simp [e0, mul], { cases nat.exists_eq_succ_of_ne_zero n₂.ne_zero with x xe, simp [h₂.zero_of_zero e0, xe, -nat.cast_succ], rw [← nat_cast_succ x, add_mul_succ _ ao, mul_assoc] }, { haveI := h₁.fst, haveI := h₂.fst, simp [IH, repr_add, power_add, ordinal.mul_add], rw ← mul_assoc, congr_n 2, have := mt repr_inj.1 e0, rw [add_mul_limit ao (power_is_limit_left omega_is_limit this), mul_assoc, mul_omega_dvd (nat_cast_pos.2 n₁.pos) (nat_lt_omega _)], simpa using power_dvd_power ω (one_le_iff_ne_zero.2 this) }, end /-- Calculate division and remainder of `o` mod ω. `split' o = (a, n)` means `o = ω * a + n`. -/ def split' : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split' a in (oadd (e - 1) n a', m) /-- Calculate division and remainder of `o` mod ω. `split o = (a, n)` means `o = a + n`, where `ω ∣ a`. -/ def split : onote → onote × ℕ | 0 := (0, 0) | (oadd e n a) := if e = 0 then (0, n) else let (a', m) := split a in (oadd e n a', m) /-- `scale x o` is the ordinal notation for `ω ^ x * o`. -/ def scale (x : onote) : onote → onote | 0 := 0 | (oadd e n a) := oadd (x + e) n (scale a) /-- `mul_nat o n` is the ordinal notation for `o * n`. -/ def mul_nat : onote → ℕ → onote | 0 m := 0 | _ 0 := 0 | (oadd e n a) (m+1) := oadd e (n * m.succ_pnat) a def power_aux (e a0 a : onote) : ℕ → ℕ → onote | _ 0 := 0 | 0 (m+1) := oadd e m.succ_pnat 0 | (k+1) m := scale (e + mul_nat a0 k) a + power_aux k m /-- `power o₁ o₂` calculates the ordinal notation for the ordinal exponential `o₁ ^ o₂`. -/ def power (o₁ o₂ : onote) : onote := match split o₁ with | (0, 0) := if o₂ = 0 then 1 else 0 | (0, 1) := 1 | (0, m+1) := let (b', k) := split' o₂ in oadd b' (@has_pow.pow ℕ+ _ _ m.succ_pnat k) 0 | (a@(oadd a0 _ _), m) := match split o₂ with | (b, 0) := oadd (a0 * b) 1 0 | (b, k+1) := let eb := a0*b in scale (eb + mul_nat a0 k) a + power_aux eb a0 (mul_nat a m) k m end end instance : has_pow onote onote := ⟨power⟩ theorem power_def (o₁ o₂ : onote) : o₁ ^ o₂ = power._match_1 o₂ (split o₁) := rfl theorem split_eq_scale_split' : ∀ {o o' m} [NF o], split' o = (o', m) → split o = (scale 1 o', m) | 0 o' m h p := by injection p; substs o' m; refl | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, exact ⟨rfl, rfl⟩ }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, simp [split_eq_scale_split' h', split, split'], have : 1 + (e - 1) = e, { refine repr_inj.1 _, simp, have := mt repr_inj.1 e0, exact add_sub_cancel_of_le (one_le_iff_ne_zero.2 this) }, intros, substs o' m, simp [scale, this] } end theorem NF_repr_split' : ∀ {o o' m} [NF o], split' o = (o', m) → NF o' ∧ repr o = ω * repr o' + m | 0 o' m h p := by injection p; substs o' m; simp [NF.zero] | (oadd e n a) o' m h p := begin by_cases e0 : e = 0; simp [e0, split, split'] at p ⊢, { rcases p with ⟨rfl, rfl⟩, simp [h.zero_of_zero e0, NF.zero] }, { revert p, cases h' : split' a with a' m', haveI := h.fst, haveI := h.snd, cases NF_repr_split' h' with IH₁ IH₂, simp [IH₂, split'], intros, substs o' m, have : ω ^ repr e = ω ^ (1 : ordinal.{0}) * ω ^ (repr e - 1), { have := mt repr_inj.1 e0, rw [← power_add, add_sub_cancel_of_le (one_le_iff_ne_zero.2 this)] }, refine ⟨NF.oadd (by apply_instance) _ _, _⟩, { simp at this ⊢, refine IH₁.below_of_lt' ((mul_lt_mul_iff_left omega_pos).1 $ lt_of_le_of_lt (le_add_right _ m') _), rw [← this, ← IH₂], exact h.snd'.repr_lt }, { rw this, simp [ordinal.mul_add, mul_assoc] } } end theorem scale_eq_mul (x) [NF x] : ∀ o [NF o], scale x o = oadd x 1 0 * o | 0 h := rfl | (oadd e n a) h := begin simp [(*)], simp [mul, scale], haveI := h.snd, by_cases e0 : e = 0, { rw scale_eq_mul, simp [e0, h.zero_of_zero, show x + 0 = x, from repr_inj.1 (by simp)] }, { simp [e0, scale_eq_mul, (*)] } end instance NF_scale (x) [NF x] (o) [NF o] : NF (scale x o) := by rw scale_eq_mul; apply_instance @[simp] theorem repr_scale (x) [NF x] (o) [NF o] : repr (scale x o) = ω ^ repr x * repr o := by simp [scale_eq_mul] theorem NF_repr_split {o o' m} [NF o] (h : split o = (o', m)) : NF o' ∧ repr o = repr o' + m := begin cases e : split' o with a n, cases NF_repr_split' e with s₁ s₂, resetI, rw split_eq_scale_split' e at h, injection h, substs o' n, simp [repr_scale, s₂.symm], apply_instance end theorem split_dvd {o o' m} [NF o] (h : split o = (o', m)) : ω ∣ repr o' := begin cases e : split' o with a n, rw split_eq_scale_split' e at h, injection h, subst o', cases NF_repr_split' e, resetI, simp [dvd_mul] end theorem split_add_lt {o e n a m} [NF o] (h : split o = (oadd e n a, m)) : repr a + m < ω ^ repr e := begin cases NF_repr_split h with h₁ h₂, cases h₁.of_dvd_omega (split_dvd h) with e0 d, have := h₁.fst, have := h₁.snd, refine add_lt_omega_power h₁.snd'.repr_lt (lt_of_lt_of_le (nat_lt_omega _) _), simpa using power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0), end @[simp] theorem mul_nat_eq_mul (n o) : mul_nat o n = o * of_nat n := by cases o; cases n; refl instance NF_mul_nat (o) [NF o] (n) : NF (mul_nat o n) := by simp; apply_instance instance NF_power_aux (e a0 a) [NF e] [NF a0] [NF a] : ∀ k m, NF (power_aux e a0 a k m) | k 0 := by cases k; exact NF.zero | 0 (m+1) := NF.oadd_zero _ _ | (k+1) (m+1) := by haveI := NF_power_aux k; simp [power_aux, nat.succ_ne_zero]; apply_instance instance NF_power (o₁ o₂) [NF o₁] [NF o₂] : NF (o₁ ^ o₂) := begin cases e₁ : split o₁ with a m, have na := (NF_repr_split e₁).1, cases e₂ : split' o₂ with b' k, haveI := (NF_repr_split' e₂).1, cases a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [pow, power, e₁, h]; apply_instance }, { by_cases m = 0; simp [pow, power, e₁, e₂, h]; apply_instance } }, { simp [pow, power, e₁, e₂, split_eq_scale_split' e₂], have := na.fst, cases k with k; simp [succ_eq_add_one, power]; apply_instance } end theorem scale_power_aux (e a0 a : onote) [NF e] [NF a0] [NF a] : ∀ k m, repr (power_aux e a0 a k m) = ω ^ repr e * repr (power_aux 0 a0 a k m) | 0 m := by cases m; simp [power_aux] | (k+1) m := by by_cases m = 0; simp [h, power_aux, ordinal.mul_add, power_add, mul_assoc, scale_power_aux] theorem repr_power_aux₁ {e a} [Ne : NF e] [Na : NF a] {a' : ordinal} (e0 : repr e ≠ 0) (h : a' < ω ^ repr e) (aa : repr a = a') (n : ℕ+) : (ω ^ repr e * (n:ℕ) + a') ^ ω = (ω ^ repr e) ^ ω := begin subst aa, have No := Ne.oadd n (Na.below_of_lt' h), have := omega_le_oadd e n a, unfold repr at this, refine le_antisymm _ (power_le_power_left _ this), apply (power_le_of_limit (ne_of_gt $ lt_of_lt_of_le (power_pos _ omega_pos) this) omega_is_limit).2, intros b l, have := (No.below_of_lt (lt_succ_self _)).repr_lt, unfold repr at this, apply le_trans (power_le_power_left b $ le_of_lt this), rw [← power_mul, ← power_mul], apply power_le_power_right omega_pos, cases le_or_lt ω (repr e) with h h, { apply le_trans (mul_le_mul_left _ $ le_of_lt $ lt_succ_self _), rw [succ, add_mul_succ _ (one_add_of_omega_le h), ← succ, succ_le, mul_lt_mul_iff_left (pos_iff_ne_zero.2 e0)], exact omega_is_limit.2 _ l }, { refine le_trans (le_of_lt $ mul_lt_omega (omega_is_limit.2 _ h) l) _, simpa using mul_le_mul_right ω (one_le_iff_ne_zero.2 e0) } end section local infixr ^ := @pow ordinal.{0} ordinal ordinal.has_pow theorem repr_power_aux₂ {a0 a'} [N0 : NF a0] [Na' : NF a'] (m : ℕ) (d : ω ∣ repr a') (e0 : repr a0 ≠ 0) (h : repr a' + m < ω ^ repr a0) (n : ℕ+) (k : ℕ) : let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m) in (k ≠ 0 → R < (ω ^ repr a0) ^ succ k) ∧ (ω ^ repr a0) ^ k * (ω ^ repr a0 * (n:ℕ) + repr a') + R = (ω ^ repr a0 * (n:ℕ) + repr a' + m) ^ succ k := begin intro, haveI No : NF (oadd a0 n a') := N0.oadd n (Na'.below_of_lt' $ lt_of_le_of_lt (le_add_right _ _) h), induction k with k IH, {cases m; simp [power_aux, R]}, rename R R', let R := repr (power_aux 0 a0 (oadd a0 n a' * of_nat m) k m), let ω0 := ω ^ repr a0, let α' := ω0 * n + repr a', change (k ≠ 0 → R < ω0 ^ succ k) ∧ ω0 ^ k * α' + R = (α' + m) ^ succ k at IH, have RR : R' = ω0 ^ k * (α' * m) + R, { by_cases m = 0; simp [h, R', power_aux, R, power_mul], { cases k; simp [power_aux] }, { refl } }, have α0 : 0 < α', {simpa [α', lt_def, repr] using oadd_pos a0 n a'}, have ω00 : 0 < ω0 ^ k := power_pos _ (power_pos _ omega_pos), have Rl : R < ω ^ (repr a0 * succ ↑k), { by_cases k0 : k = 0, { simp [k0], refine lt_of_lt_of_le _ (power_le_power_right omega_pos (one_le_iff_ne_zero.2 e0)), cases m with m; simp [k0, R, power_aux, omega_pos], rw [← nat.cast_succ], apply nat_lt_omega }, { rw power_mul, exact IH.1 k0 } }, refine ⟨λ_, _, _⟩, { rw [RR, ← power_mul _ _ (succ k.succ)], have e0 := pos_iff_ne_zero.2 e0, have rr0 := lt_of_lt_of_le e0 (le_add_left _ _), apply add_lt_omega_power, { simp [power_mul, ω0, power_add], rw [mul_lt_mul_iff_left ω00, ← ordinal.power_add], have := (No.below_of_lt _).repr_lt, unfold repr at this, refine mul_lt_omega_power rr0 this (nat_lt_omega _), simpa using (add_lt_add_iff_left (repr a0)).2 e0 }, { refine lt_of_lt_of_le Rl (power_le_power_right omega_pos $ mul_le_mul_left _ $ succ_le_succ.2 $ nat_cast_le.2 $ le_of_lt k.lt_succ_self) } }, refine calc ω0 ^ k.succ * α' + R' = ω0 ^ succ k * α' + (ω0 ^ k * α' * m + R) : by rw [nat_cast_succ, RR, ← mul_assoc] ... = (ω0 ^ k * α' + R) * α' + (ω0 ^ k * α' + R) * m : _ ... = (α' + m) ^ succ k.succ : by rw [← ordinal.mul_add, ← nat_cast_succ, power_succ, IH.2], congr_n 1, { have αd : ω ∣ α' := dvd_add (dvd_mul_of_dvd _ (by simpa using power_dvd_power ω (one_le_iff_ne_zero.2 e0))) d, rw [ordinal.mul_add (ω0 ^ k), add_assoc, ← mul_assoc, ← power_succ, add_mul_limit _ (is_limit_iff_omega_dvd.2 ⟨ne_of_gt α0, αd⟩), mul_assoc, @mul_omega_dvd n (nat_cast_pos.2 n.pos) (nat_lt_omega _) _ αd], apply @add_absorp _ (repr a0 * succ k), { refine add_lt_omega_power _ Rl, rw [power_mul, power_succ, mul_lt_mul_iff_left ω00], exact No.snd'.repr_lt }, { have := mul_le_mul_left (ω0 ^ succ k) (one_le_iff_pos.2 $ nat_cast_pos.2 n.pos), rw power_mul, simpa [-power_succ] } }, { cases m, { have : R = 0, {cases k; simp [R, power_aux]}, simp [this] }, { rw [← nat_cast_succ, add_mul_succ], apply add_absorp Rl, rw [power_mul, power_succ], apply ordinal.mul_le_mul_left, simpa [α', repr] using omega_le_oadd a0 n a' } } end end theorem repr_power (o₁ o₂) [NF o₁] [NF o₂] : repr (o₁ ^ o₂) = repr o₁ ^ repr o₂ := begin cases e₁ : split o₁ with a m, cases NF_repr_split e₁ with N₁ r₁, cases a with a0 n a', { cases m with m, { by_cases o₂ = 0; simp [power_def, power, e₁, h, r₁], have := mt repr_inj.1 h, rw zero_power this }, { cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, by_cases m = 0; simp [power_def, power, e₁, h, r₁, e₂, r₂, -nat.cast_succ], rw [power_add, power_mul, power_omega _ (nat_lt_omega _)], simpa using nat_cast_lt.2 (nat.succ_lt_succ $ nat.pos_iff_ne_zero.2 h) } }, { haveI := N₁.fst, haveI := N₁.snd, cases N₁.of_dvd_omega (split_dvd e₁) with a00 ad, have al := split_add_lt e₁, have aa : repr (a' + of_nat m) = repr a' + m, {simp}, cases e₂ : split' o₂ with b' k, cases NF_repr_split' e₂ with _ r₂, simp [power_def, power, e₁, r₁, split_eq_scale_split' e₂], cases k with k, { simp [power, r₂, power_mul, repr_power_aux₁ a00 al aa] }, { simp [succ_eq_add_one, power, r₂, power_add, power_mul, mul_assoc], rw [repr_power_aux₁ a00 al aa, scale_power_aux], simp [power_mul], rw [← ordinal.mul_add, ← add_assoc (ω ^ repr a0 * (n:ℕ))], congr_n 1, rw [← power_succ], exact (repr_power_aux₂ _ ad a00 al _ _).2 } } end end onote /-- The type of normal ordinal notations. (It would have been nicer to define this right in the inductive type, but `NF o` requires `repr` which requires `onote`, so all these things would have to be defined at once, which messes up the VM representation.) -/ def nonote := {o : onote // o.NF} instance : decidable_eq nonote := by unfold nonote; apply_instance namespace nonote open onote instance NF (o : nonote) : NF o.1 := o.2 /-- Construct a `nonote` from an ordinal notation (and infer normality) -/ def mk (o : onote) [h : NF o] : nonote := ⟨o, h⟩ /-- The ordinal represented by an ordinal notation. (This function is noncomputable because ordinal arithmetic is noncomputable. In computational applications `nonote` can be used exclusively without reference to `ordinal`, but this function allows for correctness results to be stated.) -/ noncomputable def repr (o : nonote) : ordinal := o.1.repr instance : has_to_string nonote := ⟨λ x, x.1.to_string⟩ instance : has_repr nonote := ⟨λ x, x.1.repr'⟩ instance : preorder nonote := { le := λ x y, repr x ≤ repr y, lt := λ x y, repr x < repr y, le_refl := λ a, @le_refl ordinal _ _, le_trans := λ a b c, @le_trans ordinal _ _ _ _, lt_iff_le_not_le := λ a b, @lt_iff_le_not_le ordinal _ _ _ } instance : has_zero nonote := ⟨⟨0, NF.zero⟩⟩ /-- Convert a natural number to an ordinal notation -/ def of_nat (n : ℕ) : nonote := ⟨of_nat n, _, NF_below_of_nat _⟩ /-- Compare ordinal notations -/ def cmp (a b : nonote) : ordering := cmp a.1 b.1 theorem cmp_compares : ∀ a b : nonote, (cmp a b).compares a b | ⟨a, ha⟩ ⟨b, hb⟩ := begin resetI, dsimp [cmp], have := onote.cmp_compares a b, cases onote.cmp a b; try {exact this}, exact subtype.mk_eq_mk.2 this end instance : linear_order nonote := { le_antisymm := λ a b, match cmp a b, cmp_compares a b with | ordering.lt, h, h₁, h₂ := (not_lt_of_le h₂).elim h | ordering.eq, h, h₁, h₂ := h | ordering.gt, h, h₁, h₂ := (not_lt_of_le h₁).elim h end, le_total := λ a b, match cmp a b, cmp_compares a b with | ordering.lt, h := or.inl (le_of_lt h) | ordering.eq, h := or.inl (le_of_eq h) | ordering.gt, h := or.inr (le_of_lt h) end, ..nonote.preorder } instance decidable_lt : @decidable_rel nonote (<) | a b := decidable_of_iff _ (cmp_compares a b).eq_lt instance : decidable_linear_order nonote := { decidable_le := λ a b, decidable_of_iff _ not_lt, decidable_lt := nonote.decidable_lt, ..nonote.linear_order } /-- Asserts that `repr a < ω ^ repr b`. Used in `nonote.rec_on` -/ def below (a b : nonote) : Prop := NF_below a.1 (repr b) /-- The `oadd` pseudo-constructor for `nonote` -/ def oadd (e : nonote) (n : ℕ+) (a : nonote) (h : below a e) : nonote := ⟨_, NF.oadd e.2 n h⟩ /-- This is a recursor-like theorem for `nonote` suggesting an inductive definition, which can't actually be defined this way due to conflicting dependencies. -/ @[elab_as_eliminator] def rec_on {C : nonote → Sort*} (o : nonote) (H0 : C 0) (H1 : ∀ e n a h, C e → C a → C (oadd e n a h)) : C o := begin cases o with o h, induction o with e n a IHe IHa, { exact H0 }, { exact H1 ⟨e, h.fst⟩ n ⟨a, h.snd⟩ h.snd' (IHe _) (IHa _) } end /-- Addition of ordinal notations -/ instance : has_add nonote := ⟨λ x y, mk (x.1 + y.1)⟩ theorem repr_add (a b) : repr (a + b) = repr a + repr b := onote.repr_add a.1 b.1 /-- Subtraction of ordinal notations -/ instance : has_sub nonote := ⟨λ x y, mk (x.1 - y.1)⟩ theorem repr_sub (a b) : repr (a - b) = repr a - repr b := onote.repr_sub a.1 b.1 /-- Multiplication of ordinal notations -/ instance : has_mul nonote := ⟨λ x y, mk (x.1 * y.1)⟩ theorem repr_mul (a b) : repr (a * b) = repr a * repr b := onote.repr_mul a.1 b.1 /-- Exponentiation of ordinal notations -/ def power (x y : nonote) := mk (x.1.power y.1) theorem repr_power (a b) : repr (power a b) = (repr a).power (repr b) := onote.repr_power a.1 b.1 end nonote
cadcf5c96e4eb3d9dd81b652d3a8b6d46c215a06
4727251e0cd73359b15b664c3170e5d754078599
/src/model_theory/satisfiability.lean
6e333061e03ffc7c877ca15b7adb1e77897a470c
[ "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
17,552
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import model_theory.ultraproducts import model_theory.bundled import model_theory.skolem /-! # First-Order Satisfiability This file deals with the satisfiability of first-order theories, as well as equivalence over them. ## Main Definitions * `first_order.language.Theory.is_satisfiable`: `T.is_satisfiable` indicates that `T` has a nonempty model. * `first_order.language.Theory.is_finitely_satisfiable`: `T.is_finitely_satisfiable` indicates that every finite subset of `T` is satisfiable. * `first_order.language.Theory.is_complete`: `T.is_complete` indicates that `T` is satisfiable and models each sentence or its negation. * `first_order.language.Theory.semantically_equivalent`: `T.semantically_equivalent φ ψ` indicates that `φ` and `ψ` are equivalent formulas or sentences in models of `T`. * `cardinal.categorical`: A theory is `κ`-categorical if all models of size `κ` are isomorphic. ## Main Results * The Compactness Theorem, `first_order.language.Theory.is_satisfiable_iff_is_finitely_satisfiable`, shows that a theory is satisfiable iff it is finitely satisfiable. * `first_order.language.complete_theory.is_complete`: The complete theory of a structure is complete. * `first_order.language.Theory.exists_large_model_of_infinite_model` shows that any theory with an infinite model has arbitrarily large models. ## Implementation Details * Satisfiability of an `L.Theory` `T` is defined in the minimal universe containing all the symbols of `L`. By Löwenheim-Skolem, this is equivalent to satisfiability in any universe. -/ universes u v w w' open cardinal open_locale cardinal first_order namespace first_order namespace language variables {L : language.{u v}} {T : L.Theory} {α : Type w} {n : ℕ} namespace Theory variable (T) /-- A theory is satisfiable if a structure models it. -/ def is_satisfiable : Prop := nonempty (Model.{u v (max u v)} T) /-- A theory is finitely satisfiable if all of its finite subtheories are satisfiable. -/ def is_finitely_satisfiable : Prop := ∀ (T0 : finset L.sentence), (T0 : L.Theory) ⊆ T → (T0 : L.Theory).is_satisfiable variables {T} {T' : L.Theory} lemma model.is_satisfiable (M : Type w) [n : nonempty M] [S : L.Structure M] [M ⊨ T] : T.is_satisfiable := ⟨((⊥ : substructure _ (Model.of T M)).elementary_skolem₁_reduct.to_Model T).shrink⟩ lemma is_satisfiable.mono (h : T'.is_satisfiable) (hs : T ⊆ T') : T.is_satisfiable := ⟨(Theory.model.mono (Model.is_model h.some) hs).bundled⟩ lemma is_satisfiable.is_finitely_satisfiable (h : T.is_satisfiable) : T.is_finitely_satisfiable := λ _, h.mono /-- The Compactness Theorem of first-order logic: A theory is satisfiable if and only if it is finitely satisfiable. -/ theorem is_satisfiable_iff_is_finitely_satisfiable {T : L.Theory} : T.is_satisfiable ↔ T.is_finitely_satisfiable := ⟨Theory.is_satisfiable.is_finitely_satisfiable, λ h, begin classical, set M : Π (T0 : finset T), Type (max u v) := λ T0, (h (T0.map (function.embedding.subtype (λ x, x ∈ T))) T0.map_subtype_subset).some with hM, let M' := filter.product ↑(ultrafilter.of (filter.at_top : filter (finset T))) M, haveI h' : M' ⊨ T, { refine ⟨λ φ hφ, _⟩, rw ultraproduct.sentence_realize, refine filter.eventually.filter_mono (ultrafilter.of_le _) (filter.eventually_at_top.2 ⟨{⟨φ, hφ⟩}, λ s h', Theory.realize_sentence_of_mem (s.map (function.embedding.subtype (λ x, x ∈ T))) _⟩), simp only [finset.coe_map, function.embedding.coe_subtype, set.mem_image, finset.mem_coe, subtype.exists, subtype.coe_mk, exists_and_distrib_right, exists_eq_right], exact ⟨hφ, h' (finset.mem_singleton_self _)⟩ }, exact ⟨Model.of T M'⟩, end⟩ theorem is_satisfiable_directed_union_iff {ι : Type*} [nonempty ι] {T : ι → L.Theory} (h : directed (⊆) T) : Theory.is_satisfiable (⋃ i, T i) ↔ ∀ i, (T i).is_satisfiable := begin refine ⟨λ h' i, h'.mono (set.subset_Union _ _), λ h', _⟩, rw [is_satisfiable_iff_is_finitely_satisfiable, is_finitely_satisfiable], intros T0 hT0, obtain ⟨i, hi⟩ := h.exists_mem_subset_of_finset_subset_bUnion hT0, exact (h' i).mono hi, end theorem is_satisfiable_union_distinct_constants_theory_of_card_le (T : L.Theory) (s : set α) (M : Type w') [nonempty M] [L.Structure M] [M ⊨ T] (h : cardinal.lift.{w'} (# s) ≤ cardinal.lift.{w} (# M)) : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin haveI : inhabited M := classical.inhabited_of_nonempty infer_instance, rw [cardinal.lift_mk_le'] at h, letI : (constants_on α).Structure M := constants_on.Structure (function.extend coe h.some default), haveI : M ⊨ (L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s, { refine ((Lhom.on_Theory_model _ _).2 infer_instance).union _, rw [model_distinct_constants_theory], refine λ a as b bs ab, _, rw [← subtype.coe_mk a as, ← subtype.coe_mk b bs, ← subtype.ext_iff], exact h.some.injective ((function.extend_apply subtype.coe_injective h.some default ⟨a, as⟩).symm.trans (ab.trans (function.extend_apply subtype.coe_injective h.some default ⟨b, bs⟩))), }, exact model.is_satisfiable M, end theorem is_satisfiable_union_distinct_constants_theory_of_infinite (T : L.Theory) (s : set α) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ((L.Lhom_with_constants α).on_Theory T ∪ L.distinct_constants_theory s).is_satisfiable := begin classical, rw [distinct_constants_theory_eq_Union, set.union_Union, is_satisfiable_directed_union_iff], { exact λ t, is_satisfiable_union_distinct_constants_theory_of_card_le T _ M ((lift_le_omega.2 (le_of_lt (finset_card_lt_omega _))).trans (omega_le_lift.2 (omega_le_mk M))), }, { refine (monotone_const.union (monotone_distinct_constants_theory.comp _)).directed_le, simp only [finset.coe_map, function.embedding.coe_subtype], exact set.monotone_image.comp (λ _ _, finset.coe_subset.2) } end /-- Any theory with an infinite model has arbitrarily large models. -/ lemma exists_large_model_of_infinite_model (T : L.Theory) (κ : cardinal.{w}) (M : Type w') [L.Structure M] [M ⊨ T] [infinite M] : ∃ (N : Model.{_ _ (max u v w)} T), cardinal.lift.{max u v w} κ ≤ # N := begin obtain ⟨N⟩ := is_satisfiable_union_distinct_constants_theory_of_infinite T (set.univ : set κ.out) M, refine ⟨(N.is_model.mono (set.subset_union_left _ _)).bundled.reduct _, _⟩, haveI : N ⊨ distinct_constants_theory _ _ := N.is_model.mono (set.subset_union_right _ _), simp only [Model.reduct_carrier, coe_of, Model.carrier_eq_coe], refine trans (lift_le.2 (le_of_eq (cardinal.mk_out κ).symm)) _, rw [← mk_univ], refine (card_le_of_model_distinct_constants_theory L set.univ N).trans (lift_le.1 _), rw lift_lift, end variable (T) /-- A theory models a (bounded) formula when any of its nonempty models realizes that formula on all inputs.-/ def models_bounded_formula (φ : L.bounded_formula α n) : Prop := ∀ (M : Model.{u v (max u v)} T) (v : α → M) (xs : fin n → M), φ.realize v xs infix ` ⊨ `:51 := models_bounded_formula -- input using \|= or \vDash, but not using \models variable {T} lemma models_formula_iff {φ : L.formula α} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T) (v : α → M), φ.realize v := forall_congr (λ M, forall_congr (λ v, unique.forall_iff)) lemma models_sentence_iff {φ : L.sentence} : T ⊨ φ ↔ ∀ (M : Model.{u v (max u v)} T), M ⊨ φ := models_formula_iff.trans (forall_congr (λ M, unique.forall_iff)) lemma models_sentence_of_mem {φ : L.sentence} (h : φ ∈ T) : T ⊨ φ := models_sentence_iff.2 (λ _, realize_sentence_of_mem T h) /-- A theory is complete when it is satisfiable and models each sentence or its negation. -/ def is_complete (T : L.Theory) : Prop := T.is_satisfiable ∧ ∀ (φ : L.sentence), (T ⊨ φ) ∨ (T ⊨ φ.not) /-- Two (bounded) formulas are semantically equivalent over a theory `T` when they have the same interpretation in every model of `T`. (This is also known as logical equivalence, which also has a proof-theoretic definition.) -/ def semantically_equivalent (T : L.Theory) (φ ψ : L.bounded_formula α n) : Prop := T ⊨ φ.iff ψ @[refl] lemma semantically_equivalent.refl (φ : L.bounded_formula α n) : T.semantically_equivalent φ φ := λ M v xs, by rw bounded_formula.realize_iff instance : is_refl (L.bounded_formula α n) T.semantically_equivalent := ⟨semantically_equivalent.refl⟩ @[symm] lemma semantically_equivalent.symm {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent ψ φ := λ M v xs, begin rw [bounded_formula.realize_iff, iff.comm, ← bounded_formula.realize_iff], exact h M v xs, end @[trans] lemma semantically_equivalent.trans {φ ψ θ : L.bounded_formula α n} (h1 : T.semantically_equivalent φ ψ) (h2 : T.semantically_equivalent ψ θ) : T.semantically_equivalent φ θ := λ M v xs, begin have h1' := h1 M v xs, have h2' := h2 M v xs, rw [bounded_formula.realize_iff] at *, exact ⟨h2'.1 ∘ h1'.1, h1'.2 ∘ h2'.2⟩, end lemma semantically_equivalent.realize_bd_iff {φ ψ : L.bounded_formula α n} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] [hM : T.model M] (h : T.semantically_equivalent φ ψ) {v : α → M} {xs : (fin n → M)} : φ.realize v xs ↔ ψ.realize v xs := bounded_formula.realize_iff.1 (h (Model.of T M) v xs) lemma semantically_equivalent.realize_iff {φ ψ : L.formula α} {M : Type (max u v)} [ne : nonempty M] [str : L.Structure M] (hM : T.model M) (h : T.semantically_equivalent φ ψ) {v : α → M} : φ.realize v ↔ ψ.realize v := h.realize_bd_iff /-- Semantic equivalence forms an equivalence relation on formulas. -/ def semantically_equivalent_setoid (T : L.Theory) : setoid (L.bounded_formula α n) := { r := semantically_equivalent T, iseqv := ⟨λ _, refl _, λ a b h, h.symm, λ _ _ _ h1 h2, h1.trans h2⟩ } protected lemma semantically_equivalent.all {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.all ψ.all := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_all], exact λ M v xs, forall_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.ex {φ ψ : L.bounded_formula α (n + 1)} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.ex ψ.ex := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_ex], exact λ M v xs, exists_congr (λ a, h.realize_bd_iff), end protected lemma semantically_equivalent.not {φ ψ : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) : T.semantically_equivalent φ.not ψ.not := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_not], exact λ M v xs, not_congr h.realize_bd_iff, end protected lemma semantically_equivalent.imp {φ ψ φ' ψ' : L.bounded_formula α n} (h : T.semantically_equivalent φ ψ) (h' : T.semantically_equivalent φ' ψ') : T.semantically_equivalent (φ.imp φ') (ψ.imp ψ') := begin simp_rw [semantically_equivalent, models_bounded_formula, bounded_formula.realize_iff, bounded_formula.realize_imp], exact λ M v xs, imp_congr h.realize_bd_iff h'.realize_bd_iff, end end Theory namespace complete_theory variables (L) (M : Type w) [L.Structure M] lemma is_satisfiable [nonempty M] : (L.complete_theory M).is_satisfiable := Theory.model.is_satisfiable M lemma mem_or_not_mem (φ : L.sentence) : φ ∈ L.complete_theory M ∨ φ.not ∈ L.complete_theory M := by simp_rw [complete_theory, set.mem_set_of_eq, sentence.realize, formula.realize_not, or_not] lemma is_complete [nonempty M] : (L.complete_theory M).is_complete := ⟨is_satisfiable L M, λ φ, ((mem_or_not_mem L M φ).imp Theory.models_sentence_of_mem Theory.models_sentence_of_mem)⟩ end complete_theory namespace bounded_formula variables (φ ψ : L.bounded_formula α n) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := λ M v xs, by simp lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := λ M v xs, by simp [imp_iff_not_or] lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := λ M v xs, by simp [imp_iff_not_or] lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := λ M v xs, by simp [and_iff_not_or_not] lemma all_semantically_equivalent_not_ex_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.all φ.not.ex.not := λ M v xs, by simp lemma ex_semantically_equivalent_not_all_not (φ : L.bounded_formula α (n + 1)) : T.semantically_equivalent φ.ex φ.not.all.not := λ M v xs, by simp lemma semantically_equivalent_all_lift_at : T.semantically_equivalent φ (φ.lift_at 1 n).all := λ M v xs, by { resetI, rw [realize_iff, realize_all_lift_at_one_self] } end bounded_formula namespace formula variables (φ ψ : L.formula α) lemma semantically_equivalent_not_not : T.semantically_equivalent φ φ.not.not := φ.semantically_equivalent_not_not lemma imp_semantically_equivalent_not_sup : T.semantically_equivalent (φ.imp ψ) (φ.not ⊔ ψ) := φ.imp_semantically_equivalent_not_sup ψ lemma sup_semantically_equivalent_not_inf_not : T.semantically_equivalent (φ ⊔ ψ) (φ.not ⊓ ψ.not).not := φ.sup_semantically_equivalent_not_inf_not ψ lemma inf_semantically_equivalent_not_sup_not : T.semantically_equivalent (φ ⊓ ψ) (φ.not ⊔ ψ.not).not := φ.inf_semantically_equivalent_not_sup_not ψ end formula namespace bounded_formula lemma is_qf.induction_on_sup_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hsup : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊔ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := is_qf.rec_on h hf ha (λ φ₁ φ₂ _ _ h1 h2, (hse (φ₁.imp_semantically_equivalent_not_sup φ₂)).2 (hsup (hnot h1) h2)) lemma is_qf.induction_on_inf_not {P : L.bounded_formula α n → Prop} {φ : L.bounded_formula α n} (h : is_qf φ) (hf : P (⊥ : L.bounded_formula α n)) (ha : ∀ (ψ : L.bounded_formula α n), is_atomic ψ → P ψ) (hinf : ∀ {φ₁ φ₂} (h₁ : P φ₁) (h₂ : P φ₂), P (φ₁ ⊓ φ₂)) (hnot : ∀ {φ} (h : P φ), P φ.not) (hse : ∀ {φ₁ φ₂ : L.bounded_formula α n} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := h.induction_on_sup_not hf ha (λ φ₁ φ₂ h1 h2, ((hse (φ₁.sup_semantically_equivalent_not_inf_not φ₂)).2 (hnot (hinf (hnot h1) (hnot h2))))) (λ _, hnot) (λ _ _, hse) lemma semantically_equivalent_to_prenex (φ : L.bounded_formula α n) : (∅ : L.Theory).semantically_equivalent φ φ.to_prenex := λ M v xs, by rw [realize_iff, realize_to_prenex] lemma induction_on_all_ex {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hall : ∀ {m} {ψ : L.bounded_formula α (m + 1)} (h : P ψ), P ψ.all) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := begin suffices h' : ∀ {m} {φ : L.bounded_formula α m}, φ.is_prenex → P φ, { exact (hse φ.semantically_equivalent_to_prenex).2 (h' φ.to_prenex_is_prenex) }, intros m φ hφ, induction hφ with _ _ hφ _ _ _ hφ _ _ _ hφ, { exact hqf hφ }, { exact hall hφ, }, { exact hex hφ, }, end lemma induction_on_exists_not {P : Π {m}, L.bounded_formula α m → Prop} (φ : L.bounded_formula α n) (hqf : ∀ {m} {ψ : L.bounded_formula α m}, is_qf ψ → P ψ) (hnot : ∀ {m} {φ : L.bounded_formula α m} (h : P φ), P φ.not) (hex : ∀ {m} {φ : L.bounded_formula α (m + 1)} (h : P φ), P φ.ex) (hse : ∀ {m} {φ₁ φ₂ : L.bounded_formula α m} (h : Theory.semantically_equivalent ∅ φ₁ φ₂), P φ₁ ↔ P φ₂) : P φ := φ.induction_on_all_ex (λ _ _, hqf) (λ _ φ hφ, (hse φ.all_semantically_equivalent_not_ex_not).2 (hnot (hex (hnot hφ)))) (λ _ _, hex) (λ _ _ _, hse) end bounded_formula end language end first_order namespace cardinal open first_order first_order.language variables {L : language.{u v}} (κ : cardinal.{w}) (T : L.Theory) /-- A theory is `κ`-categorical if all models of size `κ` are isomorphic. -/ def categorical : Prop := ∀ (M N : T.Model), # M = κ → # N = κ → nonempty (M ≃[L] N) theorem empty_Theory_categorical (T : language.empty.Theory) : κ.categorical T := λ M N hM hN, by rw [empty.nonempty_equiv_iff, hM, hN] end cardinal
2f8d4b0d67de94b3450e4355191f75ba4f997550
c777c32c8e484e195053731103c5e52af26a25d1
/src/algebraic_topology/dold_kan/normalized.lean
c182615e41b7c7e21c3c77b47376925c0cea6f93
[ "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
6,421
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import algebraic_topology.dold_kan.functor_n /-! # Comparison with the normalized Moore complex functor > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. TODO (@joelriou) continue adding the various files referenced below In this file, we show that when the category `A` is abelian, there is an isomorphism `N₁_iso_normalized_Moore_complex_comp_to_karoubi` between the functor `N₁ : simplicial_object A ⥤ karoubi (chain_complex A ℕ)` defined in `functor_n.lean` and the composition of `normalized_Moore_complex A` with the inclusion `chain_complex A ℕ ⥤ karoubi (chain_complex A ℕ)`. This isomorphism shall be used in `equivalence.lean` in order to obtain the Dold-Kan equivalence `category_theory.abelian.dold_kan.equivalence : simplicial_object A ≌ chain_complex A ℕ` with a functor (definitionally) equal to `normalized_Moore_complex A`. -/ open category_theory category_theory.category category_theory.limits category_theory.subobject category_theory.idempotents open_locale dold_kan noncomputable theory namespace algebraic_topology namespace dold_kan universe v variables {A : Type*} [category A] [abelian A] {X : simplicial_object A} lemma higher_faces_vanish.inclusion_of_Moore_complex_map (n : ℕ) : higher_faces_vanish (n+1) ((inclusion_of_Moore_complex_map X).f (n+1)) := λ j hj, begin dsimp [inclusion_of_Moore_complex_map], rw [← factor_thru_arrow _ _ (finset_inf_arrow_factors finset.univ _ j (by simp only [finset.mem_univ])), assoc, kernel_subobject_arrow_comp, comp_zero], end lemma factors_normalized_Moore_complex_P_infty (n : ℕ) : subobject.factors (normalized_Moore_complex.obj_X X n) (P_infty.f n) := begin cases n, { apply top_factors, }, { rw [P_infty_f, normalized_Moore_complex.obj_X, finset_inf_factors], intros i hi, apply kernel_subobject_factors, exact (higher_faces_vanish.of_P (n+1) n) i (le_add_self), } end /-- P_infty factors through the normalized Moore complex -/ @[simps] def P_infty_to_normalized_Moore_complex (X : simplicial_object A) : K[X] ⟶ N[X] := chain_complex.of_hom _ _ _ _ _ _ (λ n, factor_thru _ _ (factors_normalized_Moore_complex_P_infty n)) (λ n, begin rw [← cancel_mono (normalized_Moore_complex.obj_X X n).arrow, assoc, assoc, factor_thru_arrow, ← inclusion_of_Moore_complex_map_f, ← normalized_Moore_complex_obj_d, ← (inclusion_of_Moore_complex_map X).comm' (n+1) n rfl, inclusion_of_Moore_complex_map_f, factor_thru_arrow_assoc, ← alternating_face_map_complex_obj_d], exact P_infty.comm' (n+1) n rfl, end) @[simp, reassoc] lemma P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map (X : simplicial_object A) : P_infty_to_normalized_Moore_complex X ≫ inclusion_of_Moore_complex_map X = P_infty := by tidy @[simp, reassoc] lemma P_infty_to_normalized_Moore_complex_naturality {X Y : simplicial_object A} (f : X ⟶ Y) : alternating_face_map_complex.map f ≫ P_infty_to_normalized_Moore_complex Y = P_infty_to_normalized_Moore_complex X ≫ normalized_Moore_complex.map f := by tidy @[simp, reassoc] lemma P_infty_comp_P_infty_to_normalized_Moore_complex (X : simplicial_object A) : P_infty ≫ P_infty_to_normalized_Moore_complex X = P_infty_to_normalized_Moore_complex X := by tidy @[simp, reassoc] lemma inclusion_of_Moore_complex_map_comp_P_infty (X : simplicial_object A) : inclusion_of_Moore_complex_map X ≫ P_infty = inclusion_of_Moore_complex_map X := begin ext n, cases n, { dsimp, simp only [comp_id], }, { exact (higher_faces_vanish.inclusion_of_Moore_complex_map n).comp_P_eq_self, }, end instance : mono (inclusion_of_Moore_complex_map X) := ⟨λ Y f₁ f₂ hf, by { ext n, exact homological_complex.congr_hom hf n, }⟩ /-- `inclusion_of_Moore_complex_map X` is a split mono. -/ def split_mono_inclusion_of_Moore_complex_map (X : simplicial_object A) : split_mono (inclusion_of_Moore_complex_map X) := { retraction := P_infty_to_normalized_Moore_complex X, id' := by simp only [← cancel_mono (inclusion_of_Moore_complex_map X), assoc, id_comp, P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, inclusion_of_Moore_complex_map_comp_P_infty], } variable (A) /-- When the category `A` is abelian, the functor `N₁ : simplicial_object A ⥤ karoubi (chain_complex A ℕ)` defined using `P_infty` identifies to the composition of the normalized Moore complex functor and the inclusion in the Karoubi envelope. -/ def N₁_iso_normalized_Moore_complex_comp_to_karoubi : N₁ ≅ (normalized_Moore_complex A ⋙ to_karoubi _) := { hom := { app := λ X, { f := P_infty_to_normalized_Moore_complex X, comm := by erw [comp_id, P_infty_comp_P_infty_to_normalized_Moore_complex] }, naturality' := λ X Y f, by simp only [functor.comp_map, normalized_Moore_complex_map, P_infty_to_normalized_Moore_complex_naturality, karoubi.hom_ext, karoubi.comp_f, N₁_map_f, P_infty_comp_P_infty_to_normalized_Moore_complex_assoc, to_karoubi_map_f, assoc] }, inv := { app := λ X, { f := inclusion_of_Moore_complex_map X, comm := by erw [inclusion_of_Moore_complex_map_comp_P_infty, id_comp] }, naturality' := λ X Y f, by { ext, simp only [functor.comp_map, normalized_Moore_complex_map, karoubi.comp_f, to_karoubi_map_f, homological_complex.comp_f, normalized_Moore_complex.map_f, inclusion_of_Moore_complex_map_f, factor_thru_arrow, N₁_map_f, inclusion_of_Moore_complex_map_comp_P_infty_assoc, alternating_face_map_complex.map_f] } }, hom_inv_id' := begin ext X : 3, simp only [P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, nat_trans.comp_app, karoubi.comp_f, N₁_obj_p, nat_trans.id_app, karoubi.id_eq], end, inv_hom_id' := begin ext X : 3, simp only [← cancel_mono (inclusion_of_Moore_complex_map X), nat_trans.comp_app, karoubi.comp_f, assoc, nat_trans.id_app, karoubi.id_eq, P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map, inclusion_of_Moore_complex_map_comp_P_infty], dsimp only [functor.comp_obj, to_karoubi], rw id_comp, end } end dold_kan end algebraic_topology
24c6896596335470b3f62f6da9cbd40c1ea29f54
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/measure_theory/group/prod.lean
296ab73148c1a34ead79e82cb8a7e5b388f17ad9
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
15,713
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.constructions.prod import measure_theory.group.measure /-! # Measure theory in the product of groups In this file we show properties about measure theory in products of measurable groups and properties of iterated integrals in measurable groups. These lemmas show the uniqueness of left invariant measures on measurable groups, up to scaling. In this file we follow the proof and refer to the book *Measure Theory* by Paul Halmos. The idea of the proof is to use the translation invariance of measures to prove `μ(F) = c * μ(E)` for two sets `E` and `F`, where `c` is a constant that does not depend on `μ`. Let `e` and `f` be the characteristic functions of `E` and `F`. Assume that `μ` and `ν` are left-invariant measures. Then the map `(x, y) ↦ (y * x, x⁻¹)` preserves the measure `μ.prod ν`, which means that ``` ∫ x, ∫ y, h x y ∂ν ∂μ = ∫ x, ∫ y, h (y * x) x⁻¹ ∂ν ∂μ ``` If we apply this to `h x y := e x * f y⁻¹ / ν ((λ h, h * y⁻¹) ⁻¹' E)`, we can rewrite the RHS to `μ(F)`, and the LHS to `c * μ(E)`, where `c = c(ν)` does not depend on `μ`. Applying this to `μ` and to `ν` gives `μ (F) / μ (E) = ν (F) / ν (E)`, which is the uniqueness up to scalar multiplication. The proof in [Halmos] seems to contain an omission in §60 Th. A, see `measure_theory.measure_lintegral_div_measure`. -/ noncomputable theory open set (hiding prod_eq) function measure_theory filter (hiding map) open_locale classical ennreal pointwise measure_theory variables (G : Type*) [measurable_space G] variables [group G] [has_measurable_mul₂ G] variables (μ ν : measure G) [sigma_finite ν] [sigma_finite μ] {E : set G} /-- The map `(x, y) ↦ (x, xy)` as a `measurable_equiv`. This is a shear mapping. -/ @[to_additive "The map `(x, y) ↦ (x, x + y)` as a `measurable_equiv`. This is a shear mapping."] protected def measurable_equiv.shear_mul_right [has_measurable_inv G] : G × G ≃ᵐ G × G := { measurable_to_fun := measurable_fst.prod_mk measurable_mul, measurable_inv_fun := measurable_fst.prod_mk $ measurable_fst.inv.mul measurable_snd, .. equiv.prod_shear (equiv.refl _) equiv.mul_left } variables {G} namespace measure_theory open measure /-- A shear mapping preserves the measure `μ.prod ν`. This condition is part of the definition of a measurable group in [Halmos, §59]. There, the map in this lemma is called `S`. -/ @[to_additive map_prod_sum_eq /-" An additive shear mapping preserves the measure `μ.prod ν`. "-/] lemma map_prod_mul_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.1, z.1 * z.2)) (μ.prod ν) = μ.prod ν := ((measure_preserving.id μ).skew_product measurable_mul (filter.eventually_of_forall $ map_mul_left_eq_self ν)).map_eq /-- The function we are mapping along is `SR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_eq_swap /-" "-/] lemma map_prod_mul_eq_swap [is_mul_left_invariant μ] : map (λ z : G × G, (z.2, z.2 * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)) measurable_swap], exact map_prod_mul_eq ν μ end @[to_additive] lemma measurable_measure_mul_right (hE : measurable_set E) : measurable (λ x, μ ((λ y, y * x) ⁻¹' E)) := begin suffices : measurable (λ y, μ ((λ x, (x, y)) ⁻¹' ((λ z : G × G, ((1 : G), z.1 * z.2)) ⁻¹' (univ ×ˢ E)))), { convert this, ext1 x, congr' 1 with y : 1, simp }, apply measurable_measure_prod_mk_right, exact measurable_const.prod_mk (measurable_fst.mul measurable_snd) (measurable_set.univ.prod hE) end variables [has_measurable_inv G] /-- The function we are mapping along is `S⁻¹` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq`. -/ @[to_additive map_prod_neg_add_eq] lemma map_prod_inv_mul_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.1, z.1⁻¹ * z.2)) (μ.prod ν) = μ.prod ν := (measurable_equiv.shear_mul_right G).map_apply_eq_iff_map_symm_apply_eq.mp $ map_prod_mul_eq μ ν @[to_additive] lemma quasi_measure_preserving_div [is_mul_right_invariant μ] : quasi_measure_preserving (λ (p : G × G), p.1 / p.2) (μ.prod μ) μ := begin refine quasi_measure_preserving.prod_of_left measurable_div _, simp_rw [div_eq_mul_inv], apply eventually_of_forall, refine λ y, ⟨measurable_mul_const y⁻¹, (map_mul_right_eq_self μ y⁻¹).absolutely_continuous⟩ end variables [is_mul_left_invariant μ] /-- The function we are mapping along is `S⁻¹R` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_neg_add_eq_swap] lemma map_prod_inv_mul_eq_swap : map (λ z : G × G, (z.2, z.2⁻¹ * z.1)) (μ.prod ν) = ν.prod μ := begin rw [← prod_swap], simp_rw [map_map (measurable_snd.prod_mk $ measurable_snd.inv.mul measurable_fst) measurable_swap], exact map_prod_inv_mul_eq ν μ end /-- The function we are mapping along is `S⁻¹RSR` in [Halmos, §59], where `S` is the map in `map_prod_mul_eq` and `R` is `prod.swap`. -/ @[to_additive map_prod_add_neg_eq] lemma map_prod_mul_inv_eq [is_mul_left_invariant ν] : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod ν) = μ.prod ν := begin suffices : map ((λ z : G × G, (z.2, z.2⁻¹ * z.1)) ∘ (λ z : G × G, (z.2, z.2 * z.1))) (μ.prod ν) = μ.prod ν, { convert this, ext1 ⟨x, y⟩, simp }, simp_rw [← map_map (measurable_snd.prod_mk (measurable_snd.inv.mul measurable_fst)) (measurable_snd.prod_mk (measurable_snd.mul measurable_fst)), map_prod_mul_eq_swap μ ν, map_prod_inv_mul_eq_swap ν μ] end @[to_additive] lemma quasi_measure_preserving_inv : quasi_measure_preserving (has_inv.inv : G → G) μ μ := begin refine ⟨measurable_inv, absolutely_continuous.mk $ λ s hsm hμs, _⟩, rw [map_apply measurable_inv hsm, inv_preimage], have hf : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, suffices : map (λ z : G × G, (z.2 * z.1, z.1⁻¹)) (μ.prod μ) (s⁻¹ ×ˢ s⁻¹) = 0, { simpa only [map_prod_mul_inv_eq μ μ, prod_prod, mul_eq_zero, or_self] using this }, have hsm' : measurable_set (s⁻¹ ×ˢ s⁻¹) := hsm.inv.prod hsm.inv, simp_rw [map_apply hf hsm', prod_apply_symm (hf hsm'), preimage_preimage, mk_preimage_prod, inv_preimage, inv_inv, measure_mono_null (inter_subset_right _ _) hμs, lintegral_zero] end @[to_additive] lemma map_inv_absolutely_continuous : map has_inv.inv μ ≪ μ := (quasi_measure_preserving_inv μ).absolutely_continuous @[to_additive] lemma measure_inv_null : μ E⁻¹ = 0 ↔ μ E = 0 := begin refine ⟨λ hE, _, (quasi_measure_preserving_inv μ).preimage_null⟩, convert (quasi_measure_preserving_inv μ).preimage_null hE, exact (inv_inv _).symm end @[to_additive] lemma absolutely_continuous_map_inv : μ ≪ map has_inv.inv μ := begin refine absolutely_continuous.mk (λ s hs, _), simp_rw [map_apply measurable_inv hs, inv_preimage, measure_inv_null, imp_self] end @[to_additive] lemma lintegral_lintegral_mul_inv [is_mul_left_invariant ν] (f : G → G → ℝ≥0∞) (hf : ae_measurable (uncurry f) (μ.prod ν)) : ∫⁻ x, ∫⁻ y, f (y * x) x⁻¹ ∂ν ∂μ = ∫⁻ x, ∫⁻ y, f x y ∂ν ∂μ := begin have h : measurable (λ z : G × G, (z.2 * z.1, z.1⁻¹)) := (measurable_snd.mul measurable_fst).prod_mk measurable_fst.inv, have h2f : ae_measurable (uncurry $ λ x y, f (y * x) x⁻¹) (μ.prod ν), { apply hf.comp_measurable' h (map_prod_mul_inv_eq μ ν).absolutely_continuous }, simp_rw [lintegral_lintegral h2f, lintegral_lintegral hf], conv_rhs { rw [← map_prod_mul_inv_eq μ ν] }, symmetry, exact lintegral_map' (hf.mono' (map_prod_mul_inv_eq μ ν).absolutely_continuous) h.ae_measurable, end @[to_additive] lemma measure_mul_right_null (y : G) : μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ E = 0 := calc μ ((λ x, x * y) ⁻¹' E) = 0 ↔ μ ((λ x, y⁻¹ * x) ⁻¹' E⁻¹)⁻¹ = 0 : by simp_rw [← inv_preimage, preimage_preimage, mul_inv_rev, inv_inv] ... ↔ μ E = 0 : by simp only [measure_inv_null μ, measure_preimage_mul] @[to_additive] lemma measure_mul_right_ne_zero (h2E : μ E ≠ 0) (y : G) : μ ((λ x, x * y) ⁻¹' E) ≠ 0 := (not_iff_not_of_iff (measure_mul_right_null μ y)).mpr h2E @[to_additive] lemma quasi_measure_preserving_mul_right (g : G) : quasi_measure_preserving (λ h : G, h * g) μ μ := begin refine ⟨measurable_mul_const g, absolutely_continuous.mk $ λ s hs, _⟩, rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id, end @[to_additive] lemma map_mul_right_absolutely_continuous (g : G) : map (* g) μ ≪ μ := (quasi_measure_preserving_mul_right μ g).absolutely_continuous @[to_additive] lemma absolutely_continuous_map_mul_right (g : G) : μ ≪ map (* g) μ := begin refine absolutely_continuous.mk (λ s hs, _), rw [map_apply (measurable_mul_const g) hs, measure_mul_right_null], exact id end @[to_additive] lemma quasi_measure_preserving_div_left (g : G) : quasi_measure_preserving (λ h : G, g / h) μ μ := begin refine ⟨measurable_const.div measurable_id, _⟩, simp_rw [div_eq_mul_inv], rw [← map_map (measurable_const_mul g) measurable_inv], refine ((map_inv_absolutely_continuous μ).map $ measurable_const_mul g).trans _, rw [map_mul_left_eq_self], end @[to_additive] lemma map_div_left_absolutely_continuous (g : G) : map (λ h, g / h) μ ≪ μ := (quasi_measure_preserving_div_left μ g).absolutely_continuous @[to_additive] lemma absolutely_continuous_map_div_left (g : G) : μ ≪ map (λ h, g / h) μ := begin simp_rw [div_eq_mul_inv], rw [← map_map (measurable_const_mul g) measurable_inv], conv_lhs { rw [← map_mul_left_eq_self μ g] }, exact (absolutely_continuous_map_inv μ).map (measurable_const_mul g) end /-- This is the computation performed in the proof of [Halmos, §60 Th. A]. -/ @[to_additive] lemma measure_mul_lintegral_eq [is_mul_left_invariant ν] (Em : measurable_set E) (f : G → ℝ≥0∞) (hf : measurable f) : μ E * ∫⁻ y, f y ∂ν = ∫⁻ x, ν ((λ z, z * x) ⁻¹' E) * f (x⁻¹) ∂μ := begin rw [← set_lintegral_one, ← lintegral_indicator _ Em, ← lintegral_lintegral_mul (measurable_const.indicator Em).ae_measurable hf.ae_measurable, ← lintegral_lintegral_mul_inv μ ν], swap, { exact (((measurable_const.indicator Em).comp measurable_fst).mul (hf.comp measurable_snd)).ae_measurable }, have mE : ∀ x : G, measurable (λ y, ((λ z, z * x) ⁻¹' E).indicator (λ z, (1 : ℝ≥0∞)) y) := λ x, measurable_const.indicator (measurable_mul_const _ Em), have : ∀ x y, E.indicator (λ (z : G), (1 : ℝ≥0∞)) (y * x) = ((λ z, z * x) ⁻¹' E).indicator (λ (b : G), 1) y, { intros x y, symmetry, convert indicator_comp_right (λ y, y * x), ext1 z, refl }, simp_rw [this, lintegral_mul_const _ (mE _), lintegral_indicator _ (measurable_mul_const _ Em), set_lintegral_one], end /-- Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. -/ @[to_additive /-" Any two nonzero left-invariant measures are absolutely continuous w.r.t. each other. "-/] lemma absolutely_continuous_of_is_mul_left_invariant [is_mul_left_invariant ν] (hν : ν ≠ 0) : μ ≪ ν := begin refine absolutely_continuous.mk (λ E Em hνE, _), have h1 := measure_mul_lintegral_eq μ ν Em 1 measurable_one, simp_rw [pi.one_apply, lintegral_one, mul_one, (measure_mul_right_null ν _).mpr hνE, lintegral_zero, mul_eq_zero, measure_univ_eq_zero.not.mpr hν, or_false] at h1, exact h1 end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top [is_mul_left_invariant ν] (Em : measurable_set E) (hμE : μ E ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' E) < ∞ := begin refine ae_of_forall_measure_lt_top_ae_restrict' ν.inv _ _, intros A hA h2A h3A, simp only [ν.inv_apply] at h3A, apply ae_lt_top (measurable_measure_mul_right ν Em), have h1 := measure_mul_lintegral_eq μ ν Em (A⁻¹.indicator 1) (measurable_one.indicator hA.inv), rw [lintegral_indicator _ hA.inv] at h1, simp_rw [pi.one_apply, set_lintegral_one, ← image_inv, indicator_image inv_injective, image_inv, ← indicator_mul_right _ (λ x, ν ((λ y, y * x) ⁻¹' E)), function.comp, pi.one_apply, mul_one] at h1, rw [← lintegral_indicator _ hA, ← h1], exact ennreal.mul_ne_top hμE h3A.ne, end @[to_additive] lemma ae_measure_preimage_mul_right_lt_top_of_ne_zero [is_mul_left_invariant ν] (Em : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : ∀ᵐ x ∂μ, ν ((λ y, y * x) ⁻¹' E) < ∞ := begin refine (ae_measure_preimage_mul_right_lt_top ν ν Em h3E).filter_mono _, refine (absolutely_continuous_of_is_mul_left_invariant μ ν _).ae_le, refine mt _ h2E, intro hν, rw [hν, measure.coe_zero, pi.zero_apply] end /-- A technical lemma relating two different measures. This is basically [Halmos, §60 Th. A]. Note that if `f` is the characteristic function of a measurable set `F` this states that `μ F = c * μ E` for a constant `c` that does not depend on `μ`. Note: There is a gap in the last step of the proof in [Halmos]. In the last line, the equality `g(x⁻¹)ν(Ex⁻¹) = f(x)` holds if we can prove that `0 < ν(Ex⁻¹) < ∞`. The first inequality follows from §59, Th. D, but the second inequality is not justified. We prove this inequality for almost all `x` in `measure_theory.ae_measure_preimage_mul_right_lt_top_of_ne_zero`. -/ @[to_additive] lemma measure_lintegral_div_measure [is_mul_left_invariant ν] (Em : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) (f : G → ℝ≥0∞) (hf : measurable f) : μ E * ∫⁻ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' E) ∂ν = ∫⁻ x, f x ∂μ := begin set g := λ y, f y⁻¹ / ν ((λ x, x * y⁻¹) ⁻¹' E), have hg : measurable g := (hf.comp measurable_inv).div ((measurable_measure_mul_right ν Em).comp measurable_inv), simp_rw [measure_mul_lintegral_eq μ ν Em g hg, g, inv_inv], refine lintegral_congr_ae _, refine (ae_measure_preimage_mul_right_lt_top_of_ne_zero μ ν Em h2E h3E).mono (λ x hx , _), simp_rw [ennreal.mul_div_cancel' (measure_mul_right_ne_zero ν h2E _) hx.ne] end @[to_additive] lemma measure_mul_measure_eq [is_mul_left_invariant ν] {E F : set G} (hE : measurable_set E) (hF : measurable_set F) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : μ E * ν F = ν E * μ F := begin have h1 := measure_lintegral_div_measure ν ν hE h2E h3E (F.indicator (λ x, 1)) (measurable_const.indicator hF), have h2 := measure_lintegral_div_measure μ ν hE h2E h3E (F.indicator (λ x, 1)) (measurable_const.indicator hF), rw [lintegral_indicator _ hF, set_lintegral_one] at h1 h2, rw [← h1, mul_left_comm, h2], end /-- Left invariant Borel measures on a measurable group are unique (up to a scalar). -/ @[to_additive /-" Left invariant Borel measures on an additive measurable group are unique (up to a scalar). "-/] lemma measure_eq_div_smul [is_mul_left_invariant ν] (hE : measurable_set E) (h2E : ν E ≠ 0) (h3E : ν E ≠ ∞) : μ = (μ E / ν E) • ν := begin ext1 F hF, rw [smul_apply, smul_eq_mul, mul_comm, ← mul_div_assoc, mul_comm, measure_mul_measure_eq μ ν hE hF h2E h3E, mul_div_assoc, ennreal.mul_div_cancel' h2E h3E] end end measure_theory
b5411b4667e5fc851c9a1e5c3a92a519d404d364
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/stage0/src/Init/Data/Option/Basic.lean
5a9c67694b6a216b5f5ce108ad6c6430c999289f
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
3,348
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Core import Init.Control.Monad import Init.Control.Alternative import Init.Coe open Decidable universes u v namespace Option def toMonad {m : Type → Type} [Monad m] [Alternative m] {A} : Option A → m A | none => failure | some a => pure a @[macroInline] def getD {α : Type u} : Option α → α → α | some x, _ => x | none, e => e @[inline] def toBool {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isSome {α : Type u} : Option α → Bool | some _ => true | none => false @[inline] def isNone {α : Type u} : Option α → Bool | some _ => false | none => true @[inline] protected def bind {α : Type u} {β : Type v} : Option α → (α → Option β) → Option β | none, b => none | some a, b => b a @[inline] protected def map {α β} (f : α → β) (o : Option α) : Option β := Option.bind o (some ∘ f) theorem mapId {α} : (Option.map id : Option α → Option α) = id := funext (fun o => match o with | none => rfl | some x => rfl) instance : Monad Option := {pure := @some, bind := @Option.bind, map := @Option.map} @[inline] protected def filter {α} (p : α → Bool) : Option α → Option α | some a => if p a then some a else none | none => none @[inline] protected def all {α} (p : α → Bool) : Option α → Bool | some a => p a | none => true @[inline] protected def any {α} (p : α → Bool) : Option α → Bool | some a => p a | none => false @[macroInline] protected def orelse {α : Type u} : Option α → Option α → Option α | some a, _ => some a | none, b => b /- Remark: when using the polymorphic notation `a <|> b` is not a `[macroInline]`. Thus, `a <|> b` will make `Option.orelse` to behave like it was marked as `[inline]`. -/ instance : Alternative Option := { failure := @none, orelse := @Option.orelse, ..Option.Monad } @[inline] protected def lt {α : Type u} (r : α → α → Prop) : Option α → Option α → Prop | none, some x => True | some x, some y => r x y | _, _ => False instance decidableRelLt {α : Type u} (r : α → α → Prop) [s : DecidableRel r] : DecidableRel (Option.lt r) | none, some y => isTrue trivial | some x, some y => s x y | some x, none => isFalse notFalse | none, none => isFalse notFalse end Option instance (α : Type u) : Inhabited (Option α) := ⟨none⟩ instance {α : Type u} [DecidableEq α] : DecidableEq (Option α) := fun a b => match a, b with | none, none => isTrue rfl | none, (some v₂) => isFalse (fun h => Option.noConfusion h) | (some v₁), none => isFalse (fun h => Option.noConfusion h) | (some v₁), (some v₂) => match decEq v₁ v₂ with | (isTrue e) => isTrue (congrArg (@some α) e) | (isFalse n) => isFalse (fun h => Option.noConfusion h (fun e => absurd e n)) instance {α : Type u} [HasBeq α] : HasBeq (Option α) := ⟨fun a b => match a, b with | none, none => true | none, (some v₂) => false | (some v₁), none => false | (some v₁), (some v₂) => v₁ == v₂⟩ instance {α : Type u} [HasLess α] : HasLess (Option α) := ⟨Option.lt HasLess.Less⟩
01c4d2952907afc202e77945ef3fbea6b7356cba
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/polynomial/bernstein.lean
50080cf41991622b9fe3db71888f957208c7d76e
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,835
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 data.polynomial.derivative import data.polynomial.algebra_map import data.mv_polynomial.pderiv import data.nat.choose.sum import linear_algebra.basis import ring_theory.polynomial.pochhammer import tactic.omega /-! # Bernstein polynomials The definition of the Bernstein polynomials ``` bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : polynomial R := (choose n ν) * X^ν * (1 - X)^(n - ν) ``` and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`. We prove the basic identities * `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1` * `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X` * `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2` ## Future work The fact that the Bernstein approximations of a continuous function `f` on `[0,1]` converge uniformly. This will give a constructive proof of Weierstrass' theorem that polynomials are dense in `C([0,1], ℝ)`. -/ noncomputable theory open nat (choose) open polynomial (X) variables (R : Type*) [comm_ring R] /-- `bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`. Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring. -/ def bernstein_polynomial (n ν : ℕ) : polynomial R := choose n ν * X^ν * (1 - X)^(n - ν) example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 := begin norm_num [bernstein_polynomial, choose], ring, end namespace bernstein_polynomial lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 := by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h] section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map (f : R →+* S) (n ν : ℕ) : (bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν := by simp [bernstein_polynomial] end lemma flip (n ν : ℕ) (h : ν ≤ n) : (bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) := begin dsimp [bernstein_polynomial], simp [h, nat.sub_sub_assoc, mul_right_comm], end lemma flip' (n ν : ℕ) (h : ν ≤ n) : bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) := begin rw [←flip _ _ _ h, polynomial.comp_assoc], simp, end lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { simp [zero_pow (nat.pos_of_ne_zero h)], }, end lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { by_cases w : 0 < n - ν, { simp [zero_pow w], }, { simp [(show n < ν, by omega), nat.choose_eq_zero_of_lt], }, }, end. lemma derivative_succ_aux (n ν : ℕ) : (bernstein_polynomial R (n+1) (ν+1)).derivative = (n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) := begin dsimp [bernstein_polynomial], suffices : ↑((n + 1).choose (ν + 1)) * ((↑ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) = (↑n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) - ↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))), { simpa [polynomial.derivative_pow, ←sub_eq_add_neg], }, conv_rhs { rw mul_sub, }, -- We'll prove the two terms match up separately. refine congr (congr_arg has_sub.sub _) _, { simp only [←mul_assoc], refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl, -- Now it's just about binomial coefficients exact_mod_cast congr_arg (λ m : ℕ, (m : polynomial R)) (nat.succ_mul_choose_eq n ν).symm, }, { rw nat.sub_sub, rw [←mul_assoc,←mul_assoc], congr' 1, rw mul_comm , rw [←mul_assoc,←mul_assoc], congr' 1, norm_cast, congr' 1, convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1, { convert mul_comm _ _ using 2, simp, }, { apply mul_comm, }, }, end lemma derivative_succ (n ν : ℕ) : (bernstein_polynomial R n (ν+1)).derivative = n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) := begin cases n, { simp [bernstein_polynomial], }, { apply derivative_succ_aux, } end lemma derivative_zero (n : ℕ) : (bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 := begin dsimp [bernstein_polynomial], simp [polynomial.derivative_pow], end lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 := begin cases ν, { rintro ⟨⟩, }, { intro w, replace w := nat.lt_succ_iff.mp w, revert w, induction k with k ih generalizing n ν, { simp [eval_at_0], }, { simp only [derivative_succ, int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat, mul_eq_zero, function.comp_app, function.iterate_succ, polynomial.iterate_derivative_sub, polynomial.iterate_derivative_cast_nat_mul, polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub], intro h, apply mul_eq_zero_of_right, rw ih, simp only [sub_zero], convert @ih (n-1) (ν-1) _, { omega, }, { omega, }, { exact le_of_lt h, }, }, }, end @[simp] lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 := iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν) open polynomial /-- A Pochhammer identity that is useful for `bernstein_polynomial.iterate_derivative_at_0_aux₂`. -/ lemma iterate_derivative_at_0_aux₁ (n k : ℕ) : k * polynomial.eval (k-n) (pochhammer ℕ n) = (k-n) * polynomial.eval (k-n+1) (pochhammer ℕ n) := begin have p := congr_arg (eval (k-n)) ((pochhammer_succ_right ℕ n).symm.trans (pochhammer_succ_left ℕ n)), simp only [nat.cast_id, eval_X, eval_one, eval_mul, eval_nat_cast, eval_add, eval_comp] at p, rw [mul_comm] at p, rw ←p, by_cases h : n ≤ k, { rw nat.sub_add_cancel h, }, { simp only [not_le] at h, simp only [mul_eq_mul_right_iff], right, rw nat.sub_eq_zero_of_le (le_of_lt h), simp only [pochhammer_eval_zero, ite_eq_right_iff], rintro rfl, cases h, }, end lemma iterate_derivative_at_0_aux₂ (n k : ℕ) : (↑k) * polynomial.eval ↑(k-n) (pochhammer R n) = ↑(k-n) * polynomial.eval (↑(k-n+1)) (pochhammer R n) := by simpa using congr_arg (algebra_map ℕ R) (iterate_derivative_at_0_aux₁ n k) @[simp] lemma iterate_derivative_at_0 (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 = (pochhammer R ν).eval (n - (ν - 1) : ℕ) := begin by_cases h : ν ≤ n, { induction ν with ν ih generalizing n h, { simp [eval_at_0], }, { simp only [nat.succ_eq_add_one] at h, have h' : ν ≤ n-1 := nat.le_sub_right_of_add_le h, have w₁ : ((n - ν : ℕ) + 1 : R) = (n - ν + 1 : ℕ), { push_cast, }, simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero, nat.succ_sub_succ_eq_sub, nat.sub_zero, sub_zero, iterate_derivative_sub, iterate_derivative_cast_nat_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast, function.comp_app, function.iterate_succ, pochhammer_succ_left], rw [w₁], by_cases h'' : ν = 0, { subst h'', simp, }, { have w₂ : n - 1 - (ν - 1) = n - ν, { rw [nat.sub_sub], rw nat.add_sub_cancel', omega, }, simpa [w₂] using (iterate_derivative_at_0_aux₂ R ν n), }, }, }, { simp only [not_le] at h, have w₁ : n - (ν - 1) = 0, { omega, }, have w₂ : ν ≠ 0, { omega, }, rw [w₁, eq_zero_of_lt R h], simp [w₂], } end lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 := begin simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def, nat.cast_eq_zero], simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, by_cases h : ν = 0, { subst h, simp, }, { apply pochhammer_pos, omega, }, end /-! Rather than redoing the work of evaluating the derivatives at 1, we use the symmetry of the Bernstein polynomials. -/ lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 := begin intro w, rw flip' _ _ _ (show ν ≤ n, by omega), simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w], end @[simp] lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 = (-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) := begin rw flip' _ _ _ h, simp [polynomial.eval_comp, h], by_cases h' : n = ν, { subst h', simp, }, { replace h : ν < n, { omega, }, congr, norm_cast, congr, omega, }, end lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 := begin simp only [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def, int.coe_nat_eq_zero, neg_one_pow_mul_eq_zero_iff, nat.cast_eq_zero], rw ←nat.cast_succ, simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, apply pochhammer_pos, exact nat.succ_pos ν, end open submodule lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1): linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) := begin induction k with k ih, { apply linear_independent_empty_type, rintro ⟨⟨n, ⟨⟩⟩⟩, }, { apply linear_independent_fin_succ'.mpr, fsplit, { exact ih (le_of_lt h), }, { -- The actual work! -- We show that the (n-k)-th derivative at 1 doesn't vanish, -- but vanishes for everything in the span. clear ih, simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h, simp only [fin.coe_last, fin.init_def], dsimp, apply not_mem_span_of_apply_not_mem_span_image ((polynomial.derivative_lhom ℚ)^(n-k)), simp only [not_exists, not_and, submodule.mem_map, submodule.span_image], intros p m, apply_fun (polynomial.eval (1 : ℚ)), simp only [polynomial.derivative_lhom_coe, linear_map.pow_apply], -- The right hand side is nonzero, -- so it will suffice to show the left hand side is always zero. suffices : (polynomial.derivative^[n-k] p).eval 1 = 0, { rw [this], exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, }, apply span_induction m, { simp, rintro ⟨a, w⟩, simp only [fin.coe_mk], rw [iterate_derivative_at_1_eq_zero_of_lt ℚ _ (show n - k < n - a, by omega)], }, { simp, }, { intros x y hx hy, simp [hx, hy], }, { intros a x h, simp [h], }, }, }, end /-- The Bernstein polynomials are linearly independent. We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k` are linearly independent. The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1, annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`. -/ lemma linear_independent (n : ℕ) : linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) := linear_independent_aux n (n+1) (le_refl _) lemma sum (n : ℕ) : (finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1 := begin -- We calculate `(x + (1-x))^n` in two different ways. conv { congr, congr, skip, funext, dsimp [bernstein_polynomial], rw [mul_assoc, mul_comm], }, rw ←add_pow, simp, end open polynomial open mv_polynomial lemma sum_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X := begin -- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X = k • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, rw [pderiv_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e, nat_cast_mul], }, exact h, end lemma sum_mul_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2 := begin -- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X^2) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X^2 = (k * (k-1)) • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { rcases k with (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, simp only [pderiv_one, pderiv_mul, pderiv_pow, pderiv_nat_cast, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e, nat_cast_mul, smul_smul], }, exact h, end end bernstein_polynomial
46dfc3830a4864c548e31f23141d0b2b3e757d36
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/compiler/lazylist.lean
e927cd684c87144cedadee3a6bbde992aa99a501
[ "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,908
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ universes u v w inductive LazyList (α : Type u) | nil : LazyList α | cons (hd : α) (tl : LazyList α) : LazyList α | delayed (t : Thunk $ LazyList α) : LazyList α @[extern c inline "#2"] def List.toLazy {α : Type u} : List α → LazyList α | [] => LazyList.nil | h::t => LazyList.cons h (toLazy t) namespace LazyList variable {α : Type u} {β : Type v} {δ : Type w} instance : Inhabited (LazyList α) := ⟨nil⟩ @[inline] def pure : α → LazyList α | a => cons a nil partial def isEmpty : LazyList α → Bool | nil => true | cons _ _ => false | delayed as => isEmpty as.get partial def toList : LazyList α → List α | nil => [] | cons a as => a :: toList as | delayed as => toList as.get partial def head [Inhabited α] : LazyList α → α | nil => arbitrary | cons a as => a | delayed as => head as.get partial def tail : LazyList α → LazyList α | nil => nil | cons a as => as | delayed as => tail as.get partial def append : LazyList α → LazyList α → LazyList α | nil, bs => bs | cons a as, bs => delayed (cons a (append as bs)) | delayed as, bs => delayed (append as.get bs) instance : Append (LazyList α) := ⟨LazyList.append⟩ partial def interleave : LazyList α → LazyList α → LazyList α | nil, bs => bs | cons a as, bs => delayed (cons a (interleave bs as)) | delayed as, bs => delayed (interleave as.get bs) partial def map (f : α → β) : LazyList α → LazyList β | nil => nil | cons a as => delayed (cons (f a) (map f as)) | delayed as => delayed (map f as.get) partial def map₂ (f : α → β → δ) : LazyList α → LazyList β → LazyList δ | nil, _ => nil | _, nil => nil | cons a as, cons b bs => delayed (cons (f a b) (map₂ f as bs)) | delayed as, bs => delayed (map₂ f as.get bs) | as, delayed bs => delayed (map₂ f as bs.get) @[inline] def zip : LazyList α → LazyList β → LazyList (α × β) := map₂ Prod.mk partial def join : LazyList (LazyList α) → LazyList α | nil => nil | cons a as => delayed (append a (join as)) | delayed as => delayed (join as.get) @[inline] partial def bind (x : LazyList α) (f : α → LazyList β) : LazyList β := join (x.map f) instance isMonad : Monad LazyList := { pure := @LazyList.pure, bind := @LazyList.bind, map := @LazyList.map } instance : Alternative LazyList := { LazyList.isMonad with failure := nil, orElse := LazyList.append } partial def approx : Nat → LazyList α → List α | 0, as => [] | _, nil => [] | i+1, cons a as => a :: approx i as | i+1, delayed as => approx (i+1) as.get partial def iterate (f : α → α) : α → LazyList α | x => cons x (delayed (iterate f (f x))) partial def iterate₂ (f : α → α → α) : α → α → LazyList α | x, y => cons x (delayed (iterate₂ f y (f x y))) partial def filter (p : α → Bool) : LazyList α → LazyList α | nil => nil | cons a as => delayed (if p a then cons a (filter p as) else filter p as) | delayed as => delayed (filter p as.get) end LazyList def fib : LazyList Nat := LazyList.iterate₂ (· + ·) 0 1 def iota (i : Nat := 0) : LazyList Nat := LazyList.iterate Nat.succ i def tst : LazyList String := do let x ← [1, 2, 3].toLazy; let y ← [2, 3, 4].toLazy; guard (x + y > 5); pure s!"{x} + {y} = {x+y}" def main : IO Unit := do let n := 40; IO.println tst.isEmpty; IO.println tst.head; IO.println <| fib.interleave (iota.map (· + 100)) |>.approx n; IO.println <| iota.map (· + 10) |>.filter (· % 2 == 0) |>.approx n
d900b2245e86c96111d19dbefea211482150d878
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/analytic/basic.lean
66fca7e3546b959e5657e79715cbd0d04997bfbe
[ "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
51,330
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, Yury Kudryashov -/ import analysis.calculus.formal_multilinear_series import data.equiv.fin /-! # Analytic functions A function is analytic in one dimension around `0` if it can be written as a converging power series `Σ pₙ zⁿ`. This definition can be extended to any dimension (even in infinite dimension) by requiring that `pₙ` is a continuous `n`-multilinear map. In general, `pₙ` is not unique (in two dimensions, taking `p₂ (x, y) (x', y') = x y'` or `y x'` gives the same map when applied to a vector `(x, y) (x, y)`). A way to guarantee uniqueness is to take a symmetric `pₙ`, but this is not always possible in nonzero characteristic (in characteristic 2, the previous example has no symmetric representative). Therefore, we do not insist on symmetry or uniqueness in the definition, and we only require the existence of a converging series. The general framework is important to say that the exponential map on bounded operators on a Banach space is analytic, as well as the inverse on invertible operators. ## Main definitions Let `p` be a formal multilinear series from `E` to `F`, i.e., `p n` is a multilinear map on `E^n` for `n : ℕ`. * `p.radius`: the largest `r : ℝ≥0∞` such that `∥p n∥ * r^n` grows subexponentially, defined as a liminf. * `p.le_radius_of_bound`, `p.le_radius_of_bound_nnreal`, `p.le_radius_of_is_O`: if `∥p n∥ * r ^ n` is bounded above, then `r ≤ p.radius`; * `p.is_o_of_lt_radius`, `p.norm_mul_pow_le_mul_pow_of_lt_radius`, `p.is_o_one_of_lt_radius`, `p.norm_mul_pow_le_of_lt_radius`, `p.nnnorm_mul_pow_le_of_lt_radius`: if `r < p.radius`, then `∥p n∥ * r ^ n` tends to zero exponentially; * `p.lt_radius_of_is_O`: if `r ≠ 0` and `∥p n∥ * r ^ n = O(a ^ n)` for some `-1 < a < 1`, then `r < p.radius`; * `p.partial_sum n x`: the sum `∑_{i = 0}^{n-1} pᵢ xⁱ`. * `p.sum x`: the sum `∑'_{i = 0}^{∞} pᵢ xⁱ`. Additionally, let `f` be a function from `E` to `F`. * `has_fpower_series_on_ball f p x r`: on the ball of center `x` with radius `r`, `f (x + y) = ∑'_n pₙ yⁿ`. * `has_fpower_series_at f p x`: on some ball of center `x` with positive radius, holds `has_fpower_series_on_ball f p x r`. * `analytic_at 𝕜 f x`: there exists a power series `p` such that holds `has_fpower_series_at f p x`. We develop the basic properties of these notions, notably: * If a function admits a power series, it is continuous (see `has_fpower_series_on_ball.continuous_on` and `has_fpower_series_at.continuous_at` and `analytic_at.continuous_at`). * In a complete space, the sum of a formal power series with positive radius is well defined on the disk of convergence, see `formal_multilinear_series.has_fpower_series_on_ball`. * If a function admits a power series in a ball, then it is analytic at any point `y` of this ball, and the power series there can be expressed in terms of the initial power series `p` as `p.change_origin y`. See `has_fpower_series_on_ball.change_origin`. It follows in particular that the set of points at which a given function is analytic is open, see `is_open_analytic_at`. ## Implementation details We only introduce the radius of convergence of a power series, as `p.radius`. For a power series in finitely many dimensions, there is a finer (directional, coordinate-dependent) notion, describing the polydisk of convergence. This notion is more specific, and not necessary to build the general theory. We do not define it here. -/ noncomputable theory variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] {G : Type*} [normed_group G] [normed_space 𝕜 G] open_locale topological_space classical big_operators nnreal filter ennreal open set filter asymptotics /-! ### The radius of a formal multilinear series -/ namespace formal_multilinear_series variables (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} /-- The radius of a formal multilinear series is the largest `r` such that the sum `Σ ∥pₙ∥ ∥y∥ⁿ` converges for all `∥y∥ < r`. This implies that `Σ pₙ yⁿ` converges for all `∥y∥ < r`, but these definitions are *not* equivalent in general. -/ def radius (p : formal_multilinear_series 𝕜 E F) : ℝ≥0∞ := ⨆ (r : ℝ≥0) (C : ℝ) (hr : ∀ n, ∥p n∥ * r ^ n ≤ C), (r : ℝ≥0∞) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound (C : ℝ) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := le_supr_of_le r $ le_supr_of_le C $ (le_supr (λ _, (r : ℝ≥0∞)) h) /-- If `∥pₙ∥ rⁿ` is bounded in `n`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_bound_nnreal (C : ℝ≥0) {r : ℝ≥0} (h : ∀ (n : ℕ), ∥p n∥₊ * r^n ≤ C) : (r : ℝ≥0∞) ≤ p.radius := p.le_radius_of_bound C $ λ n, by exact_mod_cast (h n) /-- If `∥pₙ∥ rⁿ = O(1)`, as `n → ∞`, then the radius of `p` is at least `r`. -/ lemma le_radius_of_is_O (h : is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : ↑r ≤ p.radius := exists.elim (is_O_one_nat_at_top_iff.1 h) $ λ C hC, p.le_radius_of_bound C $ λ n, (le_abs_self _).trans (hC n) lemma le_radius_of_eventually_le (C) (h : ∀ᶠ n in at_top, ∥p n∥ * r ^ n ≤ C) : ↑r ≤ p.radius := p.le_radius_of_is_O $ is_O.of_bound C $ h.mono $ λ n hn, by simpa lemma le_radius_of_summable_nnnorm (h : summable (λ n, ∥p n∥₊ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_bound_nnreal (∑' n, ∥p n∥₊ * r ^ n) $ λ n, le_tsum' h _ lemma le_radius_of_summable (h : summable (λ n, ∥p n∥ * r ^ n)) : ↑r ≤ p.radius := p.le_radius_of_summable_nnnorm $ by { simp only [← coe_nnnorm] at h, exact_mod_cast h } lemma radius_eq_top_of_forall_nnreal_is_O (h : ∀ r : ℝ≥0, is_O (λ n, ∥p n∥ * r^n) (λ n, (1 : ℝ)) at_top) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le $ λ r, p.le_radius_of_is_O (h r) lemma radius_eq_top_of_eventually_eq_zero (h : ∀ᶠ n in at_top, p n = 0) : p.radius = ∞ := p.radius_eq_top_of_forall_nnreal_is_O $ λ r, (is_O_zero _ _).congr' (h.mono $ λ n hn, by simp [hn]) eventually_eq.rfl lemma radius_eq_top_of_forall_image_add_eq_zero (n : ℕ) (hn : ∀ m, p (m + n) = 0) : p.radius = ∞ := p.radius_eq_top_of_eventually_eq_zero $ mem_at_top_sets.2 ⟨n, λ k hk, nat.sub_add_cancel hk ▸ hn _⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1`, `∥p n∥ rⁿ = o(aⁿ)`. -/ lemma is_o_of_lt_radius (h : ↑r < p.radius) : ∃ a ∈ Ioo (0 : ℝ) 1, is_o (λ n, ∥p n∥ * r ^ n) (pow a) at_top := begin rw (tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 4, simp only [radius, lt_supr_iff] at h, rcases h with ⟨t, C, hC, rt⟩, rw [ennreal.coe_lt_coe, ← nnreal.coe_lt_coe] at rt, have : 0 < (t : ℝ), from r.coe_nonneg.trans_lt rt, rw [← div_lt_one this] at rt, refine ⟨_, rt, C, or.inr zero_lt_one, λ n, _⟩, calc abs (∥p n∥ * r ^ n) = (∥p n∥ * t ^ n) * (r / t) ^ n : by field_simp [mul_right_comm, abs_mul, this.ne'] ... ≤ C * (r / t) ^ n : mul_le_mul_of_nonneg_right (hC n) (pow_nonneg (div_nonneg r.2 t.2) _) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ = o(1)`. -/ lemma is_o_one_of_lt_radius (h : ↑r < p.radius) : is_o (λ n, ∥p n∥ * r ^ n) (λ _, 1 : ℕ → ℝ) at_top := let ⟨a, ha, hp⟩ := p.is_o_of_lt_radius h in hp.trans $ (is_o_pow_pow_of_lt_left ha.1.le ha.2).congr (λ n, rfl) one_pow /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` tends to zero exponentially: for some `0 < a < 1` and `C > 0`, `∥p n∥ * r ^ n ≤ C * a ^ n`. -/ lemma norm_mul_pow_le_mul_pow_of_lt_radius (h : ↑r < p.radius) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r^n ≤ C * a^n := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 1 5).mp (p.is_o_of_lt_radius h) with ⟨a, ha, C, hC, H⟩, exact ⟨a, ha, C, hC, λ n, (le_abs_self _).trans (H n)⟩ end /-- If `r ≠ 0` and `∥pₙ∥ rⁿ = O(aⁿ)` for some `-1 < a < 1`, then `r < p.radius`. -/ lemma lt_radius_of_is_O (h₀ : r ≠ 0) {a : ℝ} (ha : a ∈ Ioo (-1 : ℝ) 1) (hp : is_O (λ n, ∥p n∥ * r ^ n) (pow a) at_top) : ↑r < p.radius := begin rcases ((tfae_exists_lt_is_o_pow (λ n, ∥p n∥ * r ^ n) 1).out 2 5).mp ⟨a, ha, hp⟩ with ⟨a, ha, C, hC, hp⟩, rw [← pos_iff_ne_zero, ← nnreal.coe_pos] at h₀, lift a to ℝ≥0 using ha.1.le, have : (r : ℝ) < r / a := by simpa only [div_one] using (div_lt_div_left h₀ zero_lt_one ha.1).2 ha.2, norm_cast at this, rw [← ennreal.coe_lt_coe] at this, refine this.trans_le (p.le_radius_of_bound C $ λ n, _), rw [nnreal.coe_div, div_pow, ← mul_div_assoc, div_le_iff (pow_pos ha.1 n)], exact (le_abs_self _).trans (hp n) end /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ * r^n ≤ C := let ⟨a, ha, C, hC, h⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h in ⟨C, hC, λ n, (h n).trans $ mul_le_of_le_one_right hC.lt.le (pow_le_one _ ha.1.le ha.2.le)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma norm_le_div_pow_of_pos_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h0 : 0 < r) (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥ ≤ C / r ^ n := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨C, hC, λ n, iff.mpr (le_div_iff (pow_pos h0 _)) (hp n)⟩ /-- For `r` strictly smaller than the radius of `p`, then `∥pₙ∥ rⁿ` is bounded. -/ lemma nnnorm_mul_pow_le_of_lt_radius (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : (r : ℝ≥0∞) < p.radius) : ∃ C > 0, ∀ n, ∥p n∥₊ * r^n ≤ C := let ⟨C, hC, hp⟩ := p.norm_mul_pow_le_of_lt_radius h in ⟨⟨C, hC.lt.le⟩, hC, by exact_mod_cast hp⟩ lemma le_radius_of_tendsto (p : formal_multilinear_series 𝕜 E F) {l : ℝ} (h : tendsto (λ n, ∥p n∥ * r^n) at_top (𝓝 l)) : ↑r ≤ p.radius := p.le_radius_of_is_O (is_O_one_of_tendsto _ h) lemma le_radius_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : summable (λ n, ∥p n∥ * r^n)) : ↑r ≤ p.radius := p.le_radius_of_tendsto hs.tendsto_at_top_zero lemma not_summable_norm_of_radius_lt_nnnorm (p : formal_multilinear_series 𝕜 E F) {x : E} (h : p.radius < ∥x∥₊) : ¬ summable (λ n, ∥p n∥ * ∥x∥^n) := λ hs, not_le_of_lt h (p.le_radius_of_summable_norm hs) lemma summable_norm_of_lt_radius (p : formal_multilinear_series 𝕜 E F) (h : ↑r < p.radius) : summable (λ n, ∥p n∥ * r^n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) end lemma summable_of_nnnorm_lt_radius (p : formal_multilinear_series 𝕜 E F) [complete_space F] {x : E} (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : summable (λ n, p n (λ i, x)) := begin refine summable_of_norm_bounded (λ n, ∥p n∥ * ∥x∥₊^n) (p.summable_norm_of_lt_radius h) _, intros n, calc ∥(p n) (λ (i : fin n), x)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥x∥) : continuous_multilinear_map.le_op_norm _ _ ... = ∥p n∥ * ∥x∥₊^n : by simp end lemma radius_eq_top_of_summable_norm (p : formal_multilinear_series 𝕜 E F) (hs : ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n)) : p.radius = ∞ := ennreal.eq_top_of_forall_nnreal_le (λ r, p.le_radius_of_summable_norm (hs r)) lemma radius_eq_top_iff_summable_norm (p : formal_multilinear_series 𝕜 E F) : p.radius = ∞ ↔ ∀ r : ℝ≥0, summable (λ n, ∥p n∥ * r^n) := begin split, { intros h r, obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius (show (r:ℝ≥0∞) < p.radius, from h.symm ▸ ennreal.coe_lt_top), refine (summable_of_norm_bounded (λ n, (C : ℝ) * a ^ n) ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _) (λ n, _)), specialize hp n, rwa real.norm_of_nonneg (mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg n)) }, { exact p.radius_eq_top_of_summable_norm } end /-- If the radius of `p` is positive, then `∥pₙ∥` grows at most geometrically. -/ lemma le_mul_pow_of_radius_pos (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : ∃ C r (hC : 0 < C) (hr : 0 < r), ∀ n, ∥p n∥ ≤ C * r ^ n := begin rcases ennreal.lt_iff_exists_nnreal_btwn.1 h with ⟨r, r0, rlt⟩, have rpos : 0 < (r : ℝ), by simp [ennreal.coe_pos.1 r0], rcases norm_le_div_pow_of_pos_of_lt_radius p rpos rlt with ⟨C, Cpos, hCp⟩, refine ⟨C, r ⁻¹, Cpos, by simp [rpos], λ n, _⟩, convert hCp n, exact inv_pow' _ _, end /-- The radius of the sum of two formal series is at least the minimum of their two radii. -/ lemma min_radius_le_radius_add (p q : formal_multilinear_series 𝕜 E F) : min p.radius q.radius ≤ (p + q).radius := begin refine ennreal.le_of_forall_nnreal_lt (λ r hr, _), rw lt_min_iff at hr, have := ((p.is_o_one_of_lt_radius hr.1).add (q.is_o_one_of_lt_radius hr.2)).is_O, refine (p + q).le_radius_of_is_O ((is_O_of_le _ $ λ n, _).trans this), rw [← add_mul, normed_field.norm_mul, normed_field.norm_mul, norm_norm], exact mul_le_mul_of_nonneg_right ((norm_add_le _ _).trans (le_abs_self _)) (norm_nonneg _) end @[simp] lemma radius_neg (p : formal_multilinear_series 𝕜 E F) : (-p).radius = p.radius := by simp [radius] /-- Given a formal multilinear series `p` and a vector `x`, then `p.sum x` is the sum `Σ pₙ xⁿ`. A priori, it only behaves well when `∥x∥ < p.radius`. -/ protected def sum (p : formal_multilinear_series 𝕜 E F) (x : E) : F := ∑' n : ℕ , p n (λ i, x) /-- Given a formal multilinear series `p` and a vector `x`, then `p.partial_sum n x` is the sum `Σ pₖ xᵏ` for `k ∈ {0,..., n-1}`. -/ def partial_sum (p : formal_multilinear_series 𝕜 E F) (n : ℕ) (x : E) : F := ∑ k in finset.range n, p k (λ(i : fin k), x) /-- The partial sums of a formal multilinear series are continuous. -/ lemma partial_sum_continuous (p : formal_multilinear_series 𝕜 E F) (n : ℕ) : continuous (p.partial_sum n) := by continuity end formal_multilinear_series /-! ### Expanding a function as a power series -/ section variables {f g : E → F} {p pf pg : formal_multilinear_series 𝕜 E F} {x : E} {r r' : ℝ≥0∞} /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series on the ball of radius `r > 0` around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `∥y∥ < r`. -/ structure has_fpower_series_on_ball (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) (r : ℝ≥0∞) : Prop := (r_le : r ≤ p.radius) (r_pos : 0 < r) (has_sum : ∀ {y}, y ∈ emetric.ball (0 : E) r → has_sum (λn:ℕ, p n (λ(i : fin n), y)) (f (x + y))) /-- Given a function `f : E → F` and a formal multilinear series `p`, we say that `f` has `p` as a power series around `x` if `f (x + y) = ∑' pₙ yⁿ` for all `y` in a neighborhood of `0`. -/ def has_fpower_series_at (f : E → F) (p : formal_multilinear_series 𝕜 E F) (x : E) := ∃ r, has_fpower_series_on_ball f p x r variable (𝕜) /-- Given a function `f : E → F`, we say that `f` is analytic at `x` if it admits a convergent power series expansion around `x`. -/ def analytic_at (f : E → F) (x : E) := ∃ (p : formal_multilinear_series 𝕜 E F), has_fpower_series_at f p x variable {𝕜} lemma has_fpower_series_on_ball.has_fpower_series_at (hf : has_fpower_series_on_ball f p x r) : has_fpower_series_at f p x := ⟨r, hf⟩ lemma has_fpower_series_at.analytic_at (hf : has_fpower_series_at f p x) : analytic_at 𝕜 f x := ⟨p, hf⟩ lemma has_fpower_series_on_ball.analytic_at (hf : has_fpower_series_on_ball f p x r) : analytic_at 𝕜 f x := hf.has_fpower_series_at.analytic_at lemma has_fpower_series_on_ball.has_sum_sub (hf : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball x r) : has_sum (λ n : ℕ, p n (λ i, y - x)) (f y) := have y - x ∈ emetric.ball (0 : E) r, by simpa [edist_eq_coe_nnnorm_sub] using hy, by simpa only [add_sub_cancel'_right] using hf.has_sum this lemma has_fpower_series_on_ball.radius_pos (hf : has_fpower_series_on_ball f p x r) : 0 < p.radius := lt_of_lt_of_le hf.r_pos hf.r_le lemma has_fpower_series_at.radius_pos (hf : has_fpower_series_at f p x) : 0 < p.radius := let ⟨r, hr⟩ := hf in hr.radius_pos lemma has_fpower_series_on_ball.mono (hf : has_fpower_series_on_ball f p x r) (r'_pos : 0 < r') (hr : r' ≤ r) : has_fpower_series_on_ball f p x r' := ⟨le_trans hr hf.1, r'_pos, λ y hy, hf.has_sum (emetric.ball_subset_ball hr hy)⟩ protected lemma has_fpower_series_at.eventually (hf : has_fpower_series_at f p x) : ∀ᶠ r : ℝ≥0∞ in 𝓝[Ioi 0] 0, has_fpower_series_on_ball f p x r := let ⟨r, hr⟩ := hf in mem_sets_of_superset (Ioo_mem_nhds_within_Ioi (left_mem_Ico.2 hr.r_pos)) $ λ r' hr', hr.mono hr'.1 hr'.2.le lemma has_fpower_series_on_ball.add (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f + g) (pf + pg) x r := { r_le := le_trans (le_min_iff.2 ⟨hf.r_le, hg.r_le⟩) (pf.min_radius_le_radius_add pg), r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).add (hg.has_sum hy) } lemma has_fpower_series_at.add (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f + g) (pf + pg) x := begin rcases (hf.eventually.and hg.eventually).exists with ⟨r, hr⟩, exact ⟨r, hr.1.add hr.2⟩ end lemma analytic_at.add (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f + g) x := let ⟨pf, hpf⟩ := hf, ⟨qf, hqf⟩ := hg in (hpf.add hqf).analytic_at lemma has_fpower_series_on_ball.neg (hf : has_fpower_series_on_ball f pf x r) : has_fpower_series_on_ball (-f) (-pf) x r := { r_le := by { rw pf.radius_neg, exact hf.r_le }, r_pos := hf.r_pos, has_sum := λ y hy, (hf.has_sum hy).neg } lemma has_fpower_series_at.neg (hf : has_fpower_series_at f pf x) : has_fpower_series_at (-f) (-pf) x := let ⟨rf, hrf⟩ := hf in hrf.neg.has_fpower_series_at lemma analytic_at.neg (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (-f) x := let ⟨pf, hpf⟩ := hf in hpf.neg.analytic_at lemma has_fpower_series_on_ball.sub (hf : has_fpower_series_on_ball f pf x r) (hg : has_fpower_series_on_ball g pg x r) : has_fpower_series_on_ball (f - g) (pf - pg) x r := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_at.sub (hf : has_fpower_series_at f pf x) (hg : has_fpower_series_at g pg x) : has_fpower_series_at (f - g) (pf - pg) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma analytic_at.sub (hf : analytic_at 𝕜 f x) (hg : analytic_at 𝕜 g x) : analytic_at 𝕜 (f - g) x := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma has_fpower_series_on_ball.coeff_zero (hf : has_fpower_series_on_ball f pf x r) (v : fin 0 → E) : pf 0 v = f x := begin have v_eq : v = (λ i, 0) := subsingleton.elim _ _, have zero_mem : (0 : E) ∈ emetric.ball (0 : E) r, by simp [hf.r_pos], have : ∀ i ≠ 0, pf i (λ j, 0) = 0, { assume i hi, have : 0 < i := pos_iff_ne_zero.2 hi, exact continuous_multilinear_map.map_coord_zero _ (⟨0, this⟩ : fin i) rfl }, have A := (hf.has_sum zero_mem).unique (has_sum_single _ this), simpa [v_eq] using A.symm, end lemma has_fpower_series_at.coeff_zero (hf : has_fpower_series_at f pf x) (v : fin 0 → E) : pf 0 v = f x := let ⟨rf, hrf⟩ := hf in hrf.coeff_zero v /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. This version provides an upper estimate that decreases both in `∥y∥` and `n`. See also `has_fpower_series_on_ball.uniform_geometric_approx` for a weaker version. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ n, ∥p n∥ * r' ^n ≤ C * a^n := p.norm_mul_pow_le_mul_pow_of_lt_radius (h.trans_le hf.r_le), refine ⟨a, ha, C / (1 - a), div_pos hC (sub_pos.2 ha.2), λ y hy n, _⟩, have yr' : ∥y∥ < r', by { rw ball_0_eq at hy, exact hy }, have hr'0 : 0 < (r' : ℝ), from (norm_nonneg _).trans_lt yr', have : y ∈ emetric.ball (0 : E) r, { refine mem_emetric_ball_0_iff.2 (lt_trans _ h), exact_mod_cast yr' }, rw [norm_sub_rev, ← mul_div_right_comm], have ya : a * (∥y∥ / ↑r') ≤ a, from mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg), suffices : ∥p.partial_sum n y - f (x + y)∥ ≤ C * (a * (∥y∥ / r')) ^ n / (1 - a * (∥y∥ / r')), { refine this.trans _, apply_rules [div_le_div_of_le_left, sub_pos.2, div_nonneg, mul_nonneg, pow_nonneg, hC.lt.le, ha.1.le, norm_nonneg, nnreal.coe_nonneg, ha.2, (sub_le_sub_iff_left _).2]; apply_instance }, apply norm_sub_le_of_geometric_bound_of_has_sum (ya.trans_lt ha.2) _ (hf.has_sum this), assume n, calc ∥(p n) (λ (i : fin n), y)∥ ≤ ∥p n∥ * (∏ i : fin n, ∥y∥) : continuous_multilinear_map.le_op_norm _ _ ... = (∥p n∥ * r' ^ n) * (∥y∥ / r') ^ n : by field_simp [hr'0.ne', mul_right_comm] ... ≤ (C * a ^ n) * (∥y∥ / r') ^ n : mul_le_mul_of_nonneg_right (hp n) (pow_nonneg (div_nonneg (norm_nonneg _) r'.coe_nonneg) _) ... ≤ C * (a * (∥y∥ / r')) ^ n : by rw [mul_pow, mul_assoc] end /-- If a function admits a power series expansion, then it is exponentially close to the partial sums of this power series on strict subdisks of the disk of convergence. -/ lemma has_fpower_series_on_ball.uniform_geometric_approx {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n) := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine ⟨a, ha, C, hC, λ y hy n, (hp y hy n).trans _⟩, have yr' : ∥y∥ < r', by rwa ball_0_eq at hy, refine mul_le_mul_of_nonneg_left (pow_le_pow_of_le_left _ _ _) hC.lt.le, exacts [mul_nonneg ha.1.le (div_nonneg (norm_nonneg y) r'.coe_nonneg), mul_le_of_le_one_right ha.1.le (div_le_one_of_le yr'.le r'.coe_nonneg)] end /-- Taylor formula for an analytic function, `is_O` version. -/ lemma has_fpower_series_at.is_O_sub_partial_sum_pow (hf : has_fpower_series_at f p x) (n : ℕ) : is_O (λ y : E, f (x + y) - p.partial_sum n y) (λ y, ∥y∥ ^ n) (𝓝 0) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * (a * (∥y∥ / r')) ^ n), from hf.uniform_geometric_approx' h, refine is_O_iff.2 ⟨C * (a / r') ^ n, _⟩, replace r'0 : 0 < (r' : ℝ), by exact_mod_cast r'0, filter_upwards [metric.ball_mem_nhds (0 : E) r'0], intros y hy, simpa [mul_pow, mul_div_assoc, mul_assoc, div_mul_eq_mul_div] using hp y hy n end -- hack to speed up simp when dealing with complicated types local attribute [-instance] unique.subsingleton pi.subsingleton /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. This lemma formulates this property using `is_O` and `filter.principal` on `E × E`. -/ lemma has_fpower_series_on_ball.is_O_image_sub_image_sub_deriv_principal (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 $ emetric.ball (x, x) r') := begin lift r' to ℝ≥0 using ne_top_of_lt hr, rcases (zero_le r').eq_or_lt with rfl|hr'0, { simp }, obtain ⟨a, ha, C, hC : 0 < C, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), ∀ (n : ℕ), ∥p n∥ * ↑r' ^ n ≤ C * a ^ n, from p.norm_mul_pow_le_mul_pow_of_lt_radius (hr.trans_le hf.r_le), simp only [← le_div_iff (pow_pos (nnreal.coe_pos.2 hr'0) _)] at hp, set L : E × E → ℝ := λ y, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * (a / (1 - a) ^ 2 + 2 / (1 - a)), have hL : ∀ y ∈ emetric.ball (x, x) r', ∥f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))∥ ≤ L y, { intros y hy', have hy : y ∈ (emetric.ball x r).prod (emetric.ball x r), { rw [emetric.ball_prod_same], exact emetric.ball_subset_ball hr.le hy' }, set A : ℕ → F := λ n, p n (λ _, y.1 - x) - p n (λ _, y.2 - x), have hA : has_sum (λ n, A (n + 2)) (f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))), { convert (has_sum_nat_add_iff' 2).2 ((hf.has_sum_sub hy.1).sub (hf.has_sum_sub hy.2)), rw [finset.sum_range_succ, finset.sum_range_one, hf.coeff_zero, hf.coeff_zero, sub_self, zero_add, ← subsingleton.pi_single_eq (0 : fin 1) (y.1 - x), pi.single, ← subsingleton.pi_single_eq (0 : fin 1) (y.2 - x), pi.single, ← (p 1).map_sub, ← pi.single, subsingleton.pi_single_eq, sub_sub_sub_cancel_right] }, rw [emetric.mem_ball, edist_eq_coe_nnnorm_sub, ennreal.coe_lt_coe] at hy', set B : ℕ → ℝ := λ n, (C * (a / r') ^ 2) * (∥y - (x, x)∥ * ∥y.1 - y.2∥) * ((n + 2) * a ^ n), have hAB : ∀ n, ∥A (n + 2)∥ ≤ B n := λ n, calc ∥A (n + 2)∥ ≤ ∥p (n + 2)∥ * ↑(n + 2) * ∥y - (x, x)∥ ^ (n + 1) * ∥y.1 - y.2∥ : by simpa [fintype.card_fin, pi_norm_const, prod.norm_def, pi.sub_def, prod.fst_sub, prod.snd_sub, sub_sub_sub_cancel_right] using (p $ n + 2).norm_image_sub_le (λ _, y.1 - x) (λ _, y.2 - x) ... = ∥p (n + 2)∥ * ∥y - (x, x)∥ ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by { rw [pow_succ ∥y - (x, x)∥], ac_refl } ... ≤ (C * a ^ (n + 2) / r' ^ (n + 2)) * r' ^ n * (↑(n + 2) * ∥y - (x, x)∥ * ∥y.1 - y.2∥) : by apply_rules [mul_le_mul_of_nonneg_right, mul_le_mul, hp, pow_le_pow_of_le_left, hy'.le, norm_nonneg, pow_nonneg, div_nonneg, mul_nonneg, nat.cast_nonneg, hC.le, r'.coe_nonneg, ha.1.le] ... = B n : by { field_simp [B, pow_succ, hr'0.ne'], simp [mul_assoc, mul_comm, mul_left_comm] }, have hBL : has_sum B (L y), { apply has_sum.mul_left, simp only [add_mul], have : ∥a∥ < 1, by simp only [real.norm_eq_abs, abs_of_pos ha.1, ha.2], convert (has_sum_coe_mul_geometric_of_norm_lt_1 this).add ((has_sum_geometric_of_norm_lt_1 this).mul_left 2) }, exact hA.norm_le_of_bounded hBL hAB }, suffices : is_O L (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓟 (emetric.ball (x, x) r')), { refine (is_O.of_bound 1 (eventually_principal.2 $ λ y hy, _)).trans this, rw one_mul, exact (hL y hy).trans (le_abs_self _) }, simp_rw [L, mul_right_comm _ (_ * _)], exact (is_O_refl _ _).const_mul_left _, end /-- If `f` has formal power series `∑ n, pₙ` on a ball of radius `r`, then for `y, z` in any smaller ball, the norm of the difference `f y - f z - p 1 (λ _, y - z)` is bounded above by `C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥`. -/ lemma has_fpower_series_on_ball.image_sub_sub_deriv_le (hf : has_fpower_series_on_ball f p x r) (hr : r' < r) : ∃ C, ∀ (y z ∈ emetric.ball x r'), ∥f y - f z - (p 1 (λ _, y - z))∥ ≤ C * (max ∥y - x∥ ∥z - x∥) * ∥y - z∥ := by simpa only [is_O_principal, mul_assoc, normed_field.norm_mul, norm_norm, prod.forall, emetric.mem_ball, prod.edist_eq, max_lt_iff, and_imp] using hf.is_O_image_sub_image_sub_deriv_principal hr /-- If `f` has formal power series `∑ n, pₙ` at `x`, then `f y - f z - p 1 (λ _, y - z) = O(∥(y, z) - (x, x)∥ * ∥y - z∥)` as `(y, z) → (x, x)`. In particular, `f` is strictly differentiable at `x`. -/ lemma has_fpower_series_at.is_O_image_sub_norm_mul_norm_sub (hf : has_fpower_series_at f p x) : is_O (λ y : E × E, f y.1 - f y.2 - (p 1 (λ _, y.1 - y.2))) (λ y, ∥y - (x, x)∥ * ∥y.1 - y.2∥) (𝓝 (x, x)) := begin rcases hf with ⟨r, hf⟩, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hf.r_pos with ⟨r', r'0, h⟩, refine (hf.is_O_image_sub_image_sub_deriv_principal h).mono _, exact le_principal_iff.2 (emetric.ball_mem_nhds _ r'0) end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f (x + y)` is the uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (metric.ball (0 : E) r') := begin obtain ⟨a, ha, C, hC, hp⟩ : ∃ (a ∈ Ioo (0 : ℝ) 1) (C > 0), (∀ y ∈ metric.ball (0 : E) r', ∀ n, ∥f (x + y) - p.partial_sum n y∥ ≤ C * a ^ n), from hf.uniform_geometric_approx h, refine metric.tendsto_uniformly_on_iff.2 (λ ε εpos, _), have L : tendsto (λ n, (C : ℝ) * a^n) at_top (𝓝 ((C : ℝ) * 0)) := tendsto_const_nhds.mul (tendsto_pow_at_top_nhds_0_of_lt_1 ha.1.le ha.2), rw mul_zero at L, refine (L.eventually (gt_mem_nhds εpos)).mono (λ n hn y hy, _), rw dist_eq_norm, exact (hp y hy n).trans_lt hn end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f (x + y)` is the locally uniform limit of `p.partial_sum n y` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n y) (λ y, f (x + y)) at_top (emetric.ball (0 : E) r) := begin assume u hu x hx, rcases ennreal.lt_iff_exists_nnreal_btwn.1 hx with ⟨r', xr', hr'⟩, have : emetric.ball (0 : E) r' ∈ 𝓝 x := is_open.mem_nhds emetric.is_open_ball xr', refine ⟨emetric.ball (0 : E) r', mem_nhds_within_of_mem_nhds this, _⟩, simpa [metric.emetric_ball_nnreal] using hf.tendsto_uniformly_on hr' u hu end /-- If a function admits a power series expansion at `x`, then it is the uniform limit of the partial sums of this power series on strict subdisks of the disk of convergence, i.e., `f y` is the uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_uniformly_on' {r' : ℝ≥0} (hf : has_fpower_series_on_ball f p x r) (h : (r' : ℝ≥0∞) < r) : tendsto_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (metric.ball (x : E) r') := begin convert (hf.tendsto_uniformly_on h).comp (λ y, y - x), { simp [(∘)] }, { ext z, simp [dist_eq_norm] } end /-- If a function admits a power series expansion at `x`, then it is the locally uniform limit of the partial sums of this power series on the disk of convergence, i.e., `f y` is the locally uniform limit of `p.partial_sum n (y - x)` there. -/ lemma has_fpower_series_on_ball.tendsto_locally_uniformly_on' (hf : has_fpower_series_on_ball f p x r) : tendsto_locally_uniformly_on (λ n y, p.partial_sum n (y - x)) f at_top (emetric.ball (x : E) r) := begin have A : continuous_on (λ (y : E), y - x) (emetric.ball (x : E) r) := (continuous_id.sub continuous_const).continuous_on, convert (hf.tendsto_locally_uniformly_on).comp (λ (y : E), y - x) _ A, { ext z, simp }, { assume z, simp [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] } end /-- If a function admits a power series expansion on a disk, then it is continuous there. -/ lemma has_fpower_series_on_ball.continuous_on (hf : has_fpower_series_on_ball f p x r) : continuous_on f (emetric.ball x r) := hf.tendsto_locally_uniformly_on'.continuous_on $ λ n, ((p.partial_sum_continuous n).comp (continuous_id.sub continuous_const)).continuous_on lemma has_fpower_series_at.continuous_at (hf : has_fpower_series_at f p x) : continuous_at f x := let ⟨r, hr⟩ := hf in hr.continuous_on.continuous_at (emetric.ball_mem_nhds x (hr.r_pos)) lemma analytic_at.continuous_at (hf : analytic_at 𝕜 f x) : continuous_at f x := let ⟨p, hp⟩ := hf in hp.continuous_at lemma formal_multilinear_series.summable_norm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥ * r ^ n) := begin obtain ⟨a, ha : a ∈ Ioo (0 : ℝ) 1, C, hC : 0 < C, hp⟩ := p.norm_mul_pow_le_mul_pow_of_lt_radius h, exact summable_of_nonneg_of_le (λ n, mul_nonneg (norm_nonneg _) (pow_nonneg r.coe_nonneg _)) hp ((summable_geometric_of_lt_1 ha.1.le ha.2).mul_left _), end lemma formal_multilinear_series.summable_nnnorm_mul_pow (p : formal_multilinear_series 𝕜 E F) {r : ℝ≥0} (h : ↑r < p.radius) : summable (λ n : ℕ, ∥p n∥₊ * r ^ n) := by { rw ← nnreal.summable_coe, push_cast, exact p.summable_norm_mul_pow h } protected lemma formal_multilinear_series.summable [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : summable (λ n : ℕ, p n (λ _, x)) := begin rw mem_emetric_ball_0_iff at hx, refine summable_of_norm_bounded _ (p.summable_norm_mul_pow hx) (λ n, ((p n).le_op_norm _).trans_eq _), simp end protected lemma formal_multilinear_series.has_sum [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x : E} (hx : x ∈ emetric.ball (0 : E) p.radius) : has_sum (λ n : ℕ, p n (λ _, x)) (p.sum x) := (p.summable hx).has_sum /-- In a complete space, the sum of a converging power series `p` admits `p` as a power series. This is not totally obvious as we need to check the convergence of the series. -/ protected lemma formal_multilinear_series.has_fpower_series_on_ball [complete_space F] (p : formal_multilinear_series 𝕜 E F) (h : 0 < p.radius) : has_fpower_series_on_ball p.sum p 0 p.radius := { r_le := le_refl _, r_pos := h, has_sum := λ y hy, by { rw zero_add, exact p.has_sum hy } } lemma has_fpower_series_on_ball.sum [complete_space F] (h : has_fpower_series_on_ball f p x r) {y : E} (hy : y ∈ emetric.ball (0 : E) r) : f (x + y) = p.sum y := (h.has_sum hy).unique (p.has_sum (lt_of_lt_of_le hy h.r_le)) /-- The sum of a converging power series is continuous in its disk of convergence. -/ protected lemma formal_multilinear_series.continuous_on [complete_space F] : continuous_on p.sum (emetric.ball 0 p.radius) := begin cases (zero_le p.radius).eq_or_lt with h h, { simp [← h, continuous_on_empty] }, { exact (p.has_fpower_series_on_ball h).continuous_on } end end /-! ### Changing origin in a power series If a function is analytic in a disk `D(x, R)`, then it is analytic in any disk contained in that one. Indeed, one can write $$ f (x + y + z) = \sum_{n} p_n (y + z)^n = \sum_{n, k} \binom{n}{k} p_n y^{n-k} z^k = \sum_{k} \Bigl(\sum_{n} \binom{n}{k} p_n y^{n-k}\Bigr) z^k. $$ The corresponding power series has thus a `k`-th coefficient equal to $\sum_{n} \binom{n}{k} p_n y^{n-k}$. In the general case where `pₙ` is a multilinear map, this has to be interpreted suitably: instead of having a binomial coefficient, one should sum over all possible subsets `s` of `fin n` of cardinal `k`, and attribute `z` to the indices in `s` and `y` to the indices outside of `s`. In this paragraph, we implement this. The new power series is called `p.change_origin y`. Then, we check its convergence and the fact that its sum coincides with the original sum. The outcome of this discussion is that the set of points where a function is analytic is open. -/ namespace formal_multilinear_series section variables (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} /-- A term of `formal_multilinear_series.change_origin_series`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. Each term of `p.change_origin x` is itself an analytic function of `x` given by the series `p.change_origin_series`. Each term in `change_origin_series` is the sum of `change_origin_series_term`'s over all `s` of cardinality `l`. -/ def change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : E [×l]→L[𝕜] E [×k]→L[𝕜] F := continuous_multilinear_map.curry_fin_finset 𝕜 E F hs (by erw [finset.card_compl, fintype.card_fin, hs, nat.add_sub_cancel]) (p $ k + l) lemma change_origin_series_term_apply (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : p.change_origin_series_term k l s hs (λ _, x) (λ _, y) = p (k + l) (s.piecewise (λ _, x) (λ _, y)) := continuous_multilinear_map.curry_fin_finset_apply_const _ _ _ _ _ @[simp] lemma norm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥ = ∥p (k + l)∥ := by simp only [change_origin_series_term, linear_isometry_equiv.norm_map] @[simp] lemma nnnorm_change_origin_series_term (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) : ∥p.change_origin_series_term k l s hs∥₊ = ∥p (k + l)∥₊ := by simp only [change_origin_series_term, linear_isometry_equiv.nnnorm_map] lemma nnnorm_change_origin_series_term_apply_le (k l : ℕ) (s : finset (fin (k + l))) (hs : s.card = l) (x y : E) : ∥p.change_origin_series_term k l s hs (λ _, x) (λ _, y)∥₊ ≤ ∥p (k + l)∥₊ * ∥x∥₊ ^ l * ∥y∥₊ ^ k := begin rw [← p.nnnorm_change_origin_series_term k l s hs, ← fin.prod_const, ← fin.prod_const], apply continuous_multilinear_map.le_of_op_nnnorm_le, apply continuous_multilinear_map.le_op_nnnorm end /-- The power series for `f.change_origin k`. Given a formal multilinear series `p` and a point `x` in its ball of convergence, `p.change_origin x` is a formal multilinear series such that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin_series (k : ℕ) : formal_multilinear_series 𝕜 E (E [×k]→L[𝕜] F) := λ l, ∑ s : {s : finset (fin (k + l)) // finset.card s = l}, p.change_origin_series_term k l s s.2 lemma nnnorm_change_origin_series_le_tsum (k l : ℕ) : ∥p.change_origin_series k l∥₊ ≤ ∑' (x : {s : finset (fin (k + l)) // s.card = l}), ∥p (k + l)∥₊ := (nnnorm_sum_le _ _).trans_eq $ by simp only [tsum_fintype, nnnorm_change_origin_series_term] lemma nnnorm_change_origin_series_apply_le_tsum (k l : ℕ) (x : E) : ∥p.change_origin_series k l (λ _, x)∥₊ ≤ ∑' s : {s : finset (fin (k + l)) // s.card = l}, ∥p (k + l)∥₊ * ∥x∥₊ ^ l := begin rw [nnreal.tsum_mul_right, ← fin.prod_const], exact (p.change_origin_series k l).le_of_op_nnnorm_le _ (p.nnnorm_change_origin_series_le_tsum _ _) end /-- Changing the origin of a formal multilinear series `p`, so that `p.sum (x+y) = (p.change_origin x).sum y` when this makes sense. -/ def change_origin (x : E) : formal_multilinear_series 𝕜 E F := λ k, (p.change_origin_series k).sum x /-- An auxiliary equivalence useful in the proofs about `formal_multilinear_series.change_origin_series`: the set of triples `(k, l, s)`, where `s` is a `finset (fin (k + l))` of cardinality `l` is equivalent to the set of pairs `(n, s)`, where `s` is a `finset (fin n)`. The forward map sends `(k, l, s)` to `(k + l, s)` and the inverse map sends `(n, s)` to `(n - finset.card s, finset.card s, s)`. The actual definition is less readable because of problems with non-definitional equalities. -/ @[simps] def change_origin_index_equiv : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}) ≃ Σ n : ℕ, finset (fin n) := { to_fun := λ s, ⟨s.1 + s.2.1, s.2.2⟩, inv_fun := λ s, ⟨s.1 - s.2.card, s.2.card, ⟨s.2.map (fin.cast $ (nat.sub_add_cancel $ card_finset_fin_le s.2).symm).to_equiv.to_embedding, finset.card_map _⟩⟩, left_inv := begin rintro ⟨k, l, ⟨s : finset (fin $ k + l), hs : s.card = l⟩⟩, dsimp only [subtype.coe_mk], -- Lean can't automatically generalize `k' = k + l - s.card`, `l' = s.card`, so we explicitly -- formulate the generalized goal suffices : ∀ k' l', k' = k → l' = l → ∀ (hkl : k + l = k' + l') hs', (⟨k', l', ⟨finset.map (fin.cast hkl).to_equiv.to_embedding s, hs'⟩⟩ : (Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l})) = ⟨k, l, ⟨s, hs⟩⟩, { apply this; simp only [hs, nat.add_sub_cancel] }, rintro _ _ rfl rfl hkl hs', simp only [equiv.refl_to_embedding, fin.cast_refl, finset.map_refl, eq_self_iff_true, order_iso.refl_to_equiv, and_self, heq_iff_eq] end, right_inv := begin rintro ⟨n, s⟩, simp [nat.sub_add_cancel (card_finset_fin_le s), fin.cast_to_equiv] end } lemma change_origin_series_summable_aux₁ {r r' : ℝ≥0} (hr : (r + r' : ℝ≥0∞) < p.radius) : summable (λ s : Σ k l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (s.1 + s.2.1)∥₊ * r ^ s.2.1 * r' ^ s.1) := begin rw ← change_origin_index_equiv.symm.summable_iff, dsimp only [(∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst], have : ∀ n : ℕ, has_sum (λ s : finset (fin n), ∥p (n - s.card + s.card)∥₊ * r ^ s.card * r' ^ (n - s.card)) (∥p n∥₊ * (r + r') ^ n), { intro n, -- TODO: why `simp only [nat.sub_add_cancel (card_finset_fin_le _)]` fails? convert_to has_sum (λ s : finset (fin n), ∥p n∥₊ * (r ^ s.card * r' ^ (n - s.card))) _, { ext1 s, rw [nat.sub_add_cancel (card_finset_fin_le _), mul_assoc] }, rw ← fin.sum_pow_mul_eq_add_pow, exact (has_sum_fintype _).mul_left _ }, refine nnreal.summable_sigma.2 ⟨λ n, (this n).summable, _⟩, simp only [(this _).tsum_eq], exact p.summable_nnnorm_mul_pow hr end lemma change_origin_series_summable_aux₂ (hr : (r : ℝ≥0∞) < p.radius) (k : ℕ) : summable (λ s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * r ^ s.1) := begin rcases ennreal.lt_iff_exists_add_pos_lt.1 hr with ⟨r', h0, hr'⟩, simpa only [mul_inv_cancel_right' (pow_pos h0 _).ne'] using ((nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr')).1 k).mul_right (r' ^ k)⁻¹ end lemma change_origin_series_summable_aux₃ {r : ℝ≥0} (hr : ↑r < p.radius) (k : ℕ) : summable (λ l : ℕ, ∥p.change_origin_series k l∥₊ * r ^ l) := begin refine nnreal.summable_of_le (λ n, _) (nnreal.summable_sigma.1 $ p.change_origin_series_summable_aux₂ hr k).2, simp only [nnreal.tsum_mul_right], exact mul_le_mul' (p.nnnorm_change_origin_series_le_tsum _ _) le_rfl end lemma le_change_origin_series_radius (k : ℕ) : p.radius ≤ (p.change_origin_series k).radius := ennreal.le_of_forall_nnreal_lt $ λ r hr, le_radius_of_summable_nnnorm _ (p.change_origin_series_summable_aux₃ hr k) lemma nnnorm_change_origin_le (k : ℕ) (h : (∥x∥₊ : ℝ≥0∞) < p.radius) : ∥p.change_origin x k∥₊ ≤ ∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1 := begin refine tsum_of_nnnorm_bounded _ (λ l, p.nnnorm_change_origin_series_apply_le_tsum k l x), have := p.change_origin_series_summable_aux₂ h k, refine has_sum.sigma this.has_sum (λ l, _), exact ((nnreal.summable_sigma.1 this).1 l).has_sum end /-- The radius of convergence of `p.change_origin x` is at least `p.radius - ∥x∥`. In other words, `p.change_origin x` is well defined on the largest ball contained in the original ball of convergence.-/ lemma change_origin_radius : p.radius - ∥x∥₊ ≤ (p.change_origin x).radius := begin refine ennreal.le_of_forall_pos_nnreal_lt (λ r h0 hr, _), rw [ennreal.lt_sub_iff_add_lt, add_comm] at hr, have hr' : (∥x∥₊ : ℝ≥0∞) < p.radius, from (le_add_right le_rfl).trans_lt hr, apply le_radius_of_summable_nnnorm, have : ∀ k : ℕ, ∥p.change_origin x k∥₊ * r ^ k ≤ (∑' s : Σ l : ℕ, {s : finset (fin (k + l)) // s.card = l}, ∥p (k + s.1)∥₊ * ∥x∥₊ ^ s.1) * r ^ k, from λ k, mul_le_mul_right' (p.nnnorm_change_origin_le k hr') (r ^ k), refine nnreal.summable_of_le this _, simpa only [← nnreal.tsum_mul_right] using (nnreal.summable_sigma.1 (p.change_origin_series_summable_aux₁ hr)).2 end end -- From this point on, assume that the space is complete, to make sure that series that converge -- in norm also converge in `F`. variables [complete_space F] (p : formal_multilinear_series 𝕜 E F) {x y : E} {r R : ℝ≥0} lemma has_fpower_series_on_ball_change_origin (k : ℕ) (hr : 0 < p.radius) : has_fpower_series_on_ball (λ x, p.change_origin x k) (p.change_origin_series k) 0 p.radius := have _ := p.le_change_origin_series_radius k, ((p.change_origin_series k).has_fpower_series_on_ball (hr.trans_le this)).mono hr this /-- Summing the series `p.change_origin x` at a point `y` gives back `p (x + y)`-/ theorem change_origin_eval (h : (∥x∥₊ + ∥y∥₊ : ℝ≥0∞) < p.radius) : (p.change_origin x).sum y = (p.sum (x + y)) := begin have radius_pos : 0 < p.radius := lt_of_le_of_lt (zero_le _) h, have x_mem_ball : x ∈ emetric.ball (0 : E) p.radius, from mem_emetric_ball_0_iff.2 ((le_add_right le_rfl).trans_lt h), have y_mem_ball : y ∈ emetric.ball (0 : E) (p.change_origin x).radius, { refine mem_emetric_ball_0_iff.2 (lt_of_lt_of_le _ p.change_origin_radius), rwa [ennreal.lt_sub_iff_add_lt, add_comm] }, have x_add_y_mem_ball : x + y ∈ emetric.ball (0 : E) p.radius, { refine mem_emetric_ball_0_iff.2 (lt_of_le_of_lt _ h), exact_mod_cast nnnorm_add_le x y }, set f : (Σ (k l : ℕ), {s : finset (fin (k + l)) // s.card = l}) → F := λ s, p.change_origin_series_term s.1 s.2.1 s.2.2 s.2.2.2 (λ _, x) (λ _, y), have hsf : summable f, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₁ h) _, rintro ⟨k, l, s, hs⟩, dsimp only [subtype.coe_mk], exact p.nnnorm_change_origin_series_term_apply_le _ _ _ _ _ _ }, have hf : has_sum f ((p.change_origin x).sum y), { refine has_sum.sigma_of_has_sum ((p.change_origin x).summable y_mem_ball).has_sum (λ k, _) hsf, { dsimp only [f], refine continuous_multilinear_map.has_sum_eval _ _, have := (p.has_fpower_series_on_ball_change_origin k radius_pos).has_sum x_mem_ball, rw zero_add at this, refine has_sum.sigma_of_has_sum this (λ l, _) _, { simp only [change_origin_series, continuous_multilinear_map.sum_apply], apply has_sum_fintype }, { refine summable_of_nnnorm_bounded _ (p.change_origin_series_summable_aux₂ (mem_emetric_ball_0_iff.1 x_mem_ball) k) (λ s, _), refine (continuous_multilinear_map.le_op_nnnorm _ _).trans_eq _, simp } } }, refine hf.unique (change_origin_index_equiv.symm.has_sum_iff.1 _), refine has_sum.sigma_of_has_sum (p.has_sum x_add_y_mem_ball) (λ n, _) (change_origin_index_equiv.symm.summable_iff.2 hsf), erw [(p n).map_add_univ (λ _, x) (λ _, y)], convert has_sum_fintype _, ext1 s, dsimp only [f, change_origin_series_term, (∘), change_origin_index_equiv_symm_apply_fst, change_origin_index_equiv_symm_apply_snd_fst, change_origin_index_equiv_symm_apply_snd_snd_coe], rw continuous_multilinear_map.curry_fin_finset_apply_const, have : ∀ m (hm : n = m), p n (s.piecewise (λ _, x) (λ _, y)) = p m ((s.map (fin.cast hm).to_equiv.to_embedding).piecewise (λ _, x) (λ _, y)), { rintro m rfl, simp, congr /- probably different `decidable_eq` instances -/ }, apply this end end formal_multilinear_series section variables [complete_space F] {f : E → F} {p : formal_multilinear_series 𝕜 E F} {x y : E} {r : ℝ≥0∞} /-- If a function admits a power series expansion `p` on a ball `B (x, r)`, then it also admits a power series on any subball of this ball (even with a different center), given by `p.change_origin`. -/ theorem has_fpower_series_on_ball.change_origin (hf : has_fpower_series_on_ball f p x r) (h : (∥y∥₊ : ℝ≥0∞) < r) : has_fpower_series_on_ball f (p.change_origin y) (x + y) (r - ∥y∥₊) := { r_le := begin apply le_trans _ p.change_origin_radius, exact ennreal.sub_le_sub hf.r_le (le_refl _) end, r_pos := by simp [h], has_sum := λ z hz, begin convert (p.change_origin y).has_sum _, { rw [mem_emetric_ball_0_iff, ennreal.lt_sub_iff_add_lt, add_comm] at hz, rw [p.change_origin_eval (hz.trans_le hf.r_le), add_assoc, hf.sum], refine mem_emetric_ball_0_iff.2 (lt_of_le_of_lt _ hz), exact_mod_cast nnnorm_add_le y z }, { refine emetric.ball_subset_ball (le_trans _ p.change_origin_radius) hz, exact ennreal.sub_le_sub hf.r_le le_rfl } end } /-- If a function admits a power series expansion `p` on an open ball `B (x, r)`, then it is analytic at every point of this ball. -/ lemma has_fpower_series_on_ball.analytic_at_of_mem (hf : has_fpower_series_on_ball f p x r) (h : y ∈ emetric.ball x r) : analytic_at 𝕜 f y := begin have : (∥y - x∥₊ : ℝ≥0∞) < r, by simpa [edist_eq_coe_nnnorm_sub] using h, have := hf.change_origin this, rw [add_sub_cancel'_right] at this, exact this.analytic_at end variables (𝕜 f) /-- For any function `f` from a normed vector space to a Banach space, the set of points `x` such that `f` is analytic at `x` is open. -/ lemma is_open_analytic_at : is_open {x | analytic_at 𝕜 f x} := begin rw is_open_iff_mem_nhds, rintro x ⟨p, r, hr⟩, exact mem_sets_of_superset (emetric.ball_mem_nhds _ hr.r_pos) (λ y hy, hr.analytic_at_of_mem hy) end end
d86a549f5edabf74841534bbf00e8a487520b4e1
1dd482be3f611941db7801003235dc84147ec60a
/src/topology/metric_space/lipschitz.lean
c5eecec9327b43ead55fdac8a51b358f1193de1a
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
6,748
lean
/- Copyright (c) 2018 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl Lipschitz functions and the Banach fixed-point theorem -/ import topology.metric_space.basic analysis.specific_limits open filter variables {α : Type*} {β : Type*} {γ : Type*} lemma fixed_point_of_tendsto_iterate [topological_space α] [t2_space α] {f : α → α} {x : α} (hf : tendsto f (nhds x) (nhds (f x))) (hx : ∃ x₀ : α, tendsto (λ n, f^[n] x₀) at_top (nhds x)) : f x = x := begin rcases hx with ⟨x₀, hx⟩, refine tendsto_nhds_unique at_top_ne_bot _ hx, rw [← tendsto_comp_succ_at_top_iff, funext (assume n, nat.iterate_succ' f n x₀)], exact hx.comp hf end /-- A Lipschitz function is uniformly continuous -/ lemma uniform_continuous_of_lipschitz [metric_space α] [metric_space β] {K : ℝ} {f : α → β} (H : ∀x y, dist (f x) (f y) ≤ K * dist x y) : uniform_continuous f := begin have : 0 < max K 1 := lt_of_lt_of_le zero_lt_one (le_max_right K 1), refine metric.uniform_continuous_iff.2 (λε εpos, _), exact ⟨ε/max K 1, div_pos εpos this, assume y x Dyx, calc dist (f y) (f x) ≤ K * dist y x : H y x ... ≤ max K 1 * dist y x : mul_le_mul_of_nonneg_right (le_max_left K 1) (dist_nonneg) ... < max K 1 * (ε/max K 1) : mul_lt_mul_of_pos_left Dyx this ... = ε : mul_div_cancel' _ (ne_of_gt this)⟩ end /-- A Lipschitz function is continuous -/ lemma continuous_of_lipschitz [metric_space α] [metric_space β] {K : ℝ} {f : α → β} (H : ∀x y, dist (f x) (f y) ≤ K * dist x y) : continuous f := uniform_continuous.continuous (uniform_continuous_of_lipschitz H) lemma uniform_continuous_of_le_add [metric_space α] {f : α → ℝ} (K : ℝ) (h : ∀x y, f x ≤ f y + K * dist x y) : uniform_continuous f := begin have I : ∀ (x y : α), f x - f y ≤ K * dist x y := λx y, calc f x - f y ≤ (f y + K * dist x y) - f y : add_le_add (h x y) (le_refl _) ... = K * dist x y : by ring, refine @uniform_continuous_of_lipschitz _ _ _ _ K _ (λx y, _), rw real.dist_eq, refine abs_sub_le_iff.2 ⟨_, _⟩, { exact I x y }, { rw dist_comm, exact I y x } end /-- `lipschitz_with K f`: the function `f` is Lipschitz continuous w.r.t. the Lipschitz constant `K`. -/ def lipschitz_with [metric_space α] [metric_space β] (K : ℝ) (f : α → β) := 0 ≤ K ∧ ∀x y, dist (f x) (f y) ≤ K * dist x y namespace lipschitz_with variables [metric_space α] [metric_space β] [metric_space γ] {K : ℝ} protected lemma weaken (K' : ℝ) {f : α → β} (hf : lipschitz_with K f) (h : K ≤ K') : lipschitz_with K' f := ⟨le_trans hf.1 h, assume x y, le_trans (hf.2 x y) $ mul_le_mul_of_nonneg_right h dist_nonneg⟩ protected lemma to_uniform_continuous {f : α → β} (hf : lipschitz_with K f) : uniform_continuous f := uniform_continuous_of_lipschitz hf.2 protected lemma to_continuous {f : α → β} (hf : lipschitz_with K f) : continuous f := continuous_of_lipschitz hf.2 protected lemma const (b : β) : lipschitz_with 0 (λa:α, b) := ⟨le_refl 0, assume x y, by simp⟩ protected lemma id : lipschitz_with 1 (@id α) := ⟨zero_le_one, by simp [le_refl]⟩ protected lemma comp {Kf Kg : ℝ} {f : β → γ} {g : α → β} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf * Kg) (f ∘ g) := ⟨mul_nonneg hf.1 hg.1, assume x y, calc dist (f (g x)) (f (g y)) ≤ Kf * dist (g x) (g y) : hf.2 _ _ ... ≤ Kf * (Kg * dist x y) : mul_le_mul_of_nonneg_left (hg.2 _ _) hf.1 ... = (Kf * Kg) * dist x y : by rw mul_assoc⟩ protected lemma iterate {f : α → α} (hf : lipschitz_with K f) : ∀n, lipschitz_with (K ^ n) (f^[n]) | 0 := lipschitz_with.id | (n + 1) := by rw [← nat.succ_eq_add_one, pow_succ, mul_comm]; exact (iterate n).comp hf section contraction variables {f : α → α} {x y : α} lemma dist_inequality_of_contraction (hK₁ : K < 1) (hf : lipschitz_with K f) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) := suffices dist x y ≤ dist x (f x) + (dist y (f y) + K * dist x y), by rwa [le_div_iff (sub_pos_of_lt hK₁), mul_comm, sub_mul, one_mul, sub_le_iff_le_add, add_assoc], calc dist x y ≤ dist x (f x) + dist y (f x) : dist_triangle_right x y (f x) ... ≤ dist x (f x) + (dist y (f y) + dist (f x) (f y)) : add_le_add_left (dist_triangle_right y (f x) (f y)) _ ... ≤ dist x (f x) + (dist y (f y) + K * dist x y) : add_le_add_left (add_le_add_left (hf.2 _ _) _) _ theorem fixed_point_unique_of_contraction (hK : K < 1) (hf : lipschitz_with K f) (hx : f x = x) (hy : f y = y) : x = y := dist_le_zero.1 $ le_trans (dist_inequality_of_contraction hK hf) $ by rewrite [iff.mpr dist_eq_zero hx.symm, iff.mpr dist_eq_zero hy.symm]; simp lemma dist_bound_of_contraction (hK : K < 1) (hf : lipschitz_with K f) {n m : ℕ} : dist (f^[n] x) (f^[m] x) ≤ (K ^ n + K ^ m) * dist x (f x) / (1 - K) := begin apply le_trans, exact dist_inequality_of_contraction hK hf, apply div_le_div_of_le_of_pos _ (sub_pos_of_lt hK), have h : ∀ (m : ℕ), dist (f^[m] x) (f (f^[m] x)) ≤ K ^ m * dist x (f x), { intro m, rewrite [←nat.iterate_succ' f m x, nat.iterate_succ f m x], exact and.right (hf.iterate m) x (f x) }, rewrite add_mul, exact add_le_add (h n) (h m) end private lemma tendsto_dist_bound_at_top_nhds_0 (hK₀ : 0 ≤ K) (hK₁ : K < 1) (z : ℝ) : tendsto (λ (n : ℕ × ℕ), (K ^ n.1 + K ^ n.2) * z / (1 - K)) at_top (nhds 0) := suffices tendsto (λ (n : ℕ × ℕ), (K ^ n.1 + K ^ n.2) * z / (1 - K)) (at_top.prod at_top) (nhds (((0 + 0) * z) * (1 - K)⁻¹)), by simpa [prod_at_top_at_top_eq], tendsto_mul (tendsto_mul (tendsto_add (tendsto_fst.comp (tendsto_pow_at_top_nhds_0_of_lt_1 hK₀ hK₁)) (tendsto_snd.comp (tendsto_pow_at_top_nhds_0_of_lt_1 hK₀ hK₁))) tendsto_const_nhds) tendsto_const_nhds /-- Banach fixed-point theorem, contraction mapping theorem -/ theorem exists_fixed_point_of_contraction [hα : nonempty α] [complete_space α] (hK : K < 1) (hf : lipschitz_with K f) : ∃x, f x = x := let ⟨x₀⟩ := hα in have tendsto (λ (n : ℕ × ℕ), dist (f^[n.fst] x₀) (f^[n.snd] x₀)) at_top (nhds 0) := squeeze_zero (assume x, dist_nonneg) (assume p, dist_bound_of_contraction hK hf) (tendsto_dist_bound_at_top_nhds_0 hf.left hK (dist x₀ (f x₀))), have cauchy_seq (λ n, f^[n] x₀), by rwa [cauchy_seq_iff_tendsto_dist_at_top_0], let ⟨x, hx⟩ := cauchy_seq_tendsto_of_complete this in ⟨x, fixed_point_of_tendsto_iterate (hf.to_uniform_continuous.continuous.tendsto x) ⟨x₀, hx⟩⟩ end contraction end lipschitz_with
12ded6addd5138ed0a473d5d7dcbaa49e0047426
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/doc/examples/widgets.lean
f9047c068aefa9f74f892ca934578a7b9bdd356b
[ "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
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
8,744
lean
import Lean open Lean Widget /-! # The user-widgets system Proving and programming are inherently interactive tasks. Lots of mathematical objects and data structures are visual in nature. *User widgets* let you associate custom interactive UIs with sections of a Lean document. User widgets are rendered in the Lean infoview. ![Rubik's cube](../images/widgets_rubiks.png) ## Trying it out To try it out, simply type in the following code and place your cursor over the `#widget` command. -/ @[widget] def helloWidget : UserWidgetDefinition where name := "Hello" javascript := " import * as React from 'react'; export default function(props) { const name = props.name || 'world' return React.createElement('p', {}, name + '!') }" #widget helloWidget .null /-! If you want to dive into a full sample right away, check out [`RubiksCube`](https://github.com/leanprover/lean4-samples/blob/main/RubiksCube/). Below, we'll explain the system piece by piece. ⚠️ WARNING: All of the user widget APIs are **unstable** and subject to breaking changes. ## Widget sources and instances A *widget source* is a valid JavaScript [ESModule](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules) which exports a [React component](https://reactjs.org/docs/components-and-props.html). To access React, the module must use `import * as React from 'react'`. Our first example of a widget source is of course the value of `helloWidget.javascript`. We can register a widget source with the `@[widget]` attribute, giving it a friendlier name in the `name` field. This is bundled together in a `UserWidgetDefinition`. A *widget instance* is then the identifier of a `UserWidgetDefinition` (so `` `helloWidget ``, not `"Hello"`) associated with a range of positions in the Lean source code. Widget instances are stored in the *infotree* in the same manner as other information about the source file such as the type of every expression. In our example, the `#widget` command stores a widget instance with the entire line as its range. We can think of a widget instance as an instruction for the infoview: "when the user places their cursor here, please render the following widget". Every widget instance also contains a `props : Json` value. This value is passed as an argument to the React component. In our first invocation of `#widget`, we set it to `.null`. Try out what happens when you type in: -/ #widget helloWidget (Json.mkObj [("name", "<your name here>")]) /-! 💡 NOTE: The RPC system presented below does not depend on JavaScript. However the primary use case is the web-based infoview in VSCode. ## Querying the Lean server Besides enabling us to create cool client-side visualizations, user widgets come with the ability to communicate with the Lean server. Thanks to this, they have the same metaprogramming capabilities as custom elaborators or the tactic framework. To see this in action, let's implement a `#check` command as a web input form. This example assumes some familiarity with React. The first thing we'll need is to create an *RPC method*. Meaning "Remote Procedure Call", this is basically a Lean function callable from widget code (possibly remotely over the internet). Our method will take in the `name : Name` of a constant in the environment and return its type. By convention, we represent the input data as a `structure`. Since it will be sent over from JavaScript, we need `FromJson` and `ToJson`. We'll see below why the position field is needed. -/ structure GetTypeParams where /-- Name of a constant to get the type of. -/ name : Name /-- Position of our widget instance in the Lean file. -/ pos : Lsp.Position deriving FromJson, ToJson /-! After its arguments, we define the `getType` method. Every RPC method executes in the `RequestM` monad and must return a `RequestTask α` where `α` is its "actual" return type. The `Task` is so that requests can be handled concurrently. A first guess for `α` might be `Expr`. However, expressions in general can be large objects which depend on an `Environment` and `LocalContext`. Thus we cannot directly serialize an `Expr` and send it to the widget. Instead, there are two options: - One is to send a *reference* which points to an object residing on the server. From JavaScript's point of view, references are entirely opaque, but they can be sent back to other RPC methods for further processing. - Two is to pretty-print the expression and send its textual representation called `CodeWithInfos`. This representation contains extra data which the infoview uses for interactivity. We take this strategy here. RPC methods execute in the context of a file, but not any particular `Environment` so they don't know about the available `def`initions and `theorem`s. Thus, we need to pass in a position at which we want to use the local `Environment`. This is why we store it in `GetTypeParams`. The `withWaitFindSnapAtPos` method launches a concurrent computation whose job is to find such an `Environment` and a bit more information for us, in the form of a `snap : Snapshot`. With this in hand, we can call `MetaM` procedures to find out the type of `name` and pretty-print it. -/ open Server RequestM in @[serverRpcMethod] def getType (params : GetTypeParams) : RequestM (RequestTask CodeWithInfos) := withWaitFindSnapAtPos params.pos fun snap => do runTermElabM snap do let name ← resolveGlobalConstNoOverloadCore params.name let some c ← Meta.getConst? name | throwThe RequestError ⟨.invalidParams, s!"no constant named '{name}'"⟩ Widget.ppExprTagged c.type /-! ## Using infoview components Now that we have all we need on the server side, let's write the widget source. By importing `@leanprover/infoview`, widgets can render UI components used to implement the infoview itself. For example, the `<InteractiveCode>` component displays expressions with `term : type` tooltips as seen in the goal view. We will use it to implement our custom `#check` display. ⚠️ WARNING: Like the other widget APIs, the infoview JS API is **unstable** and subject to breaking changes. The code below demonstrates useful parts of the API. To make RPC method calls, we use the `RpcContext`. The `useAsync` helper packs the results of a call into a `status` enum, the returned `val`ue in case the call was successful, and otherwise an `err`or. Based on the `status` we either display an `InteractiveCode`, or `mapRpcError` the error in order to turn it into a readable message. -/ @[widget] def checkWidget : UserWidgetDefinition where name := "#check as a service" javascript := " import * as React from 'react'; const e = React.createElement; import { RpcContext, InteractiveCode, useAsync, mapRpcError } from '@leanprover/infoview'; export default function(props) { const rs = React.useContext(RpcContext) const [name, setName] = React.useState('getType') const [status, val, err] = useAsync(() => rs.call('getType', { name, pos: props.pos }), [name, rs, props.pos]) const type = status === 'fulfilled' ? val && e(InteractiveCode, {fmt: val}) : status === 'rejected' ? e('p', null, mapRpcError(err).message) : e('p', null, 'Loading..') const onChange = (event) => { setName(event.target.value) } return e('div', null, e('input', { value: name, onChange }), ' : ', type) } " /-! Finally we can try out the widget. -/ #widget checkWidget .null /-! ![`#check` as a service](../images/widgets_caas.png) ## Building widget sources While typing JavaScript inline is fine for a simple example, for real developments we want to use packages from NPM, a proper build system, and JSX. Thus, most actual widget sources are built with Lake and NPM. They consist of multiple files and may import libraries which don't work as ESModules by default. On the other hand a widget source must be a single, self-contained ESModule in the form of a string. Readers familiar with web development may already have guessed that to obtain such a string, we need a *bundler*. Two popular choices are [`rollup.js`](https://rollupjs.org/guide/en/) and [`esbuild`](https://esbuild.github.io/). If we go with `rollup.js`, to make a widget work with the infoview we need to: - Set [`output.format`](https://rollupjs.org/guide/en/#outputformat) to `'es'`. - [Externalize](https://rollupjs.org/guide/en/#external) `react`, `react-dom`, `@leanprover/infoview`. These libraries are already loaded by the infoview so they should not be bundled. In the RubiksCube sample, we provide a working `rollup.js` build configuration in [rollup.config.js](https://github.com/leanprover/lean4-samples/blob/main/RubiksCube/widget/rollup.config.js). -/
9319f94715a85a3103b9932ad9e8399eacbee6f5
82e44445c70db0f03e30d7be725775f122d72f3e
/src/measure_theory/mean_inequalities.lean
01fe604681f096d9400ee128efee1d8b579ae429
[ "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
19,795
lean
/- Copyright (c) 2020 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.integration import analysis.mean_inequalities import measure_theory.special_functions /-! # Mean value inequalities for integrals In this file we prove several inequalities on integrals, notably the Hölder inequality and the Minkowski inequality. The versions for finite sums are in `analysis.mean_inequalities`. ## Main results Hölder's inequality for the Lebesgue integral of `ℝ≥0∞` and `ℝ≥0` functions: we prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in two cases, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0 functions. Minkowski's inequality for the Lebesgue integral of measurable functions with `ℝ≥0∞` values: we prove `(∫ (f + g)^p ∂μ) ^ (1/p) ≤ (∫ f^p ∂μ) ^ (1/p) + (∫ g^p ∂μ) ^ (1/p)` for `1 ≤ p`. -/ section lintegral /-! ### Hölder's inequality for the Lebesgue integral of ℝ≥0∞ and nnreal functions We prove `∫ (f * g) ∂μ ≤ (∫ f^p ∂μ) ^ (1/p) * (∫ g^q ∂μ) ^ (1/q)` for `p`, `q` conjugate real exponents and `α→(e)nnreal` functions in several cases, the first two being useful only to prove the more general results: * `ennreal.lintegral_mul_le_one_of_lintegral_rpow_eq_one` : ℝ≥0∞ functions for which the integrals on the right are equal to 1, * `ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top` : ℝ≥0∞ functions for which the integrals on the right are neither ⊤ nor 0, * `ennreal.lintegral_mul_le_Lp_mul_Lq` : ℝ≥0∞ functions, * `nnreal.lintegral_mul_le_Lp_mul_Lq` : nnreal functions. -/ noncomputable theory open_locale classical big_operators nnreal ennreal open measure_theory variables {α : Type*} [measurable_space α] {μ : measure α} namespace ennreal lemma lintegral_mul_le_one_of_lintegral_rpow_eq_one {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_norm : ∫⁻ a, (f a)^p ∂μ = 1) (hg_norm : ∫⁻ a, (g a)^q ∂μ = 1) : ∫⁻ a, (f * g) a ∂μ ≤ 1 := begin calc ∫⁻ (a : α), ((f * g) a) ∂μ ≤ ∫⁻ (a : α), ((f a)^p / ennreal.of_real p + (g a)^q / ennreal.of_real q) ∂μ : lintegral_mono (λ a, young_inequality (f a) (g a) hpq) ... = 1 : begin simp only [div_eq_mul_inv], rw lintegral_add', { rw [lintegral_mul_const'' _ (hf.pow_const p), lintegral_mul_const'' _ (hg.pow_const q), hf_norm, hg_norm, ← div_eq_mul_inv, ← div_eq_mul_inv, hpq.inv_add_inv_conj_ennreal], }, { exact (hf.pow_const _).mul_const _, }, { exact (hg.pow_const _).mul_const _, }, end end /-- Function multiplied by the inverse of its p-seminorm `(∫⁻ f^p ∂μ) ^ 1/p`-/ def fun_mul_inv_snorm (f : α → ℝ≥0∞) (p : ℝ) (μ : measure α) : α → ℝ≥0∞ := λ a, (f a) * ((∫⁻ c, (f c) ^ p ∂μ) ^ (1 / p))⁻¹ lemma fun_eq_fun_mul_inv_snorm_mul_snorm {p : ℝ} (f : α → ℝ≥0∞) (hf_nonzero : ∫⁻ a, (f a) ^ p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) {a : α} : f a = (fun_mul_inv_snorm f p μ a) * (∫⁻ c, (f c)^p ∂μ)^(1/p) := by simp [fun_mul_inv_snorm, mul_assoc, inv_mul_cancel, hf_nonzero, hf_top] lemma fun_mul_inv_snorm_rpow {p : ℝ} (hp0 : 0 < p) {f : α → ℝ≥0∞} {a : α} : (fun_mul_inv_snorm f p μ a) ^ p = (f a)^p * (∫⁻ c, (f c) ^ p ∂μ)⁻¹ := begin rw [fun_mul_inv_snorm, mul_rpow_of_nonneg _ _ (le_of_lt hp0)], suffices h_inv_rpow : ((∫⁻ (c : α), f c ^ p ∂μ) ^ (1 / p))⁻¹ ^ p = (∫⁻ (c : α), f c ^ p ∂μ)⁻¹, by rw h_inv_rpow, rw [inv_rpow, ← rpow_mul, one_div_mul_cancel hp0.ne', rpow_one] end lemma lintegral_rpow_fun_mul_inv_snorm_eq_one {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hf_top : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) : ∫⁻ c, (fun_mul_inv_snorm f p μ c)^p ∂μ = 1 := begin simp_rw fun_mul_inv_snorm_rpow hp0_lt, rw [lintegral_mul_const'' _ (hf.pow_const p), mul_inv_cancel hf_nonzero hf_top], end /-- Hölder's inequality in case of finite non-zero integrals -/ lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_nontop : ∫⁻ a, (f a)^p ∂μ ≠ ⊤) (hg_nontop : ∫⁻ a, (g a)^q ∂μ ≠ ⊤) (hf_nonzero : ∫⁻ a, (f a)^p ∂μ ≠ 0) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin let npf := (∫⁻ (c : α), (f c) ^ p ∂μ) ^ (1/p), let nqg := (∫⁻ (c : α), (g c) ^ q ∂μ) ^ (1/q), calc ∫⁻ (a : α), (f * g) a ∂μ = ∫⁻ (a : α), ((fun_mul_inv_snorm f p μ * fun_mul_inv_snorm g q μ) a) * (npf * nqg) ∂μ : begin refine lintegral_congr (λ a, _), rw [pi.mul_apply, fun_eq_fun_mul_inv_snorm_mul_snorm f hf_nonzero hf_nontop, fun_eq_fun_mul_inv_snorm_mul_snorm g hg_nonzero hg_nontop, pi.mul_apply], ring, end ... ≤ npf * nqg : begin rw lintegral_mul_const' (npf * nqg) _ (by simp [hf_nontop, hg_nontop, hf_nonzero, hg_nonzero]), nth_rewrite 1 ←one_mul (npf * nqg), refine mul_le_mul _ (le_refl (npf * nqg)), have hf1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.pos hf hf_nonzero hf_nontop, have hg1 := lintegral_rpow_fun_mul_inv_snorm_eq_one hpq.symm.pos hg hg_nonzero hg_nontop, exact lintegral_mul_le_one_of_lintegral_rpow_eq_one hpq (hf.mul_const _) (hg.mul_const _) hf1 hg1, end end lemma ae_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p) {f : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : f =ᵐ[μ] 0 := begin rw lintegral_eq_zero_iff' (hf.pow_const p) at hf_zero, refine filter.eventually.mp hf_zero (filter.eventually_of_forall (λ x, _)), dsimp only, rw [pi.zero_apply, rpow_eq_zero_iff], intro hx, cases hx, { exact hx.left, }, { exfalso, linarith, }, end lemma lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero {p : ℝ} (hp0_lt : 0 < p) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_zero : ∫⁻ a, (f a)^p ∂μ = 0) : ∫⁻ a, (f * g) a ∂μ = 0 := begin rw ←@lintegral_zero_fun α _ μ, refine lintegral_congr_ae _, suffices h_mul_zero : f * g =ᵐ[μ] 0 * g , by rwa zero_mul at h_mul_zero, have hf_eq_zero : f =ᵐ[μ] 0, from ae_eq_zero_of_lintegral_rpow_eq_zero hp0_lt hf hf_zero, exact filter.eventually_eq.mul hf_eq_zero (ae_eq_refl g), end lemma lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top {p q : ℝ} (hp0_lt : 0 < p) (hq0 : 0 ≤ q) {f g : α → ℝ≥0∞} (hf_top : ∫⁻ a, (f a)^p ∂μ = ⊤) (hg_nonzero : ∫⁻ a, (g a)^q ∂μ ≠ 0) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin refine le_trans le_top (le_of_eq _), have hp0_inv_lt : 0 < 1/p, by simp [hp0_lt], rw [hf_top, ennreal.top_rpow_of_pos hp0_inv_lt], simp [hq0, hg_nonzero], end /-- Hölder's inequality for functions `α → ℝ≥0∞`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem lintegral_mul_le_Lp_mul_Lq (μ : measure α) {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^q ∂μ) ^ (1/q) := begin by_cases hf_zero : ∫⁻ a, (f a) ^ p ∂μ = 0, { refine le_trans (le_of_eq _) (zero_le _), exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.pos hf hf_zero, }, by_cases hg_zero : ∫⁻ a, (g a) ^ q ∂μ = 0, { refine le_trans (le_of_eq _) (zero_le _), rw mul_comm, exact lintegral_mul_eq_zero_of_lintegral_rpow_eq_zero hpq.symm.pos hg hg_zero, }, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.pos hpq.symm.nonneg hf_top hg_zero, }, by_cases hg_top : ∫⁻ a, (g a) ^ q ∂μ = ⊤, { rw [mul_comm, mul_comm ((∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p))], exact lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_eq_top hpq.symm.pos hpq.nonneg hg_top hf_zero, }, -- non-⊤ non-zero case exact ennreal.lintegral_mul_le_Lp_mul_Lq_of_ne_zero_of_ne_top hpq hf hg hf_top hg_top hf_zero hg_zero, end lemma lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ < ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ < ⊤) (hp1 : 1 ≤ p) : ∫⁻ a, ((f + g) a) ^ p ∂μ < ⊤ := begin have hp0_lt : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, calc ∫⁻ (a : α), (f a + g a) ^ p ∂μ ≤ ∫⁻ a, ((2:ℝ≥0∞)^(p-1) * (f a) ^ p + (2:ℝ≥0∞)^(p-1) * (g a) ^ p) ∂ μ : begin refine lintegral_mono (λ a, _), dsimp only, have h_zero_lt_half_rpow : (0 : ℝ≥0∞) < (1 / 2) ^ p, { rw [←ennreal.zero_rpow_of_pos hp0_lt], exact ennreal.rpow_lt_rpow (by simp [zero_lt_one]) hp0_lt, }, have h_rw : (1 / 2) ^ p * (2:ℝ≥0∞) ^ (p - 1) = 1 / 2, { rw [sub_eq_add_neg, ennreal.rpow_add _ _ ennreal.two_ne_zero ennreal.coe_ne_top, ←mul_assoc, ←ennreal.mul_rpow_of_nonneg _ _ hp0, one_div, ennreal.inv_mul_cancel ennreal.two_ne_zero ennreal.coe_ne_top, ennreal.one_rpow, one_mul, ennreal.rpow_neg_one], }, rw ←ennreal.mul_le_mul_left (ne_of_lt h_zero_lt_half_rpow).symm _, { rw [mul_add, ← mul_assoc, ← mul_assoc, h_rw, ←ennreal.mul_rpow_of_nonneg _ _ hp0, mul_add], refine ennreal.rpow_arith_mean_le_arith_mean2_rpow (1/2 : ℝ≥0∞) (1/2 : ℝ≥0∞) (f a) (g a) _ hp1, rw [ennreal.div_add_div_same, one_add_one_eq_two, ennreal.div_self ennreal.two_ne_zero ennreal.coe_ne_top], }, { rw ←ennreal.lt_top_iff_ne_top, refine ennreal.rpow_lt_top_of_nonneg hp0 _, rw [one_div, ennreal.inv_ne_top], exact ennreal.two_ne_zero, }, end ... < ⊤ : begin rw [lintegral_add', lintegral_const_mul'' _ (hf.pow_const p), lintegral_const_mul'' _ (hg.pow_const p), ennreal.add_lt_top], { have h_two : (2 : ℝ≥0∞) ^ (p - 1) < ⊤, from ennreal.rpow_lt_top_of_nonneg (by simp [hp1]) ennreal.coe_ne_top, repeat {rw ennreal.mul_lt_top_iff}, simp [hf_top, hg_top, h_two], }, { exact (hf.pow_const _).const_mul _ }, { exact (hg.pow_const _).const_mul _ }, end end lemma lintegral_Lp_mul_le_Lq_mul_Lr {α} [measurable_space α] {p q r : ℝ} (hp0_lt : 0 < p) (hpq : p < q) (hpqr : 1/p = 1/q + 1/r) (μ : measure α) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : (∫⁻ a, ((f * g) a)^p ∂μ) ^ (1/p) ≤ (∫⁻ a, (f a)^q ∂μ) ^ (1/q) * (∫⁻ a, (g a)^r ∂μ) ^ (1/r) := begin have hp0_ne : p ≠ 0, from (ne_of_lt hp0_lt).symm, have hp0 : 0 ≤ p, from le_of_lt hp0_lt, have hq0_lt : 0 < q, from lt_of_le_of_lt hp0 hpq, have hq0_ne : q ≠ 0, from (ne_of_lt hq0_lt).symm, have h_one_div_r : 1/r = 1/p - 1/q, by simp [hpqr], have hr0_ne : r ≠ 0, { have hr_inv_pos : 0 < 1/r, by rwa [h_one_div_r, sub_pos, one_div_lt_one_div hq0_lt hp0_lt], rw [one_div, _root_.inv_pos] at hr_inv_pos, exact (ne_of_lt hr_inv_pos).symm, }, let p2 := q/p, let q2 := p2.conjugate_exponent, have hp2q2 : p2.is_conjugate_exponent q2, from real.is_conjugate_exponent_conjugate_exponent (by simp [lt_div_iff, hpq, hp0_lt]), calc (∫⁻ (a : α), ((f * g) a) ^ p ∂μ) ^ (1 / p) = (∫⁻ (a : α), (f a)^p * (g a)^p ∂μ) ^ (1 / p) : by simp_rw [pi.mul_apply, ennreal.mul_rpow_of_nonneg _ _ hp0] ... ≤ ((∫⁻ a, (f a)^(p * p2) ∂ μ)^(1/p2) * (∫⁻ a, (g a)^(p * q2) ∂ μ)^(1/q2)) ^ (1/p) : begin refine ennreal.rpow_le_rpow _ (by simp [hp0]), simp_rw ennreal.rpow_mul, exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hp2q2 (hf.pow_const _) (hg.pow_const _) end ... = (∫⁻ (a : α), (f a) ^ q ∂μ) ^ (1 / q) * (∫⁻ (a : α), (g a) ^ r ∂μ) ^ (1 / r) : begin rw [@ennreal.mul_rpow_of_nonneg _ _ (1/p) (by simp [hp0]), ←ennreal.rpow_mul, ←ennreal.rpow_mul], have hpp2 : p * p2 = q, { symmetry, rw [mul_comm, ←div_eq_iff hp0_ne], }, have hpq2 : p * q2 = r, { rw [← inv_inv' r, ← one_div, ← one_div, h_one_div_r], field_simp [q2, real.conjugate_exponent, p2, hp0_ne, hq0_ne] }, simp_rw [div_mul_div, mul_one, mul_comm p2, mul_comm q2, hpp2, hpq2], end end lemma lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, (f a) * (g a) ^ (p - 1) ∂μ ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) * (∫⁻ a, (g a)^p ∂μ) ^ (1/q) := begin refine le_trans (ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf (hg.pow_const _)) _, by_cases hf_zero_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) = 0, { rw [hf_zero_rpow, zero_mul], exact zero_le _, }, have hf_top_rpow : (∫⁻ (a : α), (f a) ^ p ∂μ) ^ (1 / p) ≠ ⊤, { by_contra h, push_neg at h, refine hf_top _, have hp_not_neg : ¬ p < 0, by simp [hpq.nonneg], simpa [hpq.pos, hp_not_neg] using h, }, refine (ennreal.mul_le_mul_left hf_zero_rpow hf_top_rpow).mpr (le_of_eq _), congr, ext1 a, rw [←ennreal.rpow_mul, hpq.sub_one_mul_conj], end lemma lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) : ∫⁻ a, ((f + g) a)^p ∂ μ ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) := begin calc ∫⁻ a, ((f+g) a) ^ p ∂μ ≤ ∫⁻ a, ((f + g) a) * ((f + g) a) ^ (p - 1) ∂μ : begin refine lintegral_mono (λ a, _), dsimp only, by_cases h_zero : (f + g) a = 0, { rw [h_zero, ennreal.zero_rpow_of_pos hpq.pos], exact zero_le _, }, by_cases h_top : (f + g) a = ⊤, { rw [h_top, ennreal.top_rpow_of_pos hpq.sub_one_pos, ennreal.top_mul_top], exact le_top, }, refine le_of_eq _, nth_rewrite 1 ←ennreal.rpow_one ((f + g) a), rw [←ennreal.rpow_add _ _ h_zero h_top, add_sub_cancel'_right], end ... = ∫⁻ (a : α), f a * (f + g) a ^ (p - 1) ∂μ + ∫⁻ (a : α), g a * (f + g) a ^ (p - 1) ∂μ : begin have h_add_m : ae_measurable (λ (a : α), ((f + g) a) ^ (p-1)) μ, from (hf.add hg).pow_const _, have h_add_apply : ∫⁻ (a : α), (f + g) a * (f + g) a ^ (p - 1) ∂μ = ∫⁻ (a : α), (f a + g a) * (f + g) a ^ (p - 1) ∂μ, from rfl, simp_rw [h_add_apply, add_mul], rw lintegral_add' (hf.mul h_add_m) (hg.mul h_add_m), end ... ≤ ((∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p)) * (∫⁻ a, (f a + g a)^p ∂μ) ^ (1/q) : begin rw add_mul, exact add_le_add (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hf (hf.add hg) hf_top) (lintegral_mul_rpow_le_lintegral_rpow_mul_lintegral_rpow hpq hg (hf.add hg) hg_top), end end private lemma lintegral_Lp_add_le_aux {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hf_top : ∫⁻ a, (f a) ^ p ∂μ ≠ ⊤) (hg : ae_measurable g μ) (hg_top : ∫⁻ a, (g a) ^ p ∂μ ≠ ⊤) (h_add_zero : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ 0) (h_add_top : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_not_nonpos : ¬ p ≤ 0, by simp [hpq.pos], have htop_rpow : (∫⁻ a, ((f+g) a) ^ p ∂μ)^(1/p) ≠ ⊤, { by_contra h, push_neg at h, exact h_add_top (@ennreal.rpow_eq_top_of_nonneg _ (1/p) (by simp [hpq.nonneg]) h), }, have h0_rpow : (∫⁻ a, ((f+g) a) ^ p ∂ μ) ^ (1/p) ≠ 0, by simp [h_add_zero, h_add_top, hpq.nonneg, hp_not_nonpos, -pi.add_apply], suffices h : 1 ≤ (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ -(1/p) * ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)), by rwa [←mul_le_mul_left h0_rpow htop_rpow, ←mul_assoc, ←rpow_add _ _ h_add_zero h_add_top, ←sub_eq_add_neg, _root_.sub_self, rpow_zero, one_mul, mul_one] at h, have h : ∫⁻ (a : α), ((f+g) a)^p ∂μ ≤ ((∫⁻ (a : α), (f a)^p ∂μ) ^ (1/p) + (∫⁻ (a : α), (g a)^p ∂μ) ^ (1/p)) * (∫⁻ (a : α), ((f+g) a)^p ∂μ) ^ (1/q), from lintegral_rpow_add_le_add_snorm_mul_lintegral_rpow_add hpq hf hf_top hg hg_top, have h_one_div_q : 1/q = 1 - 1/p, by { nth_rewrite 1 ←hpq.inv_add_inv_conj, ring, }, simp_rw [h_one_div_q, sub_eq_add_neg 1 (1/p), ennreal.rpow_add _ _ h_add_zero h_add_top, rpow_one] at h, nth_rewrite 1 mul_comm at h, nth_rewrite 0 ←one_mul (∫⁻ (a : α), ((f+g) a) ^ p ∂μ) at h, rwa [←mul_assoc, ennreal.mul_le_mul_right h_add_zero h_add_top, mul_comm] at h, end /-- Minkowski's inequality for functions `α → ℝ≥0∞`: the `ℒp` seminorm of the sum of two functions is bounded by the sum of their `ℒp` seminorms. -/ theorem lintegral_Lp_add_le {p : ℝ} {f g : α → ℝ≥0∞} (hf : ae_measurable f μ) (hg : ae_measurable g μ) (hp1 : 1 ≤ p) : (∫⁻ a, ((f + g) a)^p ∂ μ) ^ (1/p) ≤ (∫⁻ a, (f a)^p ∂μ) ^ (1/p) + (∫⁻ a, (g a)^p ∂μ) ^ (1/p) := begin have hp_pos : 0 < p, from lt_of_lt_of_le zero_lt_one hp1, by_cases hf_top : ∫⁻ a, (f a) ^ p ∂μ = ⊤, { simp [hf_top, hp_pos], }, by_cases hg_top : ∫⁻ a, (g a) ^ p ∂μ = ⊤, { simp [hg_top, hp_pos], }, by_cases h1 : p = 1, { refine le_of_eq _, simp_rw [h1, one_div_one, ennreal.rpow_one], exact lintegral_add' hf hg, }, have hp1_lt : 1 < p, by { refine lt_of_le_of_ne hp1 _, symmetry, exact h1, }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp1_lt, by_cases h0 : ∫⁻ a, ((f+g) a) ^ p ∂ μ = 0, { rw [h0, @ennreal.zero_rpow_of_pos (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1])], exact zero_le _, }, have htop : ∫⁻ a, ((f+g) a) ^ p ∂ μ ≠ ⊤, { rw ←ne.def at hf_top hg_top, rw ←ennreal.lt_top_iff_ne_top at hf_top hg_top ⊢, exact lintegral_rpow_add_lt_top_of_lintegral_rpow_lt_top hf hf_top hg hg_top hp1, }, exact lintegral_Lp_add_le_aux hpq hf hf_top hg hg_top h0 htop, end end ennreal /-- Hölder's inequality for functions `α → ℝ≥0`. The integral of the product of two functions is bounded by the product of their `ℒp` and `ℒq` seminorms when `p` and `q` are conjugate exponents. -/ theorem nnreal.lintegral_mul_le_Lp_mul_Lq {p q : ℝ} (hpq : p.is_conjugate_exponent q) {f g : α → ℝ≥0} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ∫⁻ a, (f * g) a ∂μ ≤ (∫⁻ a, (f a)^p ∂μ)^(1/p) * (∫⁻ a, (g a)^q ∂μ)^(1/q) := begin simp_rw [pi.mul_apply, ennreal.coe_mul], exact ennreal.lintegral_mul_le_Lp_mul_Lq μ hpq hf.coe_nnreal_ennreal hg.coe_nnreal_ennreal, end end lintegral
19918325f28a00237a33b58779ec2f8966884836
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/arrowDot.lean
327ef9689c539c544aebf2a9c00de4e25c8bc5fe
[ "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
108
lean
def test (f : Nat → Nat) (g : Nat → Nat) := f.comp g $ 10 example : test (·+1) (·*2) = 21 := rfl
80b7f1b478952c8261ccfe41935f2cc7a6fbb2ca
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Prelude.lean
7142f101df04c42186f332f7709a664093f3b6ce
[ "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
73,234
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 -/ prelude universes u v w @[inline] def id {α : Sort u} (a : α) : α := a /- `idRhs` is an auxiliary declaration used to implement "smart unfolding". It is used as a marker. -/ @[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a abbrev Function.comp {α : Sort u} {β : Sort v} {δ : Sort w} (f : β → δ) (g : α → β) : α → δ := fun x => f (g x) abbrev Function.const {α : Sort u} (β : Sort v) (a : α) : β → α := fun x => a @[reducible] def inferInstance {α : Sort u} [i : α] : α := i @[reducible] def inferInstanceAs (α : Sort u) [i : α] : α := i set_option bootstrap.inductiveCheckResultingUniverse false in inductive PUnit : Sort u where | unit : PUnit /-- An abbreviation for `PUnit.{0}`, its most common instantiation. This Type should be preferred over `PUnit` where possible to avoid unnecessary universe parameters. -/ abbrev Unit : Type := PUnit @[matchPattern] abbrev Unit.unit : Unit := PUnit.unit /-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/ unsafe axiom lcProof {α : Prop} : α /-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/ unsafe axiom lcUnreachable {α : Sort u} : α inductive True : Prop where | intro : True inductive False : Prop inductive Empty : Type def Not (a : Prop) : Prop := a → False @[macroInline] def False.elim {C : Sort u} (h : False) : C := False.rec (fun _ => C) h @[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : Not a) : b := False.elim (h₂ h₁) inductive Eq {α : Sort u} (a : α) : α → Prop where | refl {} : Eq a a abbrev Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} (m : motive a) {b : α} (h : Eq a b) : motive b := Eq.rec (motive := fun α _ => motive α) m h @[matchPattern] def rfl {α : Sort u} {a : α} : Eq a a := Eq.refl a @[simp] theorem id_eq (a : α) : Eq (id a) a := rfl theorem Eq.subst {α : Sort u} {motive : α → Prop} {a b : α} (h₁ : Eq a b) (h₂ : motive a) : motive b := Eq.ndrec h₂ h₁ theorem Eq.symm {α : Sort u} {a b : α} (h : Eq a b) : Eq b a := h ▸ rfl theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : Eq a b) (h₂ : Eq b c) : Eq a c := h₂ ▸ h₁ @[macroInline] def cast {α β : Sort u} (h : Eq α β) (a : α) : β := Eq.rec (motive := fun α _ => α) a h theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : Eq a₁ a₂) : Eq (f a₁) (f a₂) := h ▸ rfl theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : Eq f₁ f₂) (h₂ : Eq a₁ a₂) : Eq (f₁ a₁) (f₂ a₂) := h₁ ▸ h₂ ▸ rfl theorem congrFun {α : Sort u} {β : α → Sort v} {f g : (x : α) → β x} (h : Eq f g) (a : α) : Eq (f a) (g a) := h ▸ rfl /- Initialize the Quotient Module, which effectively adds the following definitions: constant Quot {α : Sort u} (r : α → α → Prop) : Sort u constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) : (∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} : (∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q -/ init_quot inductive HEq {α : Sort u} (a : α) : {β : Sort u} → β → Prop where | refl {} : HEq a a @[matchPattern] def HEq.rfl {α : Sort u} {a : α} : HEq a a := HEq.refl a theorem eqOfHEq {α : Sort u} {a a' : α} (h : HEq a a') : Eq a a' := have (α β : Sort u) → (a : α) → (b : β) → HEq a b → (h : Eq α β) → Eq (cast h a) b from fun α β a b h₁ => HEq.rec (motive := fun {β} (b : β) (h : HEq a b) => (h₂ : Eq α β) → Eq (cast h₂ a) b) (fun (h₂ : Eq α α) => rfl) h₁ this α α a a' h rfl structure Prod (α : Type u) (β : Type v) where fst : α snd : β attribute [unbox] Prod /-- Similar to `Prod`, but `α` and `β` can be propositions. We use this Type internally to automatically generate the brecOn recursor. -/ structure PProd (α : Sort u) (β : Sort v) where fst : α snd : β /-- Similar to `Prod`, but `α` and `β` are in the same universe. -/ structure MProd (α β : Type u) where fst : α snd : β structure And (a b : Prop) : Prop where intro :: (left : a) (right : b) inductive Or (a b : Prop) : Prop where | inl (h : a) : Or a b | inr (h : b) : Or a b inductive Bool : Type where | false : Bool | true : Bool export Bool (false true) /- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/ structure Subtype {α : Sort u} (p : α → Prop) where val : α property : p val /-- Gadget for optional parameter support. -/ @[reducible] def optParam (α : Sort u) (default : α) : Sort u := α /-- Gadget for marking output parameters in type classes. -/ @[reducible] def outParam (α : Sort u) : Sort u := α /-- Auxiliary Declaration used to implement the notation (a : α) -/ @[reducible] def typedExpr (α : Sort u) (a : α) : α := a /-- Auxiliary Declaration used to implement the named patterns `x@p` -/ @[reducible] def namedPattern {α : Sort u} (x a : α) : α := a /- Auxiliary axiom used to implement `sorry`. -/ @[extern "lean_sorry", neverExtract] axiom sorryAx (α : Sort u) (synthetic := true) : α theorem eqFalseOfNeTrue : {b : Bool} → Not (Eq b true) → Eq b false | true, h => False.elim (h rfl) | false, h => rfl theorem eqTrueOfNeFalse : {b : Bool} → Not (Eq b false) → Eq b true | true, h => rfl | false, h => False.elim (h rfl) theorem neFalseOfEqTrue : {b : Bool} → Eq b true → Not (Eq b false) | true, _ => fun h => Bool.noConfusion h | false, h => Bool.noConfusion h theorem neTrueOfEqFalse : {b : Bool} → Eq b false → Not (Eq b true) | true, h => Bool.noConfusion h | false, _ => fun h => Bool.noConfusion h class Inhabited (α : Sort u) where mk {} :: (default : α) constant arbitrary [Inhabited α] : α := Inhabited.default instance : Inhabited (Sort u) where default := PUnit instance (α : Sort u) {β : Sort v} [Inhabited β] : Inhabited (α → β) where default := fun _ => arbitrary instance (α : Sort u) {β : α → Sort v} [(a : α) → Inhabited (β a)] : Inhabited ((a : α) → β a) where default := fun _ => arbitrary /-- Universe lifting operation from Sort to Type -/ structure PLift (α : Sort u) : Type u where up :: (down : α) /- Bijection between α and PLift α -/ theorem PLift.upDown {α : Sort u} : ∀ (b : PLift α), Eq (up (down b)) b | up a => rfl theorem PLift.downUp {α : Sort u} (a : α) : Eq (down (up a)) a := rfl /- Pointed types -/ structure PointedType where (type : Type u) (val : type) instance : Inhabited PointedType.{u} where default := { type := PUnit.{u+1}, val := ⟨⟩ } /-- Universe lifting operation -/ structure ULift.{r, s} (α : Type s) : Type (max s r) where up :: (down : α) /- Bijection between α and ULift.{v} α -/ theorem ULift.upDown {α : Type u} : ∀ (b : ULift.{v} α), Eq (up (down b)) b | up a => rfl theorem ULift.downUp {α : Type u} (a : α) : Eq (down (up.{v} a)) a := rfl class inductive Decidable (p : Prop) where | isFalse (h : Not p) : Decidable p | isTrue (h : p) : Decidable p @[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool := Decidable.casesOn (motive := fun _ => Bool) h (fun _ => false) (fun _ => true) export Decidable (isTrue isFalse decide) abbrev DecidablePred {α : Sort u} (r : α → Prop) := (a : α) → Decidable (r a) abbrev DecidableRel {α : Sort u} (r : α → α → Prop) := (a b : α) → Decidable (r a b) abbrev DecidableEq (α : Sort u) := (a b : α) → Decidable (Eq a b) def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (Eq a b) := s a b theorem decideEqTrue : [s : Decidable p] → p → Eq (decide p) true | isTrue _, _ => rfl | isFalse h₁, h₂ => absurd h₂ h₁ theorem decideEqFalse : [s : Decidable p] → Not p → Eq (decide p) false | isTrue h₁, h₂ => absurd h₁ h₂ | isFalse h, _ => rfl theorem ofDecideEqTrue [s : Decidable p] : Eq (decide p) true → p := fun h => match s with | isTrue h₁ => h₁ | isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁)) theorem ofDecideEqFalse [s : Decidable p] : Eq (decide p) false → Not p := fun h => match s with | isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁)) | isFalse h₁ => h₁ @[inline] instance : DecidableEq Bool := fun a b => match a, b with | false, false => isTrue rfl | false, true => isFalse (fun h => Bool.noConfusion h) | true, false => isFalse (fun h => Bool.noConfusion h) | true, true => isTrue rfl class BEq (α : Type u) where beq : α → α → Bool open BEq (beq) instance [DecidableEq α] : BEq α where beq a b := decide (Eq a b) -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] (t : c → α) (e : Not c → α) : α := Decidable.casesOn (motive := fun _ => α) h e t /- if-then-else -/ @[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α := Decidable.casesOn (motive := fun _ => α) h (fun _ => e) (fun _ => t) @[macroInline] instance {p q} [dp : Decidable p] [dq : Decidable q] : Decidable (And p q) := match dp with | isTrue hp => match dq with | isTrue hq => isTrue ⟨hp, hq⟩ | isFalse hq => isFalse (fun h => hq (And.right h)) | isFalse hp => isFalse (fun h => hp (And.left h)) @[macroInline] instance [dp : Decidable p] [dq : Decidable q] : Decidable (Or p q) := match dp with | isTrue hp => isTrue (Or.inl hp) | isFalse hp => match dq with | isTrue hq => isTrue (Or.inr hq) | isFalse hq => isFalse fun h => match h with | Or.inl h => hp h | Or.inr h => hq h instance [dp : Decidable p] : Decidable (Not p) := match dp with | isTrue hp => isFalse (absurd hp) | isFalse hp => isTrue hp /- Boolean operators -/ @[macroInline] def cond {α : Type u} (c : Bool) (x y : α) : α := match c with | true => x | false => y @[macroInline] def or (x y : Bool) : Bool := match x with | true => true | false => y @[macroInline] def and (x y : Bool) : Bool := match x with | false => false | true => y @[inline] def not : Bool → Bool | true => false | false => true inductive Nat where | zero : Nat | succ (n : Nat) : Nat instance : Inhabited Nat where default := Nat.zero /- For numeric literals notation -/ class OfNat (α : Type u) (n : Nat) where ofNat : α @[defaultInstance 100] /- low prio -/ instance (n : Nat) : OfNat Nat n where ofNat := n class HasLessEq (α : Type u) where LessEq : α → α → Prop class HasLess (α : Type u) where Less : α → α → Prop export HasLess (Less) export HasLessEq (LessEq) class HAdd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAdd : α → β → γ class HSub (α : Type u) (β : Type v) (γ : outParam (Type w)) where hSub : α → β → γ class HMul (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMul : α → β → γ class HDiv (α : Type u) (β : Type v) (γ : outParam (Type w)) where hDiv : α → β → γ class HMod (α : Type u) (β : Type v) (γ : outParam (Type w)) where hMod : α → β → γ class HPow (α : Type u) (β : Type v) (γ : outParam (Type w)) where hPow : α → β → γ class HAppend (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAppend : α → β → γ class HOrElse (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOrElse : α → β → γ class HAndThen (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAndThen : α → β → γ class HAnd (α : Type u) (β : Type v) (γ : outParam (Type w)) where hAnd : α → β → γ class HXor (α : Type u) (β : Type v) (γ : outParam (Type w)) where hXor : α → β → γ class HOr (α : Type u) (β : Type v) (γ : outParam (Type w)) where hOr : α → β → γ class HShiftLeft (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftLeft : α → β → γ class HShiftRight (α : Type u) (β : Type v) (γ : outParam (Type w)) where hShiftRight : α → β → γ class Add (α : Type u) where add : α → α → α class Sub (α : Type u) where sub : α → α → α class Mul (α : Type u) where mul : α → α → α class Neg (α : Type u) where neg : α → α class Div (α : Type u) where div : α → α → α class Mod (α : Type u) where mod : α → α → α class Pow (α : Type u) where pow : α → α → α class Append (α : Type u) where append : α → α → α class OrElse (α : Type u) where orElse : α → α → α class AndThen (α : Type u) where andThen : α → α → α class AndOp (α : Type u) where and : α → α → α class Xor (α : Type u) where xor : α → α → α class OrOp (α : Type u) where or : α → α → α class Complement (α : Type u) where complement : α → α class ShiftLeft (α : Type u) where shiftLeft : α → α → α class ShiftRight (α : Type u) where shiftRight : α → α → α @[defaultInstance] instance [Add α] : HAdd α α α where hAdd a b := Add.add a b @[defaultInstance] instance [Sub α] : HSub α α α where hSub a b := Sub.sub a b @[defaultInstance] instance [Mul α] : HMul α α α where hMul a b := Mul.mul a b @[defaultInstance] instance [Div α] : HDiv α α α where hDiv a b := Div.div a b @[defaultInstance] instance [Mod α] : HMod α α α where hMod a b := Mod.mod a b @[defaultInstance] instance [Pow α] : HPow α α α where hPow a b := Pow.pow a b @[defaultInstance] instance [Append α] : HAppend α α α where hAppend a b := Append.append a b @[defaultInstance] instance [OrElse α] : HOrElse α α α where hOrElse a b := OrElse.orElse a b @[defaultInstance] instance [AndThen α] : HAndThen α α α where hAndThen a b := AndThen.andThen a b @[defaultInstance] instance [AndOp α] : HAnd α α α where hAnd a b := AndOp.and a b @[defaultInstance] instance [Xor α] : HXor α α α where hXor a b := Xor.xor a b @[defaultInstance] instance [OrOp α] : HOr α α α where hOr a b := OrOp.or a b @[defaultInstance] instance [ShiftLeft α] : HShiftLeft α α α where hShiftLeft a b := ShiftLeft.shiftLeft a b @[defaultInstance] instance [ShiftRight α] : HShiftRight α α α where hShiftRight a b := ShiftRight.shiftRight a b open HAdd (hAdd) open HMul (hMul) open HPow (hPow) open HAppend (hAppend) @[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := LessEq b a @[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := Less b a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_add"] protected def Nat.add : (@& Nat) → (@& Nat) → Nat | a, Nat.zero => a | a, Nat.succ b => Nat.succ (Nat.add a b) instance : Add Nat where add := Nat.add /- We mark the following definitions as pattern to make sure they can be used in recursive equations, and reduced by the equation Compiler. -/ attribute [matchPattern] Nat.add Add.add HAdd.hAdd Neg.neg set_option bootstrap.genMatcherCode false in @[extern "lean_nat_mul"] protected def Nat.mul : (@& Nat) → (@& Nat) → Nat | a, 0 => 0 | a, Nat.succ b => Nat.add (Nat.mul a b) a instance : Mul Nat where mul := Nat.mul set_option bootstrap.genMatcherCode false in @[extern "lean_nat_pow"] protected def Nat.pow (m : @& Nat) : (@& Nat) → Nat | 0 => 1 | succ n => Nat.mul (Nat.pow m n) m instance : Pow Nat where pow := Nat.pow set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_eq"] def Nat.beq : (@& Nat) → (@& Nat) → Bool | zero, zero => true | zero, succ m => false | succ n, zero => false | succ n, succ m => beq n m theorem Nat.eqOfBeqEqTrue : {n m : Nat} → Eq (beq n m) true → Eq n m | zero, zero, h => rfl | zero, succ m, h => Bool.noConfusion h | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have Eq (beq n m) true from h have Eq n m from eqOfBeqEqTrue this this ▸ rfl theorem Nat.neOfBeqEqFalse : {n m : Nat} → Eq (beq n m) false → Not (Eq n m) | zero, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Nat.noConfusion h₂ | succ n, zero, h₁, h₂ => Nat.noConfusion h₂ | succ n, succ m, h₁, h₂ => have Eq (beq n m) false from h₁ Nat.noConfusion h₂ (fun h₂ => absurd h₂ (neOfBeqEqFalse this)) @[extern "lean_nat_dec_eq"] protected def Nat.decEq (n m : @& Nat) : Decidable (Eq n m) := match h:beq n m with | true => isTrue (eqOfBeqEqTrue h) | false => isFalse (neOfBeqEqFalse h) @[inline] instance : DecidableEq Nat := Nat.decEq set_option bootstrap.genMatcherCode false in @[extern "lean_nat_dec_le"] def Nat.ble : @& Nat → @& Nat → Bool | zero, zero => true | zero, succ m => true | succ n, zero => false | succ n, succ m => ble n m protected def Nat.le (n m : Nat) : Prop := Eq (ble n m) true instance : HasLessEq Nat where LessEq := Nat.le protected def Nat.lt (n m : Nat) : Prop := Nat.le (succ n) m instance : HasLess Nat where Less := Nat.lt theorem Nat.notSuccLeZero : ∀ (n : Nat), LessEq (succ n) 0 → False | 0, h => nomatch h | succ n, h => nomatch h theorem Nat.notLtZero (n : Nat) : Not (Less n 0) := notSuccLeZero n @[extern "lean_nat_dec_le"] instance Nat.decLe (n m : @& Nat) : Decidable (LessEq n m) := decEq (Nat.ble n m) true @[extern "lean_nat_dec_lt"] instance Nat.decLt (n m : @& Nat) : Decidable (Less n m) := decLe (succ n) m theorem Nat.zeroLe : (n : Nat) → LessEq 0 n | zero => rfl | succ n => rfl theorem Nat.succLeSucc {n m : Nat} (h : LessEq n m) : LessEq (succ n) (succ m) := h theorem Nat.zeroLtSucc (n : Nat) : Less 0 (succ n) := succLeSucc (zeroLe n) theorem Nat.leStep : {n m : Nat} → LessEq n m → LessEq n (succ m) | zero, zero, h => rfl | zero, succ n, h => rfl | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h have LessEq n (succ m) from leStep this succLeSucc this protected theorem Nat.leTrans : {n m k : Nat} → LessEq n m → LessEq m k → LessEq n k | zero, m, k, h₁, h₂ => zeroLe _ | succ n, zero, k, h₁, h₂ => Bool.noConfusion h₁ | succ n, succ m, zero, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, succ k, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m k from h₂ show LessEq n k from Nat.leTrans h₁' h₂' protected theorem Nat.ltTrans {n m k : Nat} (h₁ : Less n m) : Less m k → Less n k := Nat.leTrans (leStep h₁) theorem Nat.leSucc : (n : Nat) → LessEq n (succ n) | zero => rfl | succ n => leSucc n theorem Nat.leSuccOfLe {n m : Nat} (h : LessEq n m) : LessEq n (succ m) := Nat.leTrans h (leSucc m) protected theorem Nat.eqOrLtOfLe : {n m: Nat} → LessEq n m → Or (Eq n m) (Less n m) | zero, zero, h => Or.inl rfl | zero, succ n, h => Or.inr (zeroLe n) | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have LessEq n m from h match Nat.eqOrLtOfLe this with | Or.inl h => Or.inl (h ▸ rfl) | Or.inr h => Or.inr (succLeSucc h) protected def Nat.leRefl : (n : Nat) → LessEq n n | zero => rfl | succ n => Nat.leRefl n protected theorem Nat.ltOrGe (n m : Nat) : Or (Less n m) (GreaterEq n m) := match m with | zero => Or.inr (zeroLe n) | succ m => match Nat.ltOrGe n m with | Or.inl h => Or.inl (leSuccOfLe h) | Or.inr h => match Nat.eqOrLtOfLe h with | Or.inl h1 => Or.inl (h1 ▸ Nat.leRefl _) | Or.inr h1 => Or.inr h1 protected theorem Nat.leAntisymm : {n m : Nat} → LessEq n m → LessEq m n → Eq n m | zero, zero, h₁, h₂ => rfl | succ n, zero, h₁, h₂ => Bool.noConfusion h₁ | zero, succ m, h₁, h₂ => Bool.noConfusion h₂ | succ n, succ m, h₁, h₂ => have h₁' : LessEq n m from h₁ have h₂' : LessEq m n from h₂ (Nat.leAntisymm h₁' h₂') ▸ rfl protected theorem Nat.ltOfLeOfNe {n m : Nat} (h₁ : LessEq n m) (h₂ : Not (Eq n m)) : Less n m := match Nat.ltOrGe n m with | Or.inl h₃ => h₃ | Or.inr h₃ => absurd (Nat.leAntisymm h₁ h₃) h₂ set_option bootstrap.genMatcherCode false in @[extern c inline "lean_nat_sub(#1, lean_box(1))"] def Nat.pred : (@& Nat) → Nat | 0 => 0 | succ a => a set_option bootstrap.genMatcherCode false in @[extern "lean_nat_sub"] protected def Nat.sub : (@& Nat) → (@& Nat) → Nat | a, 0 => a | a, succ b => pred (Nat.sub a b) instance : Sub Nat where sub := Nat.sub theorem Nat.predLePred : {n m : Nat} → LessEq n m → LessEq (pred n) (pred m) | zero, zero, h => rfl | zero, succ n, h => zeroLe n | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => h theorem Nat.leOfSuccLeSucc {n m : Nat} : LessEq (succ n) (succ m) → LessEq n m := predLePred theorem Nat.leOfLtSucc {m n : Nat} : Less m (succ n) → LessEq m n := leOfSuccLeSucc @[extern "lean_system_platform_nbits"] constant System.Platform.getNumBits : Unit → Subtype fun (n : Nat) => Or (Eq n 32) (Eq n 64) := fun _ => ⟨64, Or.inr rfl⟩ -- inhabitant def System.Platform.numBits : Nat := (getNumBits ()).val theorem System.Platform.numBitsEq : Or (Eq numBits 32) (Eq numBits 64) := (getNumBits ()).property structure Fin (n : Nat) where val : Nat isLt : Less val n theorem Fin.eqOfVeq {n} : ∀ {i j : Fin n}, Eq i.val j.val → Eq i j | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Fin.veqOfEq {n} {i j : Fin n} (h : Eq i j) : Eq i.val j.val := h ▸ rfl theorem Fin.neOfVne {n} {i j : Fin n} (h : Not (Eq i.val j.val)) : Not (Eq i j) := fun h' => absurd (veqOfEq h') h instance (n : Nat) : DecidableEq (Fin n) := fun i j => match decEq i.val j.val with | isTrue h => isTrue (Fin.eqOfVeq h) | isFalse h => isFalse (Fin.neOfVne h) instance {n} : HasLess (Fin n) where Less a b := Less a.val b.val instance {n} : HasLessEq (Fin n) where LessEq a b := LessEq a.val b.val instance Fin.decLt {n} (a b : Fin n) : Decidable (Less a b) := Nat.decLt .. instance Fin.decLe {n} (a b : Fin n) : Decidable (LessEq a b) := Nat.decLe .. def UInt8.size : Nat := 256 structure UInt8 where val : Fin UInt8.size attribute [extern "lean_uint8_of_nat_mk"] UInt8.mk attribute [extern "lean_uint8_to_nat"] UInt8.val @[extern "lean_uint8_of_nat"] def UInt8.ofNatCore (n : @& Nat) (h : Less n UInt8.size) : UInt8 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt8.decEq (a b : UInt8) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt8.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt8 := UInt8.decEq instance : Inhabited UInt8 where default := UInt8.ofNatCore 0 (by decide) def UInt16.size : Nat := 65536 structure UInt16 where val : Fin UInt16.size attribute [extern "lean_uint16_of_nat_mk"] UInt16.mk attribute [extern "lean_uint16_to_nat"] UInt16.val @[extern "lean_uint16_of_nat"] def UInt16.ofNatCore (n : @& Nat) (h : Less n UInt16.size) : UInt16 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt16.decEq (a b : UInt16) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt16.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt16 := UInt16.decEq instance : Inhabited UInt16 where default := UInt16.ofNatCore 0 (by decide) def UInt32.size : Nat := 4294967296 structure UInt32 where val : Fin UInt32.size attribute [extern "lean_uint32_of_nat_mk"] UInt32.mk attribute [extern "lean_uint32_to_nat"] UInt32.val @[extern "lean_uint32_of_nat"] def UInt32.ofNatCore (n : @& Nat) (h : Less n UInt32.size) : UInt32 := { val := { val := n, isLt := h } } @[extern "lean_uint32_to_nat"] def UInt32.toNat (n : UInt32) : Nat := n.val.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt32.decEq (a b : UInt32) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt32.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt32 := UInt32.decEq instance : Inhabited UInt32 where default := UInt32.ofNatCore 0 (by decide) instance : HasLess UInt32 where Less a b := Less a.val b.val instance : HasLessEq UInt32 where LessEq a b := LessEq a.val b.val set_option bootstrap.genMatcherCode false in @[extern c inline "#1 < #2"] def UInt32.decLt (a b : UInt32) : Decidable (Less a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (Less n m)) set_option bootstrap.genMatcherCode false in @[extern c inline "#1 <= #2"] def UInt32.decLe (a b : UInt32) : Decidable (LessEq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => inferInstanceAs (Decidable (LessEq n m)) instance (a b : UInt32) : Decidable (Less a b) := UInt32.decLt a b instance (a b : UInt32) : Decidable (LessEq a b) := UInt32.decLe a b def UInt64.size : Nat := 18446744073709551616 structure UInt64 where val : Fin UInt64.size attribute [extern "lean_uint64_of_nat_mk"] UInt64.mk attribute [extern "lean_uint64_to_nat"] UInt64.val @[extern "lean_uint64_of_nat"] def UInt64.ofNatCore (n : @& Nat) (h : Less n UInt64.size) : UInt64 := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def UInt64.decEq (a b : UInt64) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h => isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => UInt64.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq UInt64 := UInt64.decEq instance : Inhabited UInt64 where default := UInt64.ofNatCore 0 (by decide) def USize.size : Nat := hPow 2 System.Platform.numBits theorem usizeSzEq : Or (Eq USize.size 4294967296) (Eq USize.size 18446744073709551616) := show Or (Eq (hPow 2 System.Platform.numBits) 4294967296) (Eq (hPow 2 System.Platform.numBits) 18446744073709551616) from match System.Platform.numBits, System.Platform.numBitsEq with | _, Or.inl rfl => Or.inl (by decide) | _, Or.inr rfl => Or.inr (by decide) structure USize where val : Fin USize.size attribute [extern "lean_usize_of_nat_mk"] USize.mk attribute [extern "lean_usize_to_nat"] USize.val @[extern "lean_usize_of_nat"] def USize.ofNatCore (n : @& Nat) (h : Less n USize.size) : USize := { val := { val := n, isLt := h } } set_option bootstrap.genMatcherCode false in @[extern c inline "#1 == #2"] def USize.decEq (a b : USize) : Decidable (Eq a b) := match a, b with | ⟨n⟩, ⟨m⟩ => dite (Eq n m) (fun h =>isTrue (h ▸ rfl)) (fun h => isFalse (fun h' => USize.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq USize := USize.decEq instance : Inhabited USize where default := USize.ofNatCore 0 (match USize.size, usizeSzEq with | _, Or.inl rfl => by decide | _, Or.inr rfl => by decide) @[extern "lean_usize_of_nat"] def USize.ofNat32 (n : @& Nat) (h : Less n 4294967296) : USize := { val := { val := n isLt := match USize.size, usizeSzEq with | _, Or.inl rfl => h | _, Or.inr rfl => Nat.ltTrans h (by decide) } } abbrev Nat.isValidChar (n : Nat) : Prop := Or (Less n 0xd800) (And (Less 0xdfff n) (Less n 0x110000)) abbrev UInt32.isValidChar (n : UInt32) : Prop := n.toNat.isValidChar /-- The `Char` Type represents an unicode scalar value. See http://www.unicode.org/glossary/#unicode_scalar_value). -/ structure Char where val : UInt32 valid : val.isValidChar private theorem validCharIsUInt32 {n : Nat} (h : n.isValidChar) : Less n UInt32.size := match h with | Or.inl h => Nat.ltTrans h (by decide) | Or.inr ⟨_, h⟩ => Nat.ltTrans h (by decide) @[extern "lean_uint32_of_nat"] private def Char.ofNatAux (n : @& Nat) (h : n.isValidChar) : Char := { val := ⟨{ val := n, isLt := validCharIsUInt32 h }⟩, valid := h } @[noinline, matchPattern] def Char.ofNat (n : Nat) : Char := dite (n.isValidChar) (fun h => Char.ofNatAux n h) (fun _ => { val := ⟨{ val := 0, isLt := by decide }⟩, valid := Or.inl (by decide) }) theorem Char.eqOfVeq : ∀ {c d : Char}, Eq c.val d.val → Eq c d | ⟨v, h⟩, ⟨_, _⟩, rfl => rfl theorem Char.veqOfEq : ∀ {c d : Char}, Eq c d → Eq c.val d.val | _, _, rfl => rfl theorem Char.neOfVne {c d : Char} (h : Not (Eq c.val d.val)) : Not (Eq c d) := fun h' => absurd (veqOfEq h') h theorem Char.vneOfNe {c d : Char} (h : Not (Eq c d)) : Not (Eq c.val d.val) := fun h' => absurd (eqOfVeq h') h instance : DecidableEq Char := fun c d => match decEq c.val d.val with | isTrue h => isTrue (Char.eqOfVeq h) | isFalse h => isFalse (Char.neOfVne h) def Char.utf8Size (c : Char) : UInt32 := let v := c.val ite (LessEq v (UInt32.ofNatCore 0x7F (by decide))) (UInt32.ofNatCore 1 (by decide)) (ite (LessEq v (UInt32.ofNatCore 0x7FF (by decide))) (UInt32.ofNatCore 2 (by decide)) (ite (LessEq v (UInt32.ofNatCore 0xFFFF (by decide))) (UInt32.ofNatCore 3 (by decide)) (UInt32.ofNatCore 4 (by decide)))) inductive Option (α : Type u) where | none : Option α | some (val : α) : Option α attribute [unbox] Option export Option (none some) instance {α} : Inhabited (Option α) where default := none inductive List (α : Type u) where | nil : List α | cons (head : α) (tail : List α) : List α instance {α} : Inhabited (List α) where default := List.nil protected def List.hasDecEq {α: Type u} [DecidableEq α] : (a b : List α) → Decidable (Eq a b) | nil, nil => isTrue rfl | cons a as, nil => isFalse (fun h => List.noConfusion h) | nil, cons b bs => isFalse (fun h => List.noConfusion h) | cons a as, cons b bs => match decEq a b with | isTrue hab => match List.hasDecEq as bs with | isTrue habs => isTrue (hab ▸ habs ▸ rfl) | isFalse nabs => isFalse (fun h => List.noConfusion h (fun _ habs => absurd habs nabs)) | isFalse nab => isFalse (fun h => List.noConfusion h (fun hab _ => absurd hab nab)) instance {α : Type u} [DecidableEq α] : DecidableEq (List α) := List.hasDecEq @[specialize] def List.foldl {α β} (f : α → β → α) : (init : α) → List β → α | a, nil => a | a, cons b l => foldl f (f a b) l def List.set : List α → Nat → α → List α | cons a as, 0, b => cons b as | cons a as, Nat.succ n, b => cons a (set as n b) | nil, _, _ => nil def List.lengthAux {α : Type u} : List α → Nat → Nat | nil, n => n | cons a as, n => lengthAux as (Nat.succ n) def List.length {α : Type u} (as : List α) : Nat := lengthAux as 0 @[simp] theorem List.length_cons {α} (a : α) (as : List α) : Eq (cons a as).length as.length.succ := let rec aux (a : α) (as : List α) : (n : Nat) → Eq ((cons a as).lengthAux n) (as.lengthAux n).succ := match as with | nil => fun _ => rfl | cons a as => fun n => aux a as n.succ aux a as 0 def List.concat {α : Type u} : List α → α → List α | nil, b => cons b nil | cons a as, b => cons a (concat as b) def List.get {α : Type u} : (as : List α) → (i : Nat) → Less i as.length → α | nil, i, h => absurd h (Nat.notLtZero _) | cons a as, 0, h => a | cons a as, Nat.succ i, h => have Less i.succ as.length.succ from length_cons .. ▸ h get as i (Nat.leOfSuccLeSucc this) structure String where data : List Char attribute [extern "lean_string_mk"] String.mk attribute [extern "lean_string_data"] String.data @[extern "lean_string_dec_eq"] def String.decEq (s₁ s₂ : @& String) : Decidable (Eq s₁ s₂) := match s₁, s₂ with | ⟨s₁⟩, ⟨s₂⟩ => dite (Eq s₁ s₂) (fun h => isTrue (congrArg _ h)) (fun h => isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))) instance : DecidableEq String := String.decEq /-- A byte position in a `String`. Internally, `String`s are UTF-8 encoded. Codepoint positions (counting the Unicode codepoints rather than bytes) are represented by plain `Nat`s instead. Indexing a `String` by a byte position is constant-time, while codepoint positions need to be translated internally to byte positions in linear-time. -/ abbrev String.Pos := Nat structure Substring where str : String startPos : String.Pos stopPos : String.Pos @[inline] def Substring.bsize : Substring → Nat | ⟨_, b, e⟩ => e.sub b def String.csize (c : Char) : Nat := c.utf8Size.toNat private def String.utf8ByteSizeAux : List Char → Nat → Nat | List.nil, r => r | List.cons c cs, r => utf8ByteSizeAux cs (hAdd r (csize c)) @[extern "lean_string_utf8_byte_size"] def String.utf8ByteSize : (@& String) → Nat | ⟨s⟩ => utf8ByteSizeAux s 0 @[inline] def String.bsize (s : String) : Nat := utf8ByteSize s @[inline] def String.toSubstring (s : String) : Substring := { str := s startPos := 0 stopPos := s.bsize } @[extern c inline "#3"] unsafe def unsafeCast {α : Type u} {β : Type v} (a : α) : β := cast lcProof (PUnit.{v}) @[neverExtract, extern "lean_panic_fn"] constant panic {α : Type u} [Inhabited α] (msg : String) : α /- The Compiler has special support for arrays. They are implemented using dynamic arrays: https://en.wikipedia.org/wiki/Dynamic_array -/ structure Array (α : Type u) where data : List α attribute [extern "lean_array_data"] Array.data attribute [extern "lean_array_mk"] Array.mk /- The parameter `c` is the initial capacity -/ @[extern "lean_mk_empty_array_with_capacity"] def Array.mkEmpty {α : Type u} (c : @& Nat) : Array α := { data := List.nil } def Array.empty {α : Type u} : Array α := mkEmpty 0 @[reducible, extern "lean_array_get_size"] def Array.size {α : Type u} (a : @& Array α) : Nat := a.data.length @[extern "lean_array_fget"] def Array.get {α : Type u} (a : @& Array α) (i : @& Fin a.size) : α := a.data.get i.val i.isLt @[inline] def Array.getD (a : Array α) (i : Nat) (v₀ : α) : α := dite (Less i a.size) (fun h => a.get ⟨i, h⟩) (fun _ => v₀) /- "Comfortable" version of `fget`. It performs a bound check at runtime. -/ @[extern "lean_array_get"] def Array.get! {α : Type u} [Inhabited α] (a : @& Array α) (i : @& Nat) : α := Array.getD a i arbitrary def Array.getOp {α : Type u} [Inhabited α] (self : Array α) (idx : Nat) : α := self.get! idx @[extern "lean_array_push"] def Array.push {α : Type u} (a : Array α) (v : α) : Array α := { data := List.concat a.data v } @[extern "lean_array_fset"] def Array.set (a : Array α) (i : @& Fin a.size) (v : α) : Array α := { data := a.data.set i.val v } @[inline] def Array.setD (a : Array α) (i : Nat) (v : α) : Array α := dite (Less i a.size) (fun h => a.set ⟨i, h⟩ v) (fun _ => a) @[extern "lean_array_set"] def Array.set! (a : Array α) (i : @& Nat) (v : α) : Array α := Array.setD a i v -- Slower `Array.append` used in quotations. protected def Array.appendCore {α : Type u} (as : Array α) (bs : Array α) : Array α := let rec loop (i : Nat) (j : Nat) (as : Array α) : Array α := dite (Less j bs.size) (fun hlt => match i with | 0 => as | Nat.succ i' => loop i' (hAdd j 1) (as.push (bs.get ⟨j, hlt⟩))) (fun _ => as) loop bs.size 0 as class Bind (m : Type u → Type v) where bind : {α β : Type u} → m α → (α → m β) → m β export Bind (bind) class Pure (f : Type u → Type v) where pure {α : Type u} : α → f α export Pure (pure) class Functor (f : Type u → Type v) : Type (max (u+1) v) where map : {α β : Type u} → (α → β) → f α → f β mapConst : {α β : Type u} → α → f β → f α := Function.comp map (Function.const _) class Seq (f : Type u → Type v) : Type (max (u+1) v) where seq : {α β : Type u} → f (α → β) → f α → f β class SeqLeft (f : Type u → Type v) : Type (max (u+1) v) where seqLeft : {α β : Type u} → f α → f β → f α class SeqRight (f : Type u → Type v) : Type (max (u+1) v) where seqRight : {α β : Type u} → f α → f β → f β class Applicative (f : Type u → Type v) extends Functor f, Pure f, Seq f, SeqLeft f, SeqRight f where map := fun x y => Seq.seq (pure x) y seqLeft := fun a b => Seq.seq (Functor.map (Function.const _) a) b seqRight := fun a b => Seq.seq (Functor.map (Function.const _ id) a) b class Monad (m : Type u → Type v) extends Applicative m, Bind m : Type (max (u+1) v) where map f x := bind x (Function.comp pure f) seq f x := bind f fun y => Functor.map y x seqLeft x y := bind x fun a => bind y (fun _ => pure a) seqRight x y := bind x fun _ => y instance {α : Type u} {m : Type u → Type v} [Monad m] : Inhabited (α → m α) where default := pure instance {α : Type u} {m : Type u → Type v} [Monad m] [Inhabited α] : Inhabited (m α) where default := pure arbitrary -- A fusion of Haskell's `sequence` and `map` def Array.sequenceMap {α : Type u} {β : Type v} {m : Type v → Type w} [Monad m] (as : Array α) (f : α → m β) : m (Array β) := let rec loop (i : Nat) (j : Nat) (bs : Array β) : m (Array β) := dite (Less j as.size) (fun hlt => match i with | 0 => pure bs | Nat.succ i' => Bind.bind (f (as.get ⟨j, hlt⟩)) fun b => loop i' (hAdd j 1) (bs.push b)) (fun _ => bs) loop as.size 0 Array.empty /-- A Function for lifting a computation from an inner Monad to an outer Monad. Like [MonadTrans](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Class.html), but `n` does not have to be a monad transformer. Alternatively, an implementation of [MonadLayer](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLayer) without `layerInvmap` (so far). -/ class MonadLift (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α /-- The reflexive-transitive closure of `MonadLift`. `monadLift` is used to transitively lift monadic computations such as `StateT.get` or `StateT.put s`. Corresponds to [MonadLift](https://hackage.haskell.org/package/layers-0.1/docs/Control-Monad-Layer.html#t:MonadLift). -/ class MonadLiftT (m : Type u → Type v) (n : Type u → Type w) where monadLift : {α : Type u} → m α → n α export MonadLiftT (monadLift) abbrev liftM := @monadLift instance (m n o) [MonadLift n o] [MonadLiftT m n] : MonadLiftT m o where monadLift x := MonadLift.monadLift (m := n) (monadLift x) instance (m) : MonadLiftT m m where monadLift x := x /-- A functor in the category of monads. Can be used to lift monad-transforming functions. Based on pipes' [MFunctor](https://hackage.haskell.org/package/pipes-2.4.0/docs/Control-MFunctor.html), but not restricted to monad transformers. Alternatively, an implementation of [MonadTransFunctor](http://duairc.netsoc.ie/layers-docs/Control-Monad-Layer.html#t:MonadTransFunctor). -/ class MonadFunctor (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α /-- The reflexive-transitive closure of `MonadFunctor`. `monadMap` is used to transitively lift Monad morphisms -/ class MonadFunctorT (m : Type u → Type v) (n : Type u → Type w) where monadMap {α : Type u} : ({β : Type u} → m β → m β) → n α → n α export MonadFunctorT (monadMap) instance (m n o) [MonadFunctor n o] [MonadFunctorT m n] : MonadFunctorT m o where monadMap f := MonadFunctor.monadMap (m := n) (monadMap (m := m) f) instance monadFunctorRefl (m) : MonadFunctorT m m where monadMap f := f inductive Except (ε : Type u) (α : Type v) where | error : ε → Except ε α | ok : α → Except ε α attribute [unbox] Except instance {ε : Type u} {α : Type v} [Inhabited ε] : Inhabited (Except ε α) where default := Except.error arbitrary /-- An implementation of [MonadError](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Except.html#t:MonadError) -/ class MonadExceptOf (ε : Type u) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α abbrev throwThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (e : ε) : m α := MonadExceptOf.throw e abbrev tryCatchThe (ε : Type u) {m : Type v → Type w} [MonadExceptOf ε m] {α : Type v} (x : m α) (handle : ε → m α) : m α := MonadExceptOf.tryCatch x handle /-- Similar to `MonadExceptOf`, but `ε` is an outParam for convenience -/ class MonadExcept (ε : outParam (Type u)) (m : Type v → Type w) where throw {α : Type v} : ε → m α tryCatch {α : Type v} : m α → (ε → m α) → m α export MonadExcept (throw tryCatch) instance (ε : outParam (Type u)) (m : Type v → Type w) [MonadExceptOf ε m] : MonadExcept ε m where throw := throwThe ε tryCatch := tryCatchThe ε namespace MonadExcept variable {ε : Type u} {m : Type v → Type w} @[inline] protected def orelse [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) : m α := tryCatch t₁ fun _ => t₂ instance [MonadExcept ε m] {α : Type v} : OrElse (m α) where orElse := MonadExcept.orelse end MonadExcept /-- An implementation of [ReaderT](https://hackage.haskell.org/package/transformers-0.5.5.0/docs/Control-Monad-Trans-Reader.html#t:ReaderT) -/ def ReaderT (ρ : Type u) (m : Type u → Type v) (α : Type u) : Type (max u v) := ρ → m α instance (ρ : Type u) (m : Type u → Type v) (α : Type u) [Inhabited (m α)] : Inhabited (ReaderT ρ m α) where default := fun _ => arbitrary @[inline] def ReaderT.run {ρ : Type u} {m : Type u → Type v} {α : Type u} (x : ReaderT ρ m α) (r : ρ) : m α := x r namespace ReaderT section variable {ρ : Type u} {m : Type u → Type v} {α : Type u} instance : MonadLift m (ReaderT ρ m) where monadLift x := fun _ => x instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (ReaderT ρ m) where throw e := liftM (m := m) (throw e) tryCatch := fun x c r => tryCatchThe ε (x r) (fun e => (c e) r) end section variable {ρ : Type u} {m : Type u → Type v} [Monad m] {α β : Type u} @[inline] protected def read : ReaderT ρ m ρ := pure @[inline] protected def pure (a : α) : ReaderT ρ m α := fun r => pure a @[inline] protected def bind (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) : ReaderT ρ m β := fun r => bind (x r) fun a => f a r @[inline] protected def map (f : α → β) (x : ReaderT ρ m α) : ReaderT ρ m β := fun r => Functor.map f (x r) instance : Monad (ReaderT ρ m) where pure := ReaderT.pure bind := ReaderT.bind map := ReaderT.map instance (ρ m) [Monad m] : MonadFunctor m (ReaderT ρ m) where monadMap f x := fun ctx => f (x ctx) @[inline] protected def adapt {ρ' : Type u} [Monad m] {α : Type u} (f : ρ' → ρ) : ReaderT ρ m α → ReaderT ρ' m α := fun x r => x (f r) end end ReaderT /-- An implementation of [MonadReader](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Reader-Class.html#t:MonadReader). It does not contain `local` because this Function cannot be lifted using `monadLift`. Instead, the `MonadReaderAdapter` class provides the more general `adaptReader` Function. Note: This class can be seen as a simplification of the more "principled" definition ``` class MonadReader (ρ : outParam (Type u)) (n : Type u → Type u) where lift {α : Type u} : ({m : Type u → Type u} → [Monad m] → ReaderT ρ m α) → n α ``` -/ class MonadReaderOf (ρ : Type u) (m : Type u → Type v) where read : m ρ @[inline] def readThe (ρ : Type u) {m : Type u → Type v} [MonadReaderOf ρ m] : m ρ := MonadReaderOf.read /-- Similar to `MonadReaderOf`, but `ρ` is an outParam for convenience -/ class MonadReader (ρ : outParam (Type u)) (m : Type u → Type v) where read : m ρ export MonadReader (read) instance (ρ : Type u) (m : Type u → Type v) [MonadReaderOf ρ m] : MonadReader ρ m where read := readThe ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadReaderOf ρ m] : MonadReaderOf ρ n where read := liftM (m := m) read instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadReaderOf ρ (ReaderT ρ m) where read := ReaderT.read class MonadWithReaderOf (ρ : Type u) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α @[inline] def withTheReader (ρ : Type u) {m : Type u → Type v} [MonadWithReaderOf ρ m] {α : Type u} (f : ρ → ρ) (x : m α) : m α := MonadWithReaderOf.withReader f x class MonadWithReader (ρ : outParam (Type u)) (m : Type u → Type v) where withReader {α : Type u} : (ρ → ρ) → m α → m α export MonadWithReader (withReader) instance (ρ : Type u) (m : Type u → Type v) [MonadWithReaderOf ρ m] : MonadWithReader ρ m where withReader := withTheReader ρ instance {ρ : Type u} {m : Type u → Type v} {n : Type u → Type v} [MonadFunctor m n] [MonadWithReaderOf ρ m] : MonadWithReaderOf ρ n where withReader f := monadMap (m := m) (withTheReader ρ f) instance {ρ : Type u} {m : Type u → Type v} [Monad m] : MonadWithReaderOf ρ (ReaderT ρ m) where withReader f x := fun ctx => x (f ctx) /-- An implementation of [MonadState](https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Class.html). In contrast to the Haskell implementation, we use overlapping instances to derive instances automatically from `monadLift`. -/ class MonadStateOf (σ : Type u) (m : Type u → Type v) where /- Obtain the top-most State of a Monad stack. -/ get : m σ /- Set the top-most State of a Monad stack. -/ set : σ → m PUnit /- Map the top-most State of a Monad stack. Note: `modifyGet f` may be preferable to `do s <- get; let (a, s) := f s; put s; pure a` because the latter does not use the State linearly (without sufficient inlining). -/ modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadStateOf (set) abbrev getThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] : m σ := MonadStateOf.get @[inline] abbrev modifyThe (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → σ) : m PUnit := MonadStateOf.modifyGet fun s => (PUnit.unit, f s) @[inline] abbrev modifyGetThe {α : Type u} (σ : Type u) {m : Type u → Type v} [MonadStateOf σ m] (f : σ → Prod α σ) : m α := MonadStateOf.modifyGet f /-- Similar to `MonadStateOf`, but `σ` is an outParam for convenience -/ class MonadState (σ : outParam (Type u)) (m : Type u → Type v) where get : m σ set : σ → m PUnit modifyGet {α : Type u} : (σ → Prod α σ) → m α export MonadState (get modifyGet) instance (σ : Type u) (m : Type u → Type v) [MonadStateOf σ m] : MonadState σ m where set := MonadStateOf.set get := getThe σ modifyGet f := MonadStateOf.modifyGet f @[inline] def modify {σ : Type u} {m : Type u → Type v} [MonadState σ m] (f : σ → σ) : m PUnit := modifyGet fun s => (PUnit.unit, f s) @[inline] def getModify {σ : Type u} {m : Type u → Type v} [MonadState σ m] [Monad m] (f : σ → σ) : m σ := modifyGet fun s => (s, f s) -- NOTE: The Ordering of the following two instances determines that the top-most `StateT` Monad layer -- will be picked first instance {σ : Type u} {m : Type u → Type v} {n : Type u → Type w} [MonadLift m n] [MonadStateOf σ m] : MonadStateOf σ n where get := liftM (m := m) MonadStateOf.get set s := liftM (m := m) (MonadStateOf.set s) modifyGet f := monadLift (m := m) (MonadState.modifyGet f) namespace EStateM inductive Result (ε σ α : Type u) where | ok : α → σ → Result ε σ α | error : ε → σ → Result ε σ α variable {ε σ α : Type u} instance [Inhabited ε] [Inhabited σ] : Inhabited (Result ε σ α) where default := Result.error arbitrary arbitrary end EStateM open EStateM (Result) in def EStateM (ε σ α : Type u) := σ → Result ε σ α namespace EStateM variable {ε σ α β : Type u} instance [Inhabited ε] : Inhabited (EStateM ε σ α) where default := fun s => Result.error arbitrary s @[inline] protected def pure (a : α) : EStateM ε σ α := fun s => Result.ok a s @[inline] protected def set (s : σ) : EStateM ε σ PUnit := fun _ => Result.ok ⟨⟩ s @[inline] protected def get : EStateM ε σ σ := fun s => Result.ok s s @[inline] protected def modifyGet (f : σ → Prod α σ) : EStateM ε σ α := fun s => match f s with | (a, s) => Result.ok a s @[inline] protected def throw (e : ε) : EStateM ε σ α := fun s => Result.error e s /-- Auxiliary instance for saving/restoring the "backtrackable" part of the state. -/ class Backtrackable (δ : outParam (Type u)) (σ : Type u) where save : σ → δ restore : σ → δ → σ @[inline] protected def tryCatch {δ} [Backtrackable δ σ] {α} (x : EStateM ε σ α) (handle : ε → EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s match x s with | Result.error e s => handle e (Backtrackable.restore s d) | ok => ok @[inline] protected def orElse {δ} [Backtrackable δ σ] (x₁ x₂ : EStateM ε σ α) : EStateM ε σ α := fun s => let d := Backtrackable.save s; match x₁ s with | Result.error _ s => x₂ (Backtrackable.restore s d) | ok => ok @[inline] def adaptExcept {ε' : Type u} (f : ε → ε') (x : EStateM ε σ α) : EStateM ε' σ α := fun s => match x s with | Result.error e s => Result.error (f e) s | Result.ok a s => Result.ok a s @[inline] protected def bind (x : EStateM ε σ α) (f : α → EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok a s => f a s | Result.error e s => Result.error e s @[inline] protected def map (f : α → β) (x : EStateM ε σ α) : EStateM ε σ β := fun s => match x s with | Result.ok a s => Result.ok (f a) s | Result.error e s => Result.error e s @[inline] protected def seqRight (x : EStateM ε σ α) (y : EStateM ε σ β) : EStateM ε σ β := fun s => match x s with | Result.ok _ s => y s | Result.error e s => Result.error e s instance : Monad (EStateM ε σ) where bind := EStateM.bind pure := EStateM.pure map := EStateM.map seqRight := EStateM.seqRight instance {δ} [Backtrackable δ σ] : OrElse (EStateM ε σ α) where orElse := EStateM.orElse instance : MonadStateOf σ (EStateM ε σ) where set := EStateM.set get := EStateM.get modifyGet := EStateM.modifyGet instance {δ} [Backtrackable δ σ] : MonadExceptOf ε (EStateM ε σ) where throw := EStateM.throw tryCatch := EStateM.tryCatch @[inline] def run (x : EStateM ε σ α) (s : σ) : Result ε σ α := x s @[inline] def run' (x : EStateM ε σ α) (s : σ) : Option α := match run x s with | Result.ok v _ => some v | Result.error .. => none @[inline] def dummySave : σ → PUnit := fun _ => ⟨⟩ @[inline] def dummyRestore : σ → PUnit → σ := fun s _ => s /- Dummy default instance -/ instance nonBacktrackable : Backtrackable PUnit σ where save := dummySave restore := dummyRestore end EStateM class Hashable (α : Sort u) where hash : α → USize export Hashable (hash) @[extern "lean_usize_mix_hash"] constant mixHash (u₁ u₂ : USize) : USize @[extern "lean_string_hash"] protected constant String.hash (s : @& String) : USize instance : Hashable String where hash := String.hash namespace Lean /- Hierarchical names -/ inductive Name where | anonymous : Name | str : Name → String → USize → Name | num : Name → Nat → USize → Name instance : Inhabited Name where default := Name.anonymous protected def Name.hash : Name → USize | Name.anonymous => USize.ofNat32 1723 (by decide) | Name.str p s h => h | Name.num p v h => h instance : Hashable Name where hash := Name.hash namespace Name @[export lean_name_mk_string] def mkStr (p : Name) (s : String) : Name := Name.str p s (mixHash (hash p) (hash s)) @[export lean_name_mk_numeral] def mkNum (p : Name) (v : Nat) : Name := Name.num p v (mixHash (hash p) (dite (Less v USize.size) (fun h => USize.ofNatCore v h) (fun _ => USize.ofNat32 17 (by decide)))) def mkSimple (s : String) : Name := mkStr Name.anonymous s @[extern "lean_name_eq"] protected def beq : (@& Name) → (@& Name) → Bool | anonymous, anonymous => true | str p₁ s₁ _, str p₂ s₂ _ => and (BEq.beq s₁ s₂) (Name.beq p₁ p₂) | num p₁ n₁ _, num p₂ n₂ _ => and (BEq.beq n₁ n₂) (Name.beq p₁ p₂) | _, _ => false instance : BEq Name where beq := Name.beq protected def append : Name → Name → Name | n, anonymous => n | n, str p s _ => Name.mkStr (Name.append n p) s | n, num p d _ => Name.mkNum (Name.append n p) d instance : Append Name where append := Name.append end Name /- Syntax -/ /-- Source information of tokens. -/ inductive SourceInfo where /- Token from original input with whitespace and position information. `leading` will be inferred after parsing by `Syntax.updateLeading`. During parsing, it is not at all clear what the preceding token was, especially with backtracking. -/ | original (leading : Substring) (pos : String.Pos) (trailing : Substring) /- Synthesized token (e.g. from a quotation) annotated with a span from the original source. In the delaborator, we "misuse" this constructor to store synthetic positions identifying subterms. -/ | synthetic (pos : String.Pos) (endPos : String.Pos) /- Synthesized token without position information. -/ | protected none instance : Inhabited SourceInfo := ⟨SourceInfo.none⟩ namespace SourceInfo def getPos? (info : SourceInfo) (originalOnly := false) : Option String.Pos := match info, originalOnly with | original (pos := pos) .., _ => some pos | synthetic (pos := pos) .., false => some pos | _, _ => none end SourceInfo abbrev SyntaxNodeKind := Name /- Syntax AST -/ inductive Syntax where | missing : Syntax | node (kind : SyntaxNodeKind) (args : Array Syntax) : Syntax | atom (info : SourceInfo) (val : String) : Syntax | ident (info : SourceInfo) (rawVal : Substring) (val : Name) (preresolved : List (Prod Name (List String))) : Syntax instance : Inhabited Syntax where default := Syntax.missing /- Builtin kinds -/ def choiceKind : SyntaxNodeKind := `choice def nullKind : SyntaxNodeKind := `null def groupKind : SyntaxNodeKind := `group def identKind : SyntaxNodeKind := `ident def strLitKind : SyntaxNodeKind := `strLit def charLitKind : SyntaxNodeKind := `charLit def numLitKind : SyntaxNodeKind := `numLit def scientificLitKind : SyntaxNodeKind := `scientificLit def nameLitKind : SyntaxNodeKind := `nameLit def fieldIdxKind : SyntaxNodeKind := `fieldIdx def interpolatedStrLitKind : SyntaxNodeKind := `interpolatedStrLitKind def interpolatedStrKind : SyntaxNodeKind := `interpolatedStrKind namespace Syntax def getKind (stx : Syntax) : SyntaxNodeKind := match stx with | Syntax.node k args => k -- We use these "pseudo kinds" for antiquotation kinds. -- For example, an antiquotation `$id:ident` (using Lean.Parser.Term.ident) -- is compiled to ``if stx.isOfKind `ident ...`` | Syntax.missing => `missing | Syntax.atom _ v => Name.mkSimple v | Syntax.ident .. => identKind def setKind (stx : Syntax) (k : SyntaxNodeKind) : Syntax := match stx with | Syntax.node _ args => Syntax.node k args | _ => stx def isOfKind (stx : Syntax) (k : SyntaxNodeKind) : Bool := beq stx.getKind k def getArg (stx : Syntax) (i : Nat) : Syntax := match stx with | Syntax.node _ args => args.getD i Syntax.missing | _ => Syntax.missing -- Add `stx[i]` as sugar for `stx.getArg i` @[inline] def getOp (self : Syntax) (idx : Nat) : Syntax := self.getArg idx def getArgs (stx : Syntax) : Array Syntax := match stx with | Syntax.node _ args => args | _ => Array.empty def getNumArgs (stx : Syntax) : Nat := match stx with | Syntax.node _ args => args.size | _ => 0 def isMissing : Syntax → Bool | Syntax.missing => true | _ => false def isNodeOf (stx : Syntax) (k : SyntaxNodeKind) (n : Nat) : Bool := and (stx.isOfKind k) (beq stx.getNumArgs n) def isIdent : Syntax → Bool | ident _ _ _ _ => true | _ => false def getId : Syntax → Name | ident _ _ val _ => val | _ => Name.anonymous def matchesNull (stx : Syntax) (n : Nat) : Bool := isNodeOf stx nullKind n def matchesIdent (stx : Syntax) (id : Name) : Bool := and stx.isIdent (beq stx.getId id) def setArgs (stx : Syntax) (args : Array Syntax) : Syntax := match stx with | node k _ => node k args | stx => stx def setArg (stx : Syntax) (i : Nat) (arg : Syntax) : Syntax := match stx with | node k args => node k (args.setD i arg) | stx => stx /-- Retrieve the left-most leaf's info in the Syntax tree. -/ partial def getHeadInfo? : Syntax → Option SourceInfo | atom info _ => some info | ident info .. => some info | node _ args => let rec loop (i : Nat) : Option SourceInfo := match decide (Less i args.size) with | true => match getHeadInfo? (args.get! i) with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _ => none /-- Retrieve the left-most leaf's info in the Syntax tree, or `none` if there is no token. -/ partial def getHeadInfo (stx : Syntax) : SourceInfo := match stx.getHeadInfo? with | some info => info | none => SourceInfo.none def getPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := stx.getHeadInfo.getPos? originalOnly partial def getTailPos? (stx : Syntax) (originalOnly := false) : Option String.Pos := match stx, originalOnly with | atom (SourceInfo.original (pos := pos) ..) val, _ => some (pos.add val.bsize) | atom (SourceInfo.synthetic (endPos := pos) ..) _, false => some pos | ident (SourceInfo.original (pos := pos) ..) val .., _ => some (pos.add val.bsize) | ident (SourceInfo.synthetic (endPos := pos) ..) .., false => some pos | node _ args, _ => let rec loop (i : Nat) : Option String.Pos := match decide (Less i args.size) with | true => match getTailPos? (args.get! ((args.size.sub i).sub 1)) originalOnly with | some info => some info | none => loop (hAdd i 1) | false => none loop 0 | _, _ => none /-- An array of syntax elements interspersed with separators. Can be coerced to/from `Array Syntax` to automatically remove/insert the separators. -/ structure SepArray (sep : String) where elemsAndSeps : Array Syntax end Syntax def SourceInfo.fromRef (ref : Syntax) : SourceInfo := match ref.getPos?, ref.getTailPos? with | some pos, some tailPos => SourceInfo.synthetic pos tailPos | _, _ => SourceInfo.none def mkAtomFrom (src : Syntax) (val : String) : Syntax := Syntax.atom src.getHeadInfo val /- Parser descriptions -/ inductive ParserDescr where | const (name : Name) | unary (name : Name) (p : ParserDescr) | binary (name : Name) (p₁ p₂ : ParserDescr) | node (kind : SyntaxNodeKind) (prec : Nat) (p : ParserDescr) | trailingNode (kind : SyntaxNodeKind) (prec lhsPrec : Nat) (p : ParserDescr) | symbol (val : String) | nonReservedSymbol (val : String) (includeIdent : Bool) | cat (catName : Name) (rbp : Nat) | parser (declName : Name) | nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : ParserDescr) | sepBy (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) | sepBy1 (p : ParserDescr) (sep : String) (psep : ParserDescr) (allowTrailingSep : Bool := false) instance : Inhabited ParserDescr where default := ParserDescr.symbol "" abbrev TrailingParserDescr := ParserDescr /- Runtime support for making quotation terms auto-hygienic, by mangling identifiers introduced by them with a "macro scope" supplied by the context. Details to appear in a paper soon. -/ abbrev MacroScope := Nat /-- Macro scope used internally. It is not available for our frontend. -/ def reservedMacroScope := 0 /-- First macro scope available for our frontend -/ def firstFrontendMacroScope := hAdd reservedMacroScope 1 class MonadRef (m : Type → Type) where getRef : m Syntax withRef {α} : Syntax → m α → m α export MonadRef (getRef) instance (m n : Type → Type) [MonadLift m n] [MonadFunctor m n] [MonadRef m] : MonadRef n where getRef := liftM (getRef : m _) withRef ref x := monadMap (m := m) (MonadRef.withRef ref) x def replaceRef (ref : Syntax) (oldRef : Syntax) : Syntax := match ref.getPos? with | some _ => ref | _ => oldRef @[inline] def withRef {m : Type → Type} [Monad m] [MonadRef m] {α} (ref : Syntax) (x : m α) : m α := bind getRef fun oldRef => let ref := replaceRef ref oldRef MonadRef.withRef ref x /-- A monad that supports syntax quotations. Syntax quotations (in term position) are monadic values that when executed retrieve the current "macro scope" from the monad and apply it to every identifier they introduce (independent of whether this identifier turns out to be a reference to an existing declaration, or an actually fresh binding during further elaboration). We also apply the position of the result of `getRef` to each introduced symbol, which results in better error positions than not applying any position. -/ class MonadQuotation (m : Type → Type) extends MonadRef m where -- Get the fresh scope of the current macro invocation getCurrMacroScope : m MacroScope getMainModule : m Name /- Execute action in a new macro invocation context. This transformer should be used at all places that morally qualify as the beginning of a "macro call", e.g. `elabCommand` and `elabTerm` in the case of the elaborator. However, it can also be used internally inside a "macro" if identifiers introduced by e.g. different recursive calls should be independent and not collide. While returning an intermediate syntax tree that will recursively be expanded by the elaborator can be used for the same effect, doing direct recursion inside the macro guarded by this transformer is often easier because one is not restricted to passing a single syntax tree. Modelling this helper as a transformer and not just a monadic action ensures that the current macro scope before the recursive call is restored after it, as expected. -/ withFreshMacroScope {α : Type} : m α → m α export MonadQuotation (getCurrMacroScope getMainModule withFreshMacroScope) def MonadRef.mkInfoFromRefPos [Monad m] [MonadRef m] : m SourceInfo := do SourceInfo.fromRef (← getRef) instance {m n : Type → Type} [MonadFunctor m n] [MonadLift m n] [MonadQuotation m] : MonadQuotation n where getCurrMacroScope := liftM (m := m) getCurrMacroScope getMainModule := liftM (m := m) getMainModule withFreshMacroScope := monadMap (m := m) withFreshMacroScope /- We represent a name with macro scopes as ``` <actual name>._@.(<module_name>.<scopes>)*.<module_name>._hyg.<scopes> ``` Example: suppose the module name is `Init.Data.List.Basic`, and name is `foo.bla`, and macroscopes [2, 5] ``` foo.bla._@.Init.Data.List.Basic._hyg.2.5 ``` We may have to combine scopes from different files/modules. The main modules being processed is always the right most one. This situation may happen when we execute a macro generated in an imported file in the current file. ``` foo.bla._@.Init.Data.List.Basic.2.1.Init.Lean.Expr_hyg.4 ``` The delimiter `_hyg` is used just to improve the `hasMacroScopes` performance. -/ def Name.hasMacroScopes : Name → Bool | str _ s _ => beq s "_hyg" | num p _ _ => hasMacroScopes p | _ => false private def eraseMacroScopesAux : Name → Name | Name.str p s _ => match beq s "_@" with | true => p | false => eraseMacroScopesAux p | Name.num p _ _ => eraseMacroScopesAux p | Name.anonymous => Name.anonymous @[export lean_erase_macro_scopes] def Name.eraseMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => eraseMacroScopesAux n | false => n private def simpMacroScopesAux : Name → Name | Name.num p i _ => Name.mkNum (simpMacroScopesAux p) i | n => eraseMacroScopesAux n /- Helper function we use to create binder names that do not need to be unique. -/ @[export lean_simp_macro_scopes] def Name.simpMacroScopes (n : Name) : Name := match n.hasMacroScopes with | true => simpMacroScopesAux n | false => n structure MacroScopesView where name : Name imported : Name mainModule : Name scopes : List MacroScope instance : Inhabited MacroScopesView where default := ⟨arbitrary, arbitrary, arbitrary, arbitrary⟩ def MacroScopesView.review (view : MacroScopesView) : Name := match view.scopes with | List.nil => view.name | List.cons _ _ => let base := (Name.mkStr (hAppend (hAppend (Name.mkStr view.name "_@") view.imported) view.mainModule) "_hyg") view.scopes.foldl Name.mkNum base private def assembleParts : List Name → Name → Name | List.nil, acc => acc | List.cons (Name.str _ s _) ps, acc => assembleParts ps (Name.mkStr acc s) | List.cons (Name.num _ n _) ps, acc => assembleParts ps (Name.mkNum acc n) | _, acc => panic "Error: unreachable @ assembleParts" private def extractImported (scps : List MacroScope) (mainModule : Name) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := mainModule, imported := assembleParts parts Name.anonymous, scopes := scps } | false => extractImported scps mainModule p (List.cons n parts) | n@(Name.num p str _), parts => extractImported scps mainModule p (List.cons n parts) | _, _ => panic "Error: unreachable @ extractImported" private def extractMainModule (scps : List MacroScope) : Name → List Name → MacroScopesView | n@(Name.str p str _), parts => match beq str "_@" with | true => { name := p, mainModule := assembleParts parts Name.anonymous, imported := Name.anonymous, scopes := scps } | false => extractMainModule scps p (List.cons n parts) | n@(Name.num p num _), acc => extractImported scps (assembleParts acc Name.anonymous) n List.nil | _, _ => panic "Error: unreachable @ extractMainModule" private def extractMacroScopesAux : Name → List MacroScope → MacroScopesView | Name.num p scp _, acc => extractMacroScopesAux p (List.cons scp acc) | Name.str p str _, acc => extractMainModule acc p List.nil -- str must be "_hyg" | _, _ => panic "Error: unreachable @ extractMacroScopesAux" /-- Revert all `addMacroScope` calls. `v = extractMacroScopes n → n = v.review`. This operation is useful for analyzing/transforming the original identifiers, then adding back the scopes (via `MacroScopesView.review`). -/ def extractMacroScopes (n : Name) : MacroScopesView := match n.hasMacroScopes with | true => extractMacroScopesAux n List.nil | false => { name := n, scopes := List.nil, imported := Name.anonymous, mainModule := Name.anonymous } def addMacroScope (mainModule : Name) (n : Name) (scp : MacroScope) : Name := match n.hasMacroScopes with | true => let view := extractMacroScopes n match beq view.mainModule mainModule with | true => Name.mkNum n scp | false => { view with imported := view.scopes.foldl Name.mkNum (hAppend view.imported view.mainModule) mainModule := mainModule scopes := List.cons scp List.nil }.review | false => Name.mkNum (Name.mkStr (hAppend (Name.mkStr n "_@") mainModule) "_hyg") scp @[inline] def MonadQuotation.addMacroScope {m : Type → Type} [MonadQuotation m] [Monad m] (n : Name) : m Name := bind getMainModule fun mainModule => bind getCurrMacroScope fun scp => pure (Lean.addMacroScope mainModule n scp) def defaultMaxRecDepth := 512 def maxRecDepthErrorMessage : String := "maximum recursion depth has been reached (use `set_option maxRecDepth <num>` to increase limit)" namespace Macro /- References -/ constant MacroEnvPointed : PointedType.{0} def MacroEnv : Type := MacroEnvPointed.type instance : Inhabited MacroEnv where default := MacroEnvPointed.val structure Context where macroEnv : MacroEnv mainModule : Name currMacroScope : MacroScope currRecDepth : Nat := 0 maxRecDepth : Nat := defaultMaxRecDepth ref : Syntax inductive Exception where | error : Syntax → String → Exception | unsupportedSyntax : Exception end Macro abbrev MacroM := ReaderT Macro.Context (EStateM Macro.Exception MacroScope) abbrev Macro := Syntax → MacroM Syntax namespace Macro instance : MonadRef MacroM where getRef := bind read fun ctx => pure ctx.ref withRef := fun ref x => withReader (fun ctx => { ctx with ref := ref }) x def addMacroScope (n : Name) : MacroM Name := bind read fun ctx => pure (Lean.addMacroScope ctx.mainModule n ctx.currMacroScope) def throwUnsupported {α} : MacroM α := throw Exception.unsupportedSyntax def throwError {α} (msg : String) : MacroM α := bind getRef fun ref => throw (Exception.error ref msg) def throwErrorAt {α} (ref : Syntax) (msg : String) : MacroM α := withRef ref (throwError msg) @[inline] protected def withFreshMacroScope {α} (x : MacroM α) : MacroM α := bind (modifyGet (fun s => (s, hAdd s 1))) fun fresh => withReader (fun ctx => { ctx with currMacroScope := fresh }) x @[inline] def withIncRecDepth {α} (ref : Syntax) (x : MacroM α) : MacroM α := bind read fun ctx => match beq ctx.currRecDepth ctx.maxRecDepth with | true => throw (Exception.error ref maxRecDepthErrorMessage) | false => withReader (fun ctx => { ctx with currRecDepth := hAdd ctx.currRecDepth 1 }) x instance : MonadQuotation MacroM where getCurrMacroScope ctx := pure ctx.currMacroScope getMainModule ctx := pure ctx.mainModule withFreshMacroScope := Macro.withFreshMacroScope unsafe def mkMacroEnvImp (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv := unsafeCast expandMacro? @[implementedBy mkMacroEnvImp] constant mkMacroEnv (expandMacro? : Syntax → MacroM (Option Syntax)) : MacroEnv def expandMacroNotAvailable? (stx : Syntax) : MacroM (Option Syntax) := throwErrorAt stx "expandMacro has not been set" def mkMacroEnvSimple : MacroEnv := mkMacroEnv expandMacroNotAvailable? unsafe def expandMacro?Imp (stx : Syntax) : MacroM (Option Syntax) := bind read fun ctx => let f : Syntax → MacroM (Option Syntax) := unsafeCast (ctx.macroEnv) f stx /-- `expandMacro? stx` return `some stxNew` if `stx` is a macro, and `stxNew` is its expansion. -/ @[implementedBy expandMacro?Imp] constant expandMacro? : Syntax → MacroM (Option Syntax) end Macro export Macro (expandMacro?) namespace PrettyPrinter abbrev UnexpandM := EStateM Unit Unit /-- Function that tries to reverse macro expansions as a post-processing step of delaboration. While less general than an arbitrary delaborator, it can be declared without importing `Lean`. Used by the `[appUnexpander]` attribute. -/ -- a `kindUnexpander` could reasonably be added later abbrev Unexpander := Syntax → UnexpandM Syntax -- unexpanders should not need to introduce new names instance : MonadQuotation UnexpandM where getRef := pure Syntax.missing withRef := fun _ => id getCurrMacroScope := pure 0 getMainModule := pure `_fakeMod withFreshMacroScope := id end PrettyPrinter end Lean
8fe7a79e9dfeb18e42ccb93bf4215fdebfd06f87
618003631150032a5676f229d13a079ac875ff77
/src/control/bitraversable/basic.lean
713a06ea8067b2ac6c475887f4bdb531e38e218c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
2,932
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import control.bifunctor /-! # Bitraversable type class Type class for traversing bifunctors. The concepts and laws are taken from <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> Simple examples of `bitraversable` are `prod` and `sum`. A more elaborate example is to define an a-list as: ``` def alist (key val : Type) := list (key × val) ``` Then we can use `f : key → io key'` and `g : val → io val'` to manipulate the `alist`'s key and value respectively with `bitraverse f g : alist key val → io (alist key' val')` ## Main definitions * bitraversable - exposes the `bitraverse` function * is_lawful_bitraversable - laws similar to is_lawful_traversable ## Tags traversable bitraversable iterator functor bifunctor applicative -/ universes u section prio set_option default_priority 100 -- see Note [default priority] class bitraversable (t : Type u → Type u → Type u) extends bifunctor t := (bitraverse : Π {m : Type u → Type u} [applicative m] {α α' β β'}, (α → m α') → (β → m β') → t α β → m (t α' β')) end prio export bitraversable ( bitraverse ) def bisequence {t m} [bitraversable t] [applicative m] {α β} : t (m α) (m β) → m (t α β) := bitraverse id id open functor section prio set_option default_priority 100 -- see Note [default priority] class is_lawful_bitraversable (t : Type u → Type u → Type u) [bitraversable t] extends is_lawful_bifunctor t := (id_bitraverse : ∀ {α β} (x : t α β), bitraverse id.mk id.mk x = id.mk x ) (comp_bitraverse : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] {α α' β β' γ γ'} (f : β → F γ) (f' : β' → F γ') (g : α → G β) (g' : α' → G β') (x : t α α'), bitraverse (comp.mk ∘ map f ∘ g) (comp.mk ∘ map f' ∘ g') x = comp.mk (bitraverse f f' <$> bitraverse g g' x) ) (bitraverse_eq_bimap_id : ∀ {α α' β β'} (f : α → β) (f' : α' → β') (x : t α α'), bitraverse (id.mk ∘ f) (id.mk ∘ f') x = id.mk (bimap f f' x)) (binaturality : ∀ {F G} [applicative F] [applicative G] [is_lawful_applicative F] [is_lawful_applicative G] (η : applicative_transformation F G) {α α' β β'} (f : α → F β) (f' : α' → F β') (x : t α α'), η (bitraverse f f' x) = bitraverse (@η _ ∘ f) (@η _ ∘ f') x) end prio export is_lawful_bitraversable ( id_bitraverse comp_bitraverse bitraverse_eq_bimap_id ) open is_lawful_bitraversable attribute [higher_order bitraverse_id_id] id_bitraverse attribute [higher_order bitraverse_comp] comp_bitraverse attribute [higher_order] binaturality bitraverse_eq_bimap_id export is_lawful_bitraversable (bitraverse_id_id bitraverse_comp)
38c1d4a0fa8fc59217f33c30ffaf87cc6330cfff
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world10/level10.lean
16221fef8798f302152332d2ff534f417f29c11b
[ "Apache-2.0" ]
permissive
ChrisHughes24/natural_number_game
c7c00aa1f6a95004286fd456ed13cf6e113159ce
9d09925424da9f6275e6cfe427c8bcf12bb0944f
refs/heads/master
1,600,715,773,528
1,573,910,462,000
1,573,910,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
328
lean
import game.world10.level9 -- hide namespace mynat -- hide /- # Inequality world. ## Level 10: `le_succ_self` Can you find the two-line proof? -/ /- Lemma For all naturals $a$, $a\le\operatorname{succ}(a).$ -/ lemma le_succ_self (a : mynat) : a ≤ succ a := begin [less_leaky] use 1, refl, end end mynat -- hide
dace9db932cca415b9b790c34bb872d81b364637
61ccc57f9d72048e493dd6969b56ebd7f0a8f9e8
/src/algebra/geom_sum.lean
244611ecc69ff9395fb00c56f4a00ddb8430c3ce
[ "Apache-2.0" ]
permissive
jtristan/mathlib
375b3c8682975df28f79f53efcb7c88840118467
8fa8f175271320d675277a672f59ec53abd62f10
refs/heads/master
1,651,072,765,551
1,588,255,641,000
1,588,255,641,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,286
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland Sums of finite geometric series -/ import algebra.commute import algebra.group_with_zero_power universe u variable {α : Type u} open finset /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i$. -/ def geom_series [semiring α] (x : α) (n : ℕ) := (range n).sum (λ i, x ^ i) theorem geom_series_def [semiring α] (x : α) (n : ℕ) : geom_series x n = (range n).sum (λ i, x ^ i) := rfl @[simp] theorem geom_series_zero [semiring α] (x : α) : geom_series x 0 = 0 := rfl @[simp] theorem geom_series_one [semiring α] (x : α) : geom_series x 1 = 1 := by { rw [geom_series_def, sum_range_one, pow_zero] } /-- Sum of the finite geometric series $\sum_{i=0}^{n-1} x^i y^{n-1-i}$. -/ def geom_series₂ [semiring α] (x y : α) (n : ℕ) := (range n).sum (λ i, x ^ i * (y ^ (n - 1 - i))) theorem geom_series₂_def [semiring α] (x y : α) (n : ℕ) : geom_series₂ x y n = (range n).sum (λ i, x ^ i * y ^ (n - 1 - i)) := rfl @[simp] theorem geom_series₂_zero [semiring α] (x y : α) : geom_series₂ x y 0 = 0 := rfl @[simp] theorem geom_series₂_one [semiring α] (x y : α) : geom_series₂ x y 1 = 1 := by { have : 1 - 1 - 0 = 0 := rfl, rw [geom_series₂_def, sum_range_one, this, pow_zero, pow_zero, mul_one] } @[simp] theorem geom_series₂_with_one [semiring α] (x : α) (n : ℕ) : geom_series₂ x 1 n = geom_series x n := sum_congr rfl (λ i _, by { rw [one_pow, mul_one] }) /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ protected theorem commute.geom_sum₂_mul_add [semiring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := begin let f := λ (m i : ℕ), (x + y) ^ i * y ^ (m - 1 - i), change ((range n).sum (f n)) * x + y ^ n = (x + y) ^ n, induction n with n ih, { rw [range_zero, sum_empty, zero_mul, zero_add, pow_zero, pow_zero] }, { have f_last : f n.succ n = (x + y) ^ n := by { dsimp [f], rw [nat.sub_sub, nat.add_comm, nat.sub_self, pow_zero, mul_one] }, have f_succ : ∀ i, i ∈ range n → f n.succ i = y * f n i := λ i hi, by { dsimp [f], have : commute y ((x + y) ^ i) := (h.symm.add_right (commute.refl y)).pow_right i, rw [← mul_assoc, this.eq, mul_assoc, ← pow_succ y (n - 1 - i)], congr' 2, rw [nat.succ_eq_add_one, nat.add_sub_cancel, nat.sub_sub, add_comm 1 i], have := nat.add_sub_of_le (mem_range.mp hi), rw [add_comm, nat.succ_eq_add_one] at this, rw [← this, nat.add_sub_cancel, add_comm i 1, ← add_assoc, nat.add_sub_cancel] }, rw [pow_succ (x + y), add_mul, sum_range_succ, f_last, add_mul, add_assoc], rw [(((commute.refl x).add_right h).pow_right n).eq], congr' 1, rw[sum_congr rfl f_succ, ← mul_sum, pow_succ y], rw[mul_assoc, ← mul_add y, ih] } end /-- $x^n-y^n = (x-y) \sum x^ky^{n-1-k}$ reformulated without `-` signs. -/ theorem geom_sum₂_mul_add [comm_semiring α] (x y : α) (n : ℕ) : (geom_series₂ (x + y) y n) * x + y ^ n = (x + y) ^ n := (commute.all x y).geom_sum₂_mul_add n theorem geom_sum_mul_add [semiring α] (x : α) (n : ℕ) : (geom_series (x + 1) n) * x + 1 = (x + 1) ^ n := begin have := (commute.one_right x).geom_sum₂_mul_add n, rw [one_pow, geom_series₂_with_one] at this, exact this end theorem geom_sum₂_mul_comm [ring α] {x y : α} (h : commute x y) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := begin have := (h.sub_left (commute.refl y)).geom_sum₂_mul_add n, rw [sub_add_cancel] at this, rw [← this, add_sub_cancel] end theorem geom_sum₂_mul [comm_ring α] (x y : α) (n : ℕ) : (geom_series₂ x y n) * (x - y) = x ^ n - y ^ n := geom_sum₂_mul_comm (commute.all x y) n theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : (geom_series x n) * (x - 1) = x ^ n - 1 := begin have := geom_sum₂_mul_comm (commute.one_right x) n, rw [one_pow, geom_series₂_with_one] at this, exact this end theorem geom_sum_mul_neg [ring α] (x : α) (n : ℕ) : (geom_series x n) * (1 - x) = 1 - x ^ n := begin have := congr_arg has_neg.neg (geom_sum_mul x n), rw [neg_sub, ← mul_neg_eq_neg_mul_symm, neg_sub] at this, exact this end theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (geom_series x n) = (x ^ n - 1) / (x - 1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] theorem geom_sum_Ico_mul [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : ((finset.Ico m n).sum (pow x)) * (x - 1) = x^n - x^m := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul, geom_sum_mul, sub_sub_sub_cancel_right] theorem geom_sum_Ico_mul_neg [ring α] (x : α) {m n : ℕ} (hmn : m ≤ n) : ((finset.Ico m n).sum (pow x)) * (1 - x) = x^m - x^n := by rw [sum_Ico_eq_sub _ hmn, ← geom_series_def, ← geom_series_def, sub_mul, geom_sum_mul_neg, geom_sum_mul_neg, sub_sub_sub_cancel_left] theorem geom_sum_Ico [division_ring α] {x : α} (hx : x ≠ 1) {m n : ℕ} (hmn : m ≤ n) : (finset.Ico m n).sum (λ i, x ^ i) = (x ^ n - x ^ m) / (x - 1) := by simp only [sum_Ico_eq_sub _ hmn, (geom_series_def _ _).symm, geom_sum hx, div_sub_div_same, sub_sub_sub_cancel_right] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (geom_series x⁻¹ n) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * (x ^ n)⁻¹ = (x ^ n)⁻¹ * x := nat.rec_on n (by simp) (λ n h, by rw [pow_succ, mul_inv', ←mul_assoc, h, mul_assoc, mul_inv_cancel hx0, mul_assoc, inv_mul_cancel hx0]), begin rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃], simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄, sub_eq_add_neg, add_comm, add_left_comm], end
20a35f15cf92018a63f1ff0890e448636ffa7fb1
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/trust0/t1.lean
fd5d599a56c67a41a15519d75da943c75390db86
[ "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
30
lean
import system.io #print trust
ed6ca01a41365a62566ee6c0f43aa02e1a2df6dc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/order_functions_auto.lean
33edce8e6eb9c4f5af95570ddb2bdf466100db25
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
5,962
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.order import Mathlib.order.lattice import Mathlib.PostPort universes u v namespace Mathlib /-! # `max` and `min` This file proves basic properties about maxima and minima on a `linear_order`. ## Tags min, max -/ -- translate from lattices to linear orders (sup → max, inf → min) @[simp] theorem le_min_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : c ≤ min a b ↔ c ≤ a ∧ c ≤ b := le_inf_iff @[simp] theorem max_le_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a b ≤ c ↔ a ≤ c ∧ b ≤ c := sup_le_iff theorem max_le_max {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} : a ≤ c → b ≤ d → max a b ≤ max c d := sup_le_sup theorem min_le_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} : a ≤ c → b ≤ d → min a b ≤ min c d := inf_le_inf theorem le_max_left_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ b → a ≤ max b c := le_sup_left_of_le theorem le_max_right_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ c → a ≤ max b c := le_sup_right_of_le theorem min_le_left_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ c → min a b ≤ c := inf_le_left_of_le theorem min_le_right_of_le {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : b ≤ c → min a b ≤ c := inf_le_right_of_le theorem max_min_distrib_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a (min b c) = min (max a b) (max a c) := sup_inf_left theorem max_min_distrib_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max (min a b) c = min (max a c) (max b c) := sup_inf_right theorem min_max_distrib_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a (max b c) = max (min a b) (min a c) := inf_sup_left theorem min_max_distrib_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min (max a b) c = max (min a c) (min b c) := inf_sup_right theorem min_le_max {α : Type u} [linear_order α] {a : α} {b : α} : min a b ≤ max a b := le_trans (min_le_left a b) (le_max_left a b) @[simp] theorem min_eq_left_iff {α : Type u} [linear_order α] {a : α} {b : α} : min a b = a ↔ a ≤ b := inf_eq_left @[simp] theorem min_eq_right_iff {α : Type u} [linear_order α] {a : α} {b : α} : min a b = b ↔ b ≤ a := inf_eq_right @[simp] theorem max_eq_left_iff {α : Type u} [linear_order α] {a : α} {b : α} : max a b = a ↔ b ≤ a := sup_eq_left @[simp] theorem max_eq_right_iff {α : Type u} [linear_order α] {a : α} {b : α} : max a b = b ↔ a ≤ b := sup_eq_right /-- An instance asserting that `max a a = a` -/ protected instance max_idem {α : Type u} [linear_order α] : is_idempotent α max := Mathlib.sup_is_idempotent /-- An instance asserting that `min a a = a` -/ protected instance min_idem {α : Type u} [linear_order α] : is_idempotent α min := Mathlib.inf_is_idempotent @[simp] theorem max_lt_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : max a b < c ↔ a < c ∧ b < c := sup_lt_iff @[simp] theorem lt_min_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a < min b c ↔ a < b ∧ a < c := lt_inf_iff @[simp] theorem lt_max_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a < max b c ↔ a < b ∨ a < c := lt_sup_iff @[simp] theorem min_lt_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a b < c ↔ a < c ∨ b < c := lt_max_iff @[simp] theorem min_le_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : min a b ≤ c ↔ a ≤ c ∨ b ≤ c := inf_le_iff @[simp] theorem le_max_iff {α : Type u} [linear_order α] {a : α} {b : α} {c : α} : a ≤ max b c ↔ a ≤ b ∨ a ≤ c := min_le_iff theorem max_lt_max {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : a < c) (h₂ : b < d) : max a b < max c d := sorry theorem min_lt_min {α : Type u} [linear_order α] {a : α} {b : α} {c : α} {d : α} (h₁ : a < c) (h₂ : b < d) : min a b < min c d := max_lt_max h₁ h₂ theorem min_right_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : min (min a b) c = min (min a c) b := right_comm min min_comm min_assoc a b c theorem max.left_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max a (max b c) = max b (max a c) := left_comm max max_comm max_assoc a b c theorem max.right_comm {α : Type u} [linear_order α] (a : α) (b : α) (c : α) : max (max a b) c = max (max a c) b := right_comm max max_comm max_assoc a b c theorem monotone.map_max {α : Type u} {β : Type v} [linear_order α] [linear_order β] {f : α → β} {a : α} {b : α} (hf : monotone f) : f (max a b) = max (f a) (f b) := sorry theorem monotone.map_min {α : Type u} {β : Type v} [linear_order α] [linear_order β] {f : α → β} {a : α} {b : α} (hf : monotone f) : f (min a b) = min (f a) (f b) := monotone.map_max (monotone.order_dual hf) theorem min_choice {α : Type u} [linear_order α] (a : α) (b : α) : min a b = a ∨ min a b = b := sorry theorem max_choice {α : Type u} [linear_order α] (a : α) (b : α) : max a b = a ∨ max a b = b := min_choice a b theorem le_of_max_le_left {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : max a b ≤ c) : a ≤ c := le_trans (le_max_left a b) h theorem le_of_max_le_right {α : Type u} [linear_order α] {a : α} {b : α} {c : α} (h : max a b ≤ c) : b ≤ c := le_trans (le_max_right a b) h end Mathlib
0add6f0b1ab4496d6f0ebdd1bffa9edb38616c89
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/linear_algebra/matrix.lean
36b5de9812a96eb9138983d81a074445db822bd8
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
33,219
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Patrick Massot, Casper Putz -/ import linear_algebra.finite_dimensional import linear_algebra.nonsingular_inverse import linear_algebra.multilinear /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. It also defines the trace of an endomorphism, and the determinant of a family of vectors with respect to some basis. Some results are proved about the linear map corresponding to a diagonal matrix (`range`, `ker` and `rank`). ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `to_lin`: the `R`-linear map from `matrix m n R` to `R`-linear maps from `n → R` to `m → R` * `to_matrix`: the map in the other direction * `linear_equiv_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `linear_equiv_matrix'`: the same thing but with `M₁ = n → R` and `M₂ = m → R`, using their standard bases * `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between `R`-endomorphisms of `M` and `matrix n n R` * `matrix.trace`: the trace of a square matrix * `linear_map.trace`: the trace of an endomorphism * `is_basis.to_matrix`: the matrix whose columns are a given family of vectors in a given basis * `is_basis.to_matrix_equiv`: given a basis, the linear equivalence between families of vectors and matrices arising from `is_basis.to_matrix` * `is_basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map ## Tags linear_map, matrix, linear_equiv, diagonal, det, trace -/ noncomputable theory open set submodule open_locale big_operators universes u v w variables {l m n : Type*} [fintype l] [fintype m] [fintype n] namespace matrix variables {R : Type v} [comm_ring R] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- Evaluation of matrices gives a linear map from `matrix m n R` to linear maps `(n → R) →ₗ[R] (m → R)`. -/ def eval : (matrix m n R) →ₗ[R] ((n → R) →ₗ[R] (m → R)) := begin refine linear_map.mk₂ R mul_vec _ _ _ _, { assume M N v, funext x, change ∑ y : n, (M x y + N x y) * v y = _, simp only [_root_.add_mul, finset.sum_add_distrib], refl }, { assume c M v, funext x, change ∑ y : n, (c * M x y) * v y = _, simp only [_root_.mul_assoc, finset.mul_sum.symm], refl }, { assume M v w, funext x, change ∑ y : n, M x y * (v y + w y) = _, simp [_root_.mul_add, finset.sum_add_distrib], refl }, { assume c M v, funext x, change ∑ y : n, M x y * (c * v y) = _, rw [show (λy:n, M x y * (c * v y)) = (λy:n, c * (M x y * v y)), { funext n, ac_refl }, ← finset.mul_sum], refl } end /-- Evaluation of matrices gives a map from `matrix m n R` to linear maps `(n → R) →ₗ[R] (m → R)`. -/ def to_lin : matrix m n R → (n → R) →ₗ[R] (m → R) := eval.to_fun theorem to_lin_of_equiv {p q : Type*} [fintype p] [fintype q] (e₁ : m ≃ p) (e₂ : n ≃ q) (f : matrix p q R) : to_lin (λ i j, f (e₁ i) (e₂ j) : matrix m n R) = linear_equiv.arrow_congr (linear_map.fun_congr_left R R e₂) (linear_map.fun_congr_left R R e₁) (to_lin f) := linear_map.ext $ λ v, funext $ λ i, calc ∑ j : n, f (e₁ i) (e₂ j) * v j = ∑ j : n, f (e₁ i) (e₂ j) * v (e₂.symm (e₂ j)) : by simp_rw e₂.symm_apply_apply ... = ∑ k : q, f (e₁ i) k * v (e₂.symm k) : finset.sum_equiv e₂ (λ k, f (e₁ i) k * v (e₂.symm k)) lemma to_lin_add (M N : matrix m n R) : (M + N).to_lin = M.to_lin + N.to_lin := matrix.eval.map_add M N @[simp] lemma to_lin_zero : (0 : matrix m n R).to_lin = 0 := matrix.eval.map_zero @[simp] lemma to_lin_neg (M : matrix m n R) : (-M).to_lin = -M.to_lin := @linear_map.map_neg _ _ ((n → R) →ₗ[R] m → R) _ _ _ _ _ matrix.eval M instance to_lin.is_add_monoid_hom : @is_add_monoid_hom (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ to_lin := { map_zero := to_lin_zero, map_add := to_lin_add } @[simp] lemma to_lin_apply (M : matrix m n R) (v : n → R) : (M.to_lin : (n → R) → (m → R)) v = mul_vec M v := rfl lemma mul_to_lin (M : matrix m n R) (N : matrix n l R) : (M.mul N).to_lin = M.to_lin.comp N.to_lin := by { ext, simp } @[simp] lemma to_lin_one [decidable_eq n] : (1 : matrix n n R).to_lin = linear_map.id := by { ext, simp } end matrix namespace linear_map variables {R : Type v} [comm_ring R] /-- The linear map from linear maps `(n → R) →ₗ[R] (m → R)` to `matrix m n R`. -/ def to_matrixₗ [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) →ₗ[R] matrix m n R := begin refine linear_map.mk (λ f i j, f (λ n, ite (j = n) 1 0) i) _ _, { assume f g, simp only [add_apply], refl }, { assume f g, simp only [smul_apply], refl } end /-- The map from linear maps `(n → R) →ₗ[R] (m → R)` to `matrix m n R`. -/ def to_matrix [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) → matrix m n R := to_matrixₗ.to_fun @[simp] lemma to_matrix_id [decidable_eq n] : (@linear_map.id _ (n → R) _ _ _).to_matrix = 1 := by { ext, simp [to_matrix, to_matrixₗ, matrix.one_apply, eq_comm] } theorem to_matrix_of_equiv {p q : Type*} [decidable_eq n] [decidable_eq q] [fintype p] [fintype q] (e₁ : m ≃ p) (e₂ : n ≃ q) (f : (q → R) →ₗ[R] (p → R)) (i j) : to_matrix f (e₁ i) (e₂ j) = to_matrix (linear_equiv.arrow_congr (linear_map.fun_congr_left R R e₂) (linear_map.fun_congr_left R R e₁) f) i j := show f (λ k : q, ite (e₂ j = k) 1 0) (e₁ i) = f (λ k : q, ite (j = e₂.symm k) 1 0) (e₁ i), by { rcongr, rw equiv.eq_symm_apply } end linear_map section linear_equiv_matrix variables {R : Type v} [comm_ring R] [decidable_eq n] open finsupp matrix linear_map /-- `to_lin` is the left inverse of `to_matrix`. -/ lemma to_matrix_to_lin {f : (n → R) →ₗ[R] (m → R)} : to_lin (to_matrix f) = f := begin ext : 1, -- Show that the two sides are equal by showing that they are equal on a basis convert linear_eq_on (set.range _) _ (is_basis.mem_span (@pi.is_basis_fun R n _ _) _), assume e he, rw [@std_basis_eq_single R _ _ _ 1] at he, cases (set.mem_range.mp he) with i h, ext j, change ∑ k, (f (λ l, ite (k = l) 1 0)) j * (e k) = _, rw [←h], conv_lhs { congr, skip, funext, rw [mul_comm, ←smul_eq_mul, ←pi.smul_apply, ←linear_map.map_smul], rw [show _ = ite (i = k) (1:R) 0, by convert single_apply], rw [show f (ite (i = k) (1:R) 0 • (λ l, ite (k = l) 1 0)) = ite (i = k) (f _) 0, { split_ifs, { rw [one_smul] }, { rw [zero_smul], exact linear_map.map_zero f } }] }, convert finset.sum_eq_single i _ _, { rw [if_pos rfl], convert rfl, ext, congr }, { assume _ _ hbi, rw [if_neg $ ne.symm hbi], refl }, { assume hi, exact false.elim (hi $ finset.mem_univ i) } end /-- `to_lin` is the right inverse of `to_matrix`. -/ lemma to_lin_to_matrix {M : matrix m n R} : to_matrix (to_lin M) = M := begin ext, change ∑ y, M i y * ite (j = y) 1 0 = M i j, have h1 : (λ y, M i y * ite (j = y) 1 0) = (λ y, ite (j = y) (M i y) 0), { ext, split_ifs, exact mul_one _, exact mul_zero _ }, have h2 : ∑ y, ite (j = y) (M i y) 0 = ∑ y in {j}, ite (j = y) (M i y) 0, { refine (finset.sum_subset _ _).symm, { intros _ H, rwa finset.mem_singleton.1 H, exact finset.mem_univ _ }, { exact λ _ _ H, if_neg (mt (finset.mem_singleton.2 ∘ eq.symm) H) } }, rw [h1, h2, finset.sum_singleton], exact if_pos rfl end /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_equiv_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := to_matrix, inv_fun := to_lin, right_inv := λ _, to_lin_to_matrix, left_inv := λ _, to_matrix_to_lin, map_add' := to_matrixₗ.map_add, map_smul' := to_matrixₗ.map_smul } @[simp] lemma linear_equiv_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) : linear_equiv_matrix' f = to_matrix f := rfl variables {ι κ M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [fintype ι] [decidable_eq ι] [fintype κ] {v₁ : ι → M₁} {v₂ : κ → M₂} /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/ def linear_equiv_matrix (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix κ ι R := linear_equiv.trans (linear_equiv.arrow_congr hv₁.equiv_fun hv₂.equiv_fun) linear_equiv_matrix' variables (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) lemma linear_equiv_matrix_apply (f : M₁ →ₗ[R] M₂) (i : κ) (j : ι) : linear_equiv_matrix hv₁ hv₂ f i j = hv₂.equiv_fun (f (v₁ j)) i := by simp only [linear_equiv_matrix, to_matrix, to_matrixₗ, ite_smul, linear_equiv.trans_apply, linear_equiv.arrow_congr_apply, linear_equiv.coe_coe, linear_equiv_matrix'_apply, finset.mem_univ, if_true, one_smul, zero_smul, finset.sum_ite_eq, hv₁.equiv_fun_symm_apply] lemma linear_equiv_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : κ) (j : ι) : linear_equiv_matrix hv₁ hv₂ f i j = hv₂.repr (f (v₁ j)) i := linear_equiv_matrix_apply hv₁ hv₂ f i j @[simp] lemma linear_equiv_matrix_id : linear_equiv_matrix hv₁ hv₁ id = 1 := begin ext i j, simp [linear_equiv_matrix_apply, is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end @[simp] lemma linear_equiv_matrix_symm_one : (linear_equiv_matrix hv₁ hv₁).symm 1 = id := begin rw [← linear_equiv_matrix_id hv₁, ← linear_equiv.trans_apply], simp end open_locale classical theorem linear_equiv_matrix_range (f : M₁ →ₗ[R] M₂) (k : κ) (i : ι) : linear_equiv_matrix hv₁.range hv₂.range f ⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ = linear_equiv_matrix hv₁ hv₂ f k i := if H : (0 : R) = 1 then eq_of_zero_eq_one H _ _ else begin haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩, simp_rw [linear_equiv_matrix, linear_equiv.trans_apply, linear_equiv_matrix'_apply, ← equiv.of_injective_apply _ hv₁.injective, ← equiv.of_injective_apply _ hv₂.injective, to_matrix_of_equiv, ← linear_equiv.trans_apply, linear_equiv.arrow_congr_trans], congr' 3; refine function.left_inverse.injective linear_equiv.symm_symm _; ext x; simp_rw [linear_equiv.symm_trans_apply, is_basis.equiv_fun_symm_apply, fun_congr_left_symm, fun_congr_left_apply, fun_left_apply], convert (finset.sum_equiv (equiv.of_injective _ hv₁.injective) _).symm, simp_rw [equiv.symm_apply_apply, equiv.of_injective_apply, subtype.coe_mk], convert (finset.sum_equiv (equiv.of_injective _ hv₂.injective) _).symm, simp_rw [equiv.symm_apply_apply, equiv.of_injective_apply, subtype.coe_mk] end end linear_equiv_matrix namespace matrix open_locale matrix lemma comp_to_matrix_mul {R : Type v} [comm_ring R] [decidable_eq l] [decidable_eq m] (f : (m → R) →ₗ[R] (n → R)) (g : (l → R) →ₗ[R] (m → R)) : (f.comp g).to_matrix = f.to_matrix ⬝ g.to_matrix := suffices (f.comp g) = (f.to_matrix ⬝ g.to_matrix).to_lin, by rw [this, to_lin_to_matrix], by rw [mul_to_lin, to_matrix_to_lin, to_matrix_to_lin] section comp variables {R ι κ μ M₁ M₂ M₃ : Type*} [comm_ring R] [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [add_comm_group M₃] [module R M₃] [fintype ι] [decidable_eq κ] [fintype κ] [fintype μ] {v₁ : ι → M₁} {v₂ : κ → M₂} {v₃ : μ → M₃} (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) (hv₃ : is_basis R v₃) lemma linear_equiv_matrix_comp [decidable_eq ι] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) : linear_equiv_matrix hv₁ hv₃ (f.comp g) = linear_equiv_matrix hv₂ hv₃ f ⬝ linear_equiv_matrix hv₁ hv₂ g := by simp_rw [linear_equiv_matrix, linear_equiv.trans_apply, linear_equiv_matrix'_apply, linear_equiv.arrow_congr_comp _ hv₂.equiv_fun, comp_to_matrix_mul] lemma linear_equiv_matrix_mul [decidable_eq ι] (f g : M₁ →ₗ[R] M₁) : linear_equiv_matrix hv₁ hv₁ (f * g) = linear_equiv_matrix hv₁ hv₁ f * linear_equiv_matrix hv₁ hv₁ g := linear_equiv_matrix_comp hv₁ hv₁ hv₁ f g lemma linear_equiv_matrix_symm_mul [decidable_eq μ] (A : matrix ι κ R) (B : matrix κ μ R) : (linear_equiv_matrix hv₃ hv₁).symm (A ⬝ B) = ((linear_equiv_matrix hv₂ hv₁).symm A).comp ((linear_equiv_matrix hv₃ hv₂).symm B) := begin suffices : A ⬝ B = (linear_equiv_matrix hv₃ hv₁) (((linear_equiv_matrix hv₂ hv₁).symm A).comp $ (linear_equiv_matrix hv₃ hv₂).symm B), by rw [this, ← linear_equiv.trans_apply, linear_equiv.trans_symm, linear_equiv.refl_apply], rw [linear_equiv_matrix_comp hv₃ hv₂ hv₁, linear_equiv.apply_symm_apply, linear_equiv.apply_symm_apply] end end comp end matrix section is_basis_to_matrix variables {ι ι' R M : Type*} [fintype ι] [decidable_eq ι] [comm_ring R] [add_comm_group M] [module R M] open function matrix /-- From a basis `e : ι → M` and a family of vectors `v : ι → M`, make the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def is_basis.to_matrix {e : ι → M} (he : is_basis R e) (v : ι → M) : matrix ι ι R := linear_equiv_matrix he he (he.constr v) variables {e : ι → M} (he : is_basis R e) (v : ι → M) (i j : ι) namespace is_basis lemma to_matrix_apply : he.to_matrix v i j = he.equiv_fun (v j) i := by simp [is_basis.to_matrix, linear_equiv_matrix_apply] @[simp] lemma to_matrix_self : he.to_matrix e = 1 := begin rw is_basis.to_matrix, ext i j, simp [linear_equiv_matrix_apply, is_basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end lemma to_matrix_update (x : M) : he.to_matrix (function.update v i x) = matrix.update_column (he.to_matrix v) i (he.repr x) := begin ext j k, rw [is_basis.to_matrix, linear_equiv_matrix_apply' he he (he.constr (update v i x)), matrix.update_column_apply, constr_basis, he.to_matrix_apply], split_ifs, { rw [h, update_same i x v] }, { rw [update_noteq h, he.equiv_fun_apply] }, end /-- From a basis `e : ι → M`, build a linear equivalence between families of vectors `v : ι → M`, and matrices, making the matrix whose columns are the vectors `v i` written in the basis `e`. -/ def to_matrix_equiv {e : ι → M} (he : is_basis R e) : (ι → M) ≃ₗ[R] matrix ι ι R := { to_fun := he.to_matrix, map_add' := λ v w, begin ext i j, change _ = _ + _, simp [he.to_matrix_apply] end, map_smul' := begin intros c v, ext i j, simp [he.to_matrix_apply] end, inv_fun := λ m j, ∑ i, (m i j) • e i, left_inv := begin intro v, ext j, simp [he.to_matrix_apply, he.equiv_fun_total (v j)] end, right_inv := begin intros x, ext k l, simp [he.to_matrix_apply, he.equiv_fun.map_sum, he.equiv_fun.map_smul, fintype.sum_apply k (λ i, x i l • he.equiv_fun (e i)), he.equiv_fun_self] end } end is_basis end is_basis_to_matrix open_locale matrix section det open matrix variables {R ι M M' : Type*} [comm_ring R] [add_comm_group M] [module R M] [add_comm_group M'] [module R M'] [decidable_eq ι] [fintype ι] {v : ι → M} {v' : ι → M'} lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (hv : is_basis R v) (hv' : is_basis R v') : is_unit (linear_equiv_matrix hv hv' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_equiv_matrix_comp hv hv' hv f.symm f).symm end /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {hv : is_basis R v} {hv' : is_basis R v'} (h : is_unit (linear_equiv_matrix hv hv' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := (linear_equiv_matrix hv' hv).symm (linear_equiv_matrix hv hv' f)⁻¹, left_inv := begin rw function.left_inverse_iff_comp, have : f = (linear_equiv_matrix hv hv').symm (linear_equiv_matrix hv hv' f), { rw ← linear_equiv.trans_apply, simp }, conv_lhs { congr, skip, rw this }, rw [linear_map.comp_coe, ← linear_equiv_matrix_symm_mul], simp [h] end, right_inv := begin rw function.right_inverse_iff_comp, have : f = (linear_equiv_matrix hv hv').symm (linear_equiv_matrix hv hv' f), { change f = (linear_equiv_matrix hv hv').trans (linear_equiv_matrix hv hv').symm f, simp }, conv_lhs { congr, rw this }, rw [linear_map.comp_coe, ← linear_equiv_matrix_symm_mul], simp [h] end } variables {e : ι → M} (he : is_basis R e) /-- The determinant of a family of vectors with respect to some basis, as a multilinear map. -/ def is_basis.det : multilinear_map R (λ i : ι, M) R := { to_fun := λ v, det (he.to_matrix v), map_add' := begin intros v i x y, simp only [he.to_matrix_update, linear_map.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [he.to_matrix_update, algebra.id.smul_eq_mul, map_smul_eq_smul_map], apply det_update_column_smul end } lemma is_basis.det_apply (v : ι → M) : he.det v = det (he.to_matrix v) := rfl lemma is_basis.det_self : he.det e = 1 := by simp [he.det_apply] lemma is_basis.iff_det {v : ι → M} : is_basis R v ↔ is_unit (he.det v) := begin split, { intro hv, change is_unit (linear_equiv_matrix he he (equiv_of_is_basis he hv $ equiv.refl ι)).det, apply linear_equiv.is_unit_det }, { intro h, convert linear_equiv.is_basis he (linear_equiv.of_is_unit_det h), ext i, exact (constr_basis he).symm }, end end det namespace matrix section trace variables (n) (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M] /-- The diagonal of a square matrix. -/ def diag : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, map_add' := by { intros, ext, refl, }, map_smul' := by { intros, ext, refl, } } variables {n} {R} {M} @[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl @[simp] lemma diag_one [decidable_eq n] : diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] } @[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl variables (n) (R) (M) /-- The trace of a square matrix. -/ def trace : (matrix n n M) →ₗ[R] M := { to_fun := λ A, ∑ i, diag n R M A i, map_add' := by { intros, apply finset.sum_add_distrib, }, map_smul' := by { intros, simp [finset.smul_sum], } } variables {n} {R} {M} @[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl @[simp] lemma trace_one [decidable_eq n] : trace n R R 1 = fintype.card n := have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl, by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl @[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl @[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) : trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm lemma trace_mul_comm {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) : trace n S S (B ⬝ A) = trace m S S (A ⬝ B) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] end trace section ring variables {R : Type v} [comm_ring R] [decidable_eq n] open linear_map matrix lemma proj_diagonal (i : n) (w : n → R) : (proj i).comp (to_lin (diagonal w)) = (w i) • proj i := by ext j; simp [mul_vec_diagonal] lemma diagonal_comp_std_basis (w : n → R) (i : n) : (diagonal w).to_lin.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i := begin ext a j, simp_rw [linear_map.comp_apply, to_lin_apply, mul_vec_diagonal, linear_map.smul_apply, pi.smul_apply, algebra.id.smul_eq_mul], by_cases i = j, { subst h }, { rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] } end lemma diagonal_to_lin (w : n → R) : (diagonal w).to_lin = linear_map.pi (λi, w i • linear_map.proj i) := by ext v j; simp [mul_vec_diagonal] /-- An invertible matrix yields a linear equivalence from the free module to itself. -/ def to_linear_equiv (P : matrix n n R) (h : is_unit P) : (n → R) ≃ₗ[R] (n → R) := have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h, { inv_fun := P⁻¹.to_lin, left_inv := λ v, show (P⁻¹.to_lin.comp P.to_lin) v = v, by rw [←matrix.mul_to_lin, P.nonsing_inv_mul h', matrix.to_lin_one, linear_map.id_apply], right_inv := λ v, show (P.to_lin.comp P⁻¹.to_lin) v = v, by rw [←matrix.mul_to_lin, P.mul_nonsing_inv h', matrix.to_lin_one, linear_map.id_apply], ..P.to_lin } @[simp] lemma to_linear_equiv_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h) : module.End R (n → R)) = P.to_lin := rfl @[simp] lemma to_linear_equiv_symm_apply (P : matrix n n R) (h : is_unit P) : (↑(P.to_linear_equiv h).symm : module.End R (n → R)) = P⁻¹.to_lin := rfl end ring section vector_space variables {K : Type u} [field K] -- maybe try to relax the universe constraint open linear_map matrix set_option pp.all true lemma rank_vec_mul_vec {m n : Type u} [fintype m] [fintype n] (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin ≤ 1 := begin rw [vec_mul_vec_eq, mul_to_lin], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.lift_eq_nat_iff.mpr (cardinal.fintype_card unit), cardinal.mk_unit], exact le_of_eq (cardinal.lift_one) end lemma ker_diagonal_to_lin [decidable_eq m] (w : m → K) : ker (diagonal w).to_lin = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) := begin rw [← comap_bot, ← infi_ker_proj], simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'], have : univ ⊆ {i : m | w i = 0} ∪ {i : m | w i = 0}ᶜ, { rw set.union_compl_self }, exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) (disjoint_compl {i | w i = 0}) this (finite.of_fintype _)).symm end lemma range_diagonal [decidable_eq m] (w : m → K) : (diagonal w).to_lin.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) := begin dsimp only [mem_set_of_eq], rw [← map_top, ← supr_range_std_basis, map_supr], congr, funext i, rw [← linear_map.range_comp, diagonal_comp_std_basis, ← range_smul'] end lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) : rank (diagonal w).to_lin = fintype.card { i // w i ≠ 0 } := begin have hu : univ ⊆ {i : m | w i = 0}ᶜ ∪ {i : m | w i = 0}, { rw set.compl_union_self }, have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := (disjoint_compl {i | w i = 0}).symm, have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _), have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu, rw [rank, range_diagonal, h₁, ←@dim_fun' K], apply linear_equiv.dim_eq, apply h₂, end end vector_space section finite_dimensional variables {R : Type v} [field R] instance : finite_dimensional R (matrix m n R) := linear_equiv.finite_dimensional (linear_equiv.uncurry R m n).symm /-- The dimension of the space of finite dimensional matrices is the product of the number of rows and columns. -/ @[simp] lemma findim_matrix : finite_dimensional.findim R (matrix m n R) = fintype.card m * fintype.card n := by rw [@linear_equiv.findim_eq R (matrix m n R) _ _ _ _ _ _ (linear_equiv.uncurry R m n), finite_dimensional.findim_fintype_fun_eq_card, fintype.card_prod] end finite_dimensional section reindexing variables {l' m' n' : Type*} [fintype l'] [fintype m'] [fintype n'] variables {R : Type v} /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ matrix m' n' R := { to_fun := λ M i j, M (eₘ.symm i) (eₙ.symm j), inv_fun := λ M i j, M (eₘ i) (eₙ j), left_inv := λ M, by simp, right_inv := λ M, by simp, } @[simp] lemma reindex_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma reindex_symm_apply (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl /-- The natural map that reindexes a matrix's rows and columns with equivalent types is a linear equivalence. -/ def reindex_linear_equiv [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ₗ[R] matrix m' n' R := { map_add' := λ M N, rfl, map_smul' := λ M N, rfl, ..(reindex eₘ eₙ)} @[simp] lemma reindex_linear_equiv_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : reindex_linear_equiv eₘ eₙ M = λ i j, M (eₘ.symm i) (eₙ.symm j) := rfl @[simp] lemma reindex_linear_equiv_symm_apply [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : (reindex_linear_equiv eₘ eₙ).symm M = λ i j, M (eₘ i) (eₙ j) := rfl lemma reindex_mul [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (eₗ : l ≃ l') (M : matrix m n R) (N : matrix n l R) : (reindex_linear_equiv eₘ eₙ M) ⬝ (reindex_linear_equiv eₙ eₗ N) = reindex_linear_equiv eₘ eₗ (M ⬝ N) := begin ext i j, dsimp only [matrix.mul, matrix.dot_product], rw [←finset.univ_map_equiv_to_embedding eₙ, finset.sum_map finset.univ eₙ.to_embedding], simp, end /-- For square matrices, the natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence of algebras. -/ def reindex_alg_equiv [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) : matrix m m R ≃ₐ[R] matrix n n R := { map_mul' := λ M N, by simp only [reindex_mul, linear_equiv.to_fun_apply, mul_eq_mul], commutes' := λ r, by { ext, simp [algebra_map, algebra.to_ring_hom], by_cases h : i = j; simp [h], }, ..(reindex_linear_equiv e e) } @[simp] lemma reindex_alg_equiv_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix m m R) : reindex_alg_equiv e M = λ i j, M (e.symm i) (e.symm j) := rfl @[simp] lemma reindex_alg_equiv_symm_apply [comm_semiring R] [decidable_eq m] [decidable_eq n] (e : m ≃ n) (M : matrix n n R) : (reindex_alg_equiv e).symm M = λ i j, M (e i) (e j) := rfl lemma reindex_transpose (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : (reindex eₘ eₙ M)ᵀ = (reindex eₙ eₘ Mᵀ) := rfl end reindexing end matrix namespace linear_map open_locale matrix /-- The trace of an endomorphism given a basis. -/ def trace_aux (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace ι R R).comp $ linear_equiv_matrix hb hb @[simp] lemma trace_aux_def (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace_aux R hb f = matrix.trace ι R R (linear_equiv_matrix hb hb f) := rfl theorem trace_aux_eq' (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type w} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := linear_map.ext $ λ f, calc matrix.trace ι R R (linear_equiv_matrix hb hb f) = matrix.trace ι R R (linear_equiv_matrix hb hb ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace ι R R (linear_equiv_matrix hc hb linear_map.id ⬝ linear_equiv_matrix hc hc f ⬝ linear_equiv_matrix hb hc linear_map.id) : by rw [matrix.linear_equiv_matrix_comp _ hc, matrix.linear_equiv_matrix_comp _ hc] ... = matrix.trace κ R R (linear_equiv_matrix hc hc f ⬝ linear_equiv_matrix hb hc linear_map.id ⬝ linear_equiv_matrix hc hb linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace κ R R (linear_equiv_matrix hc hc ((f.comp linear_map.id).comp linear_map.id)) : by rw [matrix.linear_equiv_matrix_comp _ hb, matrix.linear_equiv_matrix_comp _ hc] ... = matrix.trace κ R R (linear_equiv_matrix hc hc f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical theorem trace_aux_range (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [fintype ι] {b : ι → M} (hb : is_basis R b) : trace_aux R hb.range = trace_aux R hb := linear_map.ext $ λ f, if H : 0 = 1 then eq_of_zero_eq_one H _ _ else begin haveI : nontrivial R := ⟨⟨0, 1, H⟩⟩, change ∑ i : set.range b, _ = ∑ i : ι, _, simp_rw [matrix.diag_apply], symmetry, convert finset.sum_equiv (equiv.of_injective _ hb.injective) _, ext i, exact (linear_equiv_matrix_range hb hb f i i).symm end /-- where `ι` and `κ` can reside in different universes -/ theorem trace_aux_eq (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type*} [decidable_eq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type*} [decidable_eq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := calc trace_aux R hb = trace_aux R hb.range : by { rw trace_aux_range R hb, congr } ... = trace_aux R hc.range : trace_aux_eq' _ _ _ ... = trace_aux R hc : by { rw trace_aux_range R hc, congr } /-- Trace of an endomorphism independent of basis. -/ def trace (R : Type u) [comm_ring R] (M : Type v) [add_comm_group M] [module R M] : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then trace_aux R (classical.some_spec H) else 0 theorem trace_eq_matrix_trace (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [fintype ι] {b : ι → M} (hb : is_basis R b) (f : M →ₗ[R] M) : trace R M f = matrix.trace ι R R (linear_equiv_matrix hb hb f) := have ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M), from ⟨finset.univ.image b, by { rw [finset.coe_image, finset.coe_univ, set.image_univ], exact hb.range }⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_mul_comm (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ s : finset M, is_basis R (λ x, x : (↑s : set M) → M) then let ⟨s, hb⟩ := H in by { simp_rw [trace_eq_matrix_trace R hb, matrix.linear_equiv_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] end linear_map /-- The natural equivalence between linear endomorphisms of finite free modules and square matrices is compatible with the algebra structures. -/ def alg_equiv_matrix' {R : Type v} [comm_ring R] [decidable_eq n] : module.End R (n → R) ≃ₐ[R] matrix n n R := { map_mul' := matrix.comp_to_matrix_mul, map_add' := linear_equiv_matrix'.map_add, commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix = r • 1, rw ←linear_map.to_matrix_id, refl, }, ..linear_equiv_matrix' } /-- A linear equivalence of two modules induces an equivalence of algebras of their endomorphisms. -/ def linear_equiv.alg_conj {R : Type v} [comm_ring R] {M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] (e : M₁ ≃ₗ[R] M₂) : module.End R M₁ ≃ₐ[R] module.End R M₂ := { map_mul' := λ f g, by apply e.arrow_congr_comp, map_add' := e.conj.map_add, commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id, rw [linear_equiv.map_smul, linear_equiv.conj_id], }, ..e.conj } /-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to square matrices. -/ def alg_equiv_matrix {R : Type v} {M : Type w} [comm_ring R] [add_comm_group M] [module R M] [decidable_eq n] {b : n → M} (h : is_basis R b) : module.End R M ≃ₐ[R] matrix n n R := h.equiv_fun.alg_conj.trans alg_equiv_matrix'
26d8b905fe1a486812ba4c7015b67b05dce42a5a
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/PrettyPrinter/Delaborator/Basic.lean
9d15e2e853e8a1f2fc20f0a46dfd7d8ce913eaf2
[ "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
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
12,977
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Elab.Term import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.PrettyPrinter.Delaborator.TopDownAnalyze /-! The delaborator is the first stage of the pretty printer, and the inverse of the elaborator: it turns fully elaborated `Expr` core terms back into surface-level `Syntax`, omitting some implicit information again and using higher-level syntax abstractions like notations where possible. The exact behavior can be customized using pretty printer options; activating `pp.all` should guarantee that the delaborator is injective and that re-elaborating the resulting `Syntax` round-trips. Pretty printer options can be given not only for the whole term, but also specific subterms. This is used both when automatically refining pp options until round-trip and when interactively selecting pp options for a subterm (both TBD). The association of options to subterms is done by assigning a unique, synthetic Nat position to each subterm derived from its position in the full term. This position is added to the corresponding Syntax object so that elaboration errors and interactions with the pretty printer output can be traced back to the subterm. The delaborator is extensible via the `[delab]` attribute. -/ namespace Lean.PrettyPrinter.Delaborator open Lean.Meta Lean.SubExpr SubExpr open Lean.Elab (Info TermInfo Info.ofTermInfo) structure Context where defaultOptions : Options optionsPerPos : OptionsPerPos currNamespace : Name openDecls : List OpenDecl inPattern : Bool := false -- true when delaborating `match` patterns subExpr : SubExpr structure State where /-- We attach `Elab.Info` at various locations in the `Syntax` output in order to convey its semantics. While the elaborator emits `InfoTree`s, here we have no real text location tree to traverse, so we use a flattened map. -/ infos : PosMap Info := {} /-- See `SubExpr.nextExtraPos`. -/ holeIter : SubExpr.HoleIterator := {} -- Exceptions from delaborators are not expected. We use an internal exception to signal whether -- the delaborator was able to produce a Syntax object. builtin_initialize delabFailureId : InternalExceptionId ← registerInternalExceptionId `delabFailure abbrev DelabM := ReaderT Context (StateRefT State MetaM) abbrev Delab := DelabM Term instance : Inhabited (DelabM α) where default := throw default @[inline] protected def orElse (d₁ : DelabM α) (d₂ : Unit → DelabM α) : DelabM α := do catchInternalId delabFailureId d₁ fun _ => d₂ () protected def failure : DelabM α := throw $ Exception.internal delabFailureId instance : Alternative DelabM where orElse := Delaborator.orElse failure := Delaborator.failure -- HACK: necessary since it would otherwise prefer the instance from MonadExcept instance {α} : OrElse (DelabM α) := ⟨Delaborator.orElse⟩ -- Low priority instances so `read`/`get`/etc default to the whole `Context`/`State` instance (priority := low) : MonadReaderOf SubExpr DelabM where read := Context.subExpr <$> read instance (priority := low) : MonadWithReaderOf SubExpr DelabM where withReader f x := fun ctx => x { ctx with subExpr := f ctx.subExpr } instance (priority := low) : MonadStateOf SubExpr.HoleIterator DelabM where get := State.holeIter <$> get set iter := modify fun ⟨infos, _⟩ => ⟨infos, iter⟩ modifyGet f := modifyGet fun ⟨infos, iter⟩ => let (ret, iter') := f iter; (ret, ⟨infos, iter'⟩) -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : MonadQuotation DelabM := { getCurrMacroScope := pure default getMainModule := pure default withFreshMacroScope := fun x => x } unsafe def mkDelabAttribute : IO (KeyedDeclsAttribute Delab) := KeyedDeclsAttribute.init { builtinName := `builtin_delab, name := `delab, descr := "Register a delaborator. [delab k] registers a declaration of type `Lean.PrettyPrinter.Delaborator.Delab` for the `Lean.Expr` constructor `k`. Multiple delaborators for a single constructor are tried in turn until the first success. If the term to be delaborated is an application of a constant `c`, elaborators for `app.c` are tried first; this is also done for `Expr.const`s (\"nullary applications\") to reduce special casing. If the term is an `Expr.mdata` with a single key `k`, `mdata.k` is tried first.", valueTypeName := `Lean.PrettyPrinter.Delaborator.Delab evalKey := fun _ stx => do let stx ← Attribute.Builtin.getIdent stx let kind := stx.getId if (← Elab.getInfoState).enabled && kind.getRoot == `app then let c := kind.replacePrefix `app .anonymous if (← getEnv).contains c then Elab.addConstInfo stx c none pure kind } `Lean.PrettyPrinter.Delaborator.delabAttribute @[builtin_init mkDelabAttribute] opaque delabAttribute : KeyedDeclsAttribute Delab def getExprKind : DelabM Name := do let e ← getExpr pure $ match e with | Expr.bvar _ => `bvar | Expr.fvar _ => `fvar | Expr.mvar _ => `mvar | Expr.sort _ => `sort | Expr.const c _ => -- we identify constants as "nullary applications" to reduce special casing `app ++ c | Expr.app fn _ => match fn.getAppFn with | Expr.const c _ => `app ++ c | _ => `app | Expr.lam _ _ _ _ => `lam | Expr.forallE _ _ _ _ => `forallE | Expr.letE _ _ _ _ _ => `letE | Expr.lit _ => `lit | Expr.mdata m _ => match m.entries with | [(key, _)] => `mdata ++ key | _ => `mdata | Expr.proj _ _ _ => `proj def getOptionsAtCurrPos : DelabM Options := do let ctx ← read let mut opts := ctx.defaultOptions if let some opts' := ctx.optionsPerPos.find? (← getPos) then for (k, v) in opts' do opts := opts.insert k v return opts /-- Evaluate option accessor, using subterm-specific options if set. -/ def getPPOption (opt : Options → Bool) : DelabM Bool := do return opt (← getOptionsAtCurrPos) def whenPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then failure else d /-- Set the given option at the current position and execute `x` in this context. -/ def withOptionAtCurrPos (k : Name) (v : DataValue) (x : DelabM α) : DelabM α := do let pos ← getPos withReader (fun ctx => let opts' := ctx.optionsPerPos.find? pos |>.getD {} |>.insert k v { ctx with optionsPerPos := ctx.optionsPerPos.insert pos opts' }) x def annotatePos (pos : Pos) (stx : Term) : Term := ⟨stx.raw.setInfo (SourceInfo.synthetic ⟨pos⟩ ⟨pos⟩)⟩ def annotateCurPos (stx : Term) : Delab := return annotatePos (← getPos) stx def getUnusedName (suggestion : Name) (body : Expr) : DelabM Name := do -- Use a nicer binder name than `[anonymous]`. We probably shouldn't do this in all LocalContext use cases, so do it here. let suggestion := if suggestion.isAnonymous then `a else suggestion -- We use this small hack to convert identifiers created using `mkAuxFunDiscr` to simple names let suggestion := suggestion.eraseMacroScopes let lctx ← getLCtx if !lctx.usesUserName suggestion then return suggestion else if (← getPPOption getPPSafeShadowing) && !bodyUsesSuggestion lctx suggestion then return suggestion else return lctx.getUnusedName suggestion where bodyUsesSuggestion (lctx : LocalContext) (suggestion' : Name) : Bool := Option.isSome <| body.find? fun | Expr.fvar fvarId => match lctx.find? fvarId with | none => false | some decl => decl.userName == suggestion' | _ => false def withBindingBodyUnusedName {α} (d : Syntax → DelabM α) : DelabM α := do let n ← getUnusedName (← getExpr).bindingName! (← getExpr).bindingBody! let stxN ← annotateCurPos (mkIdent n) withBindingBody n $ d stxN @[inline] def liftMetaM {α} (x : MetaM α) : DelabM α := liftM x def addTermInfo (pos : Pos) (stx : Syntax) (e : Expr) (isBinder : Bool := false) : DelabM Unit := do let info ← mkTermInfo stx e isBinder modify fun s => { s with infos := s.infos.insert pos info } where mkTermInfo stx e isBinder := return Info.ofTermInfo { elaborator := `Delab, stx := stx, lctx := (← getLCtx), expectedType? := none, expr := e, isBinder := isBinder } def addFieldInfo (pos : Pos) (projName fieldName : Name) (stx : Syntax) (val : Expr) : DelabM Unit := do let info ← mkFieldInfo projName fieldName stx val modify fun s => { s with infos := s.infos.insert pos info } where mkFieldInfo projName fieldName stx val := return Info.ofFieldInfo { projName := projName, fieldName := fieldName, lctx := (← getLCtx), val := val, stx := stx } def annotateTermInfo (stx : Term) : Delab := do let stx ← annotateCurPos stx addTermInfo (← getPos) stx (← getExpr) pure stx partial def delabFor : Name → Delab | Name.anonymous => failure | k => (do annotateTermInfo (← (delabAttribute.getValues (← getEnv) k).firstM id)) -- have `app.Option.some` fall back to `app` etc. <|> if k.isAtomic then failure else delabFor k.getRoot partial def delab : Delab := do checkMaxHeartbeats "delab" let e ← getExpr -- no need to hide atomic proofs if ← pure !e.isAtomic <&&> pure !(← getPPOption getPPProofs) <&&> (try Meta.isProof e catch _ => pure false) then if ← getPPOption getPPProofsWithType then let stx ← withType delab return ← annotateTermInfo (← `((_ : $stx))) else return ← annotateTermInfo (← ``(_)) let k ← getExprKind let stx ← delabFor k <|> (liftM $ show MetaM _ from throwError "don't know how to delaborate '{k}'") if ← getPPOption getPPAnalyzeTypeAscriptions <&&> getPPOption getPPAnalysisNeedsType <&&> pure !e.isMData then let typeStx ← withType delab `(($stx : $typeStx)) >>= annotateCurPos else return stx unsafe def mkAppUnexpanderAttribute : IO (KeyedDeclsAttribute Unexpander) := KeyedDeclsAttribute.init { name := `app_unexpander, descr := "Register an unexpander for applications of a given constant. [app_unexpander c] registers a `Lean.PrettyPrinter.Unexpander` for applications of the constant `c`. The unexpander is passed the result of pre-pretty printing the application *without* implicitly passed arguments. If `pp.explicit` is set to true or `pp.notation` is set to false, it will not be called at all.", valueTypeName := `Lean.PrettyPrinter.Unexpander evalKey := fun _ stx => do Elab.resolveGlobalConstNoOverloadWithInfo (← Attribute.Builtin.getIdent stx) } `Lean.PrettyPrinter.Delaborator.appUnexpanderAttribute @[builtin_init mkAppUnexpanderAttribute] opaque appUnexpanderAttribute : KeyedDeclsAttribute Unexpander end Delaborator open SubExpr (Pos PosMap) open Delaborator (OptionsPerPos topDownAnalyze) def delabCore (e : Expr) (optionsPerPos : OptionsPerPos := {}) (delab := Delaborator.delab) : MetaM (Term × PosMap Elab.Info) := do /- Using `erasePatternAnnotations` here is a bit hackish, but we do it `Expr.mdata` affects the delaborator. TODO: should we fix that? -/ let e ← Meta.erasePatternRefAnnotations e trace[PrettyPrinter.delab.input] "{Std.format e}" let mut opts ← getOptions -- default `pp.proofs` to `true` if `e` is a proof if pp.proofs.get? opts == none then try if ← Meta.isProof e then opts := pp.proofs.set opts true catch _ => pure () let e ← if getPPInstantiateMVars opts then instantiateMVars e else pure e let optionsPerPos ← if !getPPAll opts && getPPAnalyze opts && optionsPerPos.isEmpty then withTheReader Core.Context (fun ctx => { ctx with options := opts }) do topDownAnalyze e else pure optionsPerPos let (stx, {infos := infos, ..}) ← catchInternalId Delaborator.delabFailureId (delab { defaultOptions := opts optionsPerPos := optionsPerPos currNamespace := (← getCurrNamespace) openDecls := (← getOpenDecls) subExpr := SubExpr.mkRoot e inPattern := opts.getInPattern } |>.run { : Delaborator.State }) (fun _ => unreachable!) return (stx, infos) /-- "Delaborate" the given term into surface-level syntax using the default and given subterm-specific options. -/ def delab (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM Term := do let (stx, _) ← delabCore e optionsPerPos return stx builtin_initialize registerTraceClass `PrettyPrinter.delab end Lean.PrettyPrinter
384622b264bacffce9f8405eb785389262aed811
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/multiset/nat_antidiagonal.lean
9b41c72960a5634a9657a53aa9df54e04e803ba2
[ "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
2,630
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 data.multiset.nodup import data.list.nat_antidiagonal /-! # Antidiagonals in ℕ × ℕ as multisets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the antidiagonals of ℕ × ℕ as multisets: the `n`-th antidiagonal is the multiset of pairs `(i, j)` such that `i + j = n`. This is useful for polynomial multiplication and more generally for sums going from `0` to `n`. ## Notes This refines file `data.list.nat_antidiagonal` and is further refined by file `data.finset.nat_antidiagonal`. -/ namespace multiset namespace nat /-- The antidiagonal of a natural number `n` is the multiset of pairs `(i, j)` such that `i + j = n`. -/ def antidiagonal (n : ℕ) : multiset (ℕ × ℕ) := list.nat.antidiagonal n /-- A pair (i, j) is contained in the antidiagonal of `n` if and only if `i + j = n`. -/ @[simp] lemma mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} : x ∈ antidiagonal n ↔ x.1 + x.2 = n := by rw [antidiagonal, mem_coe, list.nat.mem_antidiagonal] /-- The cardinality of the antidiagonal of `n` is `n+1`. -/ @[simp] lemma card_antidiagonal (n : ℕ) : (antidiagonal n).card = n+1 := by rw [antidiagonal, coe_card, list.nat.length_antidiagonal] /-- The antidiagonal of `0` is the list `[(0, 0)]` -/ @[simp] lemma antidiagonal_zero : antidiagonal 0 = {(0, 0)} := rfl /-- The antidiagonal of `n` does not contain duplicate entries. -/ @[simp] lemma nodup_antidiagonal (n : ℕ) : nodup (antidiagonal n) := coe_nodup.2 $ list.nat.nodup_antidiagonal n @[simp] lemma antidiagonal_succ {n : ℕ} : antidiagonal (n + 1) = (0, n + 1) ::ₘ ((antidiagonal n).map (prod.map nat.succ id)) := by simp only [antidiagonal, list.nat.antidiagonal_succ, coe_map, cons_coe] lemma antidiagonal_succ' {n : ℕ} : antidiagonal (n + 1) = (n + 1, 0) ::ₘ ((antidiagonal n).map (prod.map id nat.succ)) := by rw [antidiagonal, list.nat.antidiagonal_succ', ← coe_add, add_comm, antidiagonal, coe_map, coe_add, list.singleton_append, cons_coe] lemma antidiagonal_succ_succ' {n : ℕ} : antidiagonal (n + 2) = (0, n + 2) ::ₘ (n + 2, 0) ::ₘ ((antidiagonal n).map (prod.map nat.succ nat.succ)) := by { rw [antidiagonal_succ, antidiagonal_succ', map_cons, map_map, prod_map], refl } lemma map_swap_antidiagonal {n : ℕ} : (antidiagonal n).map prod.swap = antidiagonal n := by rw [antidiagonal, coe_map, list.nat.map_swap_antidiagonal, coe_reverse] end nat end multiset
2da7f10d287b93e5ee7185e88f02474ddf65cc83
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/nat/bquant.lean
6bc962da2ed6927c4bcfedab0e653289a4520446
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,332
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.nat.bquant Author: Leonardo de Moura Show that "bounded" quantifiers: (∃x, x < n ∧ P x) and (∀x, x < n → P x) are decidable when P is decidable. This module allow us to write if-then-else expressions such as if (∀ x : nat, x < n → ∃ y : nat, y < n ∧ y * y = x) then t else s without assuming classical axioms. More importantly, they can be reduced inside of the Lean kernel. -/ import data.nat.order namespace nat definition bex [reducible] (n : nat) (P : nat → Prop) : Prop := ∃ x, x < n ∧ P x definition ball [reducible] (n : nat) (P : nat → Prop) : Prop := ∀ x, x < n → P x definition not_bex_zero (P : nat → Prop) : ¬ bex 0 P := λ H, obtain (w : nat) (Hw : w < 0 ∧ P w), from H, and.rec_on Hw (λ h₁ h₂, absurd h₁ (not_lt_zero w)) definition bex_succ {P : nat → Prop} {n : nat} (H : bex n P) : bex (succ n) P := obtain (w : nat) (Hw : w < n ∧ P w), from H, and.rec_on Hw (λ hlt hp, exists.intro w (and.intro (lt.step hlt) hp)) definition bex_succ_of_pred {P : nat → Prop} {a : nat} (H : P a) : bex (succ a) P := exists.intro a (and.intro (lt.base a) H) definition not_bex_succ {P : nat → Prop} {n : nat} (H₁ : ¬ bex n P) (H₂ : ¬ P n) : ¬ bex (succ n) P := λ H, obtain (w : nat) (Hw : w < succ n ∧ P w), from H, and.rec_on Hw (λ hltsn hp, or.rec_on (eq_or_lt_of_le hltsn) (λ heq : w = n, absurd (eq.rec_on heq hp) H₂) (λ hltn : w < n, absurd (exists.intro w (and.intro hltn hp)) H₁)) definition ball_zero (P : nat → Prop) : ball zero P := λ x Hlt, absurd Hlt !not_lt_zero definition ball_of_ball_succ {n : nat} {P : nat → Prop} (H : ball (succ n) P) : ball n P := λ x Hlt, H x (lt.step Hlt) definition ball_succ_of_ball {n : nat} {P : nat → Prop} (H₁ : ball n P) (H₂ : P n) : ball (succ n) P := λ (x : nat) (Hlt : x < succ n), or.elim (eq_or_lt_of_le Hlt) (λ heq : x = n, eq.rec_on (eq.rec_on heq rfl) H₂) (λ hlt : x < n, H₁ x hlt) definition not_ball_of_not {n : nat} {P : nat → Prop} (H₁ : ¬ P n) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (H n (lt.base n)) H₁ definition not_ball_succ_of_not_ball {n : nat} {P : nat → Prop} (H₁ : ¬ ball n P) : ¬ ball (succ n) P := λ (H : ball (succ n) P), absurd (ball_of_ball_succ H) H₁ end nat section open nat decidable definition decidable_bex [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (bex n P) := nat.rec_on n (inr (not_bex_zero P)) (λ a ih, decidable.rec_on ih (λ hpos : bex a P, inl (bex_succ hpos)) (λ hneg : ¬ bex a P, decidable.rec_on (H a) (λ hpa : P a, inl (bex_succ_of_pred hpa)) (λ hna : ¬ P a, inr (not_bex_succ hneg hna)))) definition decidable_ball [instance] (n : nat) (P : nat → Prop) [H : decidable_pred P] : decidable (ball n P) := nat.rec_on n (inl (ball_zero P)) (λ n₁ ih, decidable.rec_on ih (λ ih_pos, decidable.rec_on (H n₁) (λ p_pos, inl (ball_succ_of_ball ih_pos p_pos)) (λ p_neg, inr (not_ball_of_not p_neg))) (λ ih_neg, inr (not_ball_succ_of_not_ball ih_neg))) end
147d5fcdab2f42c05e56335b174a75cc4949d4a9
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/module/localized_module.lean
6c33c39d43e93a16baf59437c7b0261a49659932
[ "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
40,925
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang, Jujian Zhang -/ import group_theory.monoid_localization import ring_theory.localization.basic import algebra.algebra.restrict_scalars /-! # Localized Module Given a commutative ring `R`, a multiplicative subset `S ⊆ R` and an `R`-module `M`, we can localize `M` by `S`. This gives us a `localization S`-module. ## Main definitions * `localized_module.r` : the equivalence relation defining this localization, namely `(m, s) ≈ (m', s')` if and only if if there is some `u : S` such that `u • s' • m = u • s • m'`. * `localized_module M S` : the localized module by `S`. * `localized_module.mk` : the canonical map sending `(m, s) : M × S ↦ m/s : localized_module M S` * `localized_module.lift_on` : any well defined function `f : M × S → α` respecting `r` descents to a function `localized_module M S → α` * `localized_module.lift_on₂` : any well defined function `f : M × S → M × S → α` respecting `r` descents to a function `localized_module M S → localized_module M S` * `localized_module.mk_add_mk` : in the localized module `mk m s + mk m' s' = mk (s' • m + s • m') (s * s')` * `localized_module.mk_smul_mk` : in the localized module, for any `r : R`, `s t : S`, `m : M`, we have `mk r s • mk m t = mk (r • m) (s * t)` where `mk r s : localization S` is localized ring by `S`. * `localized_module.is_module` : `localized_module M S` is a `localization S`-module. ## Future work * Redefine `localization` for monoids and rings to coincide with `localized_module`. -/ namespace localized_module universes u v variables {R : Type u} [comm_semiring R] (S : submonoid R) variables (M : Type v) [add_comm_monoid M] [module R M] /--The equivalence relation on `M × S` where `(m1, s1) ≈ (m2, s2)` if and only if for some (u : S), u * (s2 • m1 - s1 • m2) = 0-/ def r : (M × S) → (M × S) → Prop | ⟨m1, s1⟩ ⟨m2, s2⟩ := ∃ (u : S), u • s1 • m2 = u • s2 • m1 lemma r.is_equiv : is_equiv _ (r S M) := { refl := λ ⟨m, s⟩, ⟨1, by rw [one_smul]⟩, trans := λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨m3, s3⟩ ⟨u1, hu1⟩ ⟨u2, hu2⟩, begin use u1 * u2 * s2, -- Put everything in the same shape, sorting the terms using `simp` have hu1' := congr_arg ((•) (u2 * s3)) hu1, have hu2' := congr_arg ((•) (u1 * s1)) hu2, simp only [← mul_smul, smul_assoc, mul_assoc, mul_comm, mul_left_comm] at ⊢ hu1' hu2', rw [hu2', hu1'] end, symm := λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, ⟨u, hu.symm⟩ } instance r.setoid : setoid (M × S) := { r := r S M, iseqv := ⟨(r.is_equiv S M).refl, (r.is_equiv S M).symm, (r.is_equiv S M).trans⟩ } /-- If `S` is a multiplicative subset of a ring `R` and `M` an `R`-module, then we can localize `M` by `S`. -/ @[nolint has_nonempty_instance] def _root_.localized_module : Type (max u v) := quotient (r.setoid S M) section variables {M S} /--The canonical map sending `(m, s) ↦ m/s`-/ def mk (m : M) (s : S) : localized_module S M := quotient.mk ⟨m, s⟩ lemma mk_eq {m m' : M} {s s' : S} : mk m s = mk m' s' ↔ ∃ (u : S), u • s • m' = u • s' • m := quotient.eq @[elab_as_eliminator] lemma induction_on {β : localized_module S M → Prop} (h : ∀ (m : M) (s : S), β (mk m s)) : ∀ (x : localized_module S M), β x := by { rintro ⟨⟨m, s⟩⟩, exact h m s } @[elab_as_eliminator] lemma induction_on₂ {β : localized_module S M → localized_module S M → Prop} (h : ∀ (m m' : M) (s s' : S), β (mk m s) (mk m' s')) : ∀ x y, β x y := by { rintro ⟨⟨m, s⟩⟩ ⟨⟨m', s'⟩⟩, exact h m m' s s' } /--If `f : M × S → α` respects the equivalence relation `localized_module.r`, then `f` descents to a map `localized_module M S → α`. -/ def lift_on {α : Type*} (x : localized_module S M) (f : M × S → α) (wd : ∀ (p p' : M × S) (h1 : p ≈ p'), f p = f p') : α := quotient.lift_on x f wd lemma lift_on_mk {α : Type*} {f : M × S → α} (wd : ∀ (p p' : M × S) (h1 : p ≈ p'), f p = f p') (m : M) (s : S) : lift_on (mk m s) f wd = f ⟨m, s⟩ := by convert quotient.lift_on_mk f wd ⟨m, s⟩ /--If `f : M × S → M × S → α` respects the equivalence relation `localized_module.r`, then `f` descents to a map `localized_module M S → localized_module M S → α`. -/ def lift_on₂ {α : Type*} (x y : localized_module S M) (f : (M × S) → (M × S) → α) (wd : ∀ (p q p' q' : M × S) (h1 : p ≈ p') (h2 : q ≈ q'), f p q = f p' q') : α := quotient.lift_on₂ x y f wd lemma lift_on₂_mk {α : Type*} (f : (M × S) → (M × S) → α) (wd : ∀ (p q p' q' : M × S) (h1 : p ≈ p') (h2 : q ≈ q'), f p q = f p' q') (m m' : M) (s s' : S) : lift_on₂ (mk m s) (mk m' s') f wd = f ⟨m, s⟩ ⟨m', s'⟩ := by convert quotient.lift_on₂_mk f wd _ _ instance : has_zero (localized_module S M) := ⟨mk 0 1⟩ @[simp] lemma zero_mk (s : S) : mk (0 : M) s = 0 := mk_eq.mpr ⟨1, by rw [one_smul, smul_zero, smul_zero, one_smul]⟩ instance : has_add (localized_module S M) := { add := λ p1 p2, lift_on₂ p1 p2 (λ x y, mk (y.2 • x.1 + x.2 • y.1) (x.2 * y.2)) $ λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨m1', s1'⟩ ⟨m2', s2'⟩ ⟨u1, hu1⟩ ⟨u2, hu2⟩, mk_eq.mpr ⟨u1 * u2, begin -- Put everything in the same shape, sorting the terms using `simp` have hu1' := congr_arg ((•) (u2 * s2 * s2')) hu1, have hu2' := congr_arg ((•) (u1 * s1 * s1')) hu2, simp only [smul_add, ← mul_smul, smul_assoc, mul_assoc, mul_comm, mul_left_comm] at ⊢ hu1' hu2', rw [hu1', hu2'] end⟩ } lemma mk_add_mk {m1 m2 : M} {s1 s2 : S} : mk m1 s1 + mk m2 s2 = mk (s2 • m1 + s1 • m2) (s1 * s2) := mk_eq.mpr $ ⟨1, by dsimp only; rw [one_smul]⟩ private lemma add_assoc' (x y z : localized_module S M) : x + y + z = x + (y + z) := begin induction x using localized_module.induction_on with mx sx, induction y using localized_module.induction_on with my sy, induction z using localized_module.induction_on with mz sz, simp only [mk_add_mk, smul_add], refine mk_eq.mpr ⟨1, _⟩, rw [one_smul, one_smul], congr' 1, { rw [mul_assoc] }, { rw [mul_comm, add_assoc, mul_smul, mul_smul, ←mul_smul sx sz, mul_comm, mul_smul], }, end private lemma add_comm' (x y : localized_module S M) : x + y = y + x := localized_module.induction_on₂ (λ m m' s s', by rw [mk_add_mk, mk_add_mk, add_comm, mul_comm]) x y private lemma zero_add' (x : localized_module S M) : 0 + x = x := induction_on (λ m s, by rw [← zero_mk s, mk_add_mk, smul_zero, zero_add, mk_eq]; exact ⟨1, by rw [one_smul, mul_smul, one_smul]⟩) x private lemma add_zero' (x : localized_module S M) : x + 0 = x := induction_on (λ m s, by rw [← zero_mk s, mk_add_mk, smul_zero, add_zero, mk_eq]; exact ⟨1, by rw [one_smul, mul_smul, one_smul]⟩) x instance has_nat_smul : has_smul ℕ (localized_module S M) := { smul := λ n, nsmul_rec n } private lemma nsmul_zero' (x : localized_module S M) : (0 : ℕ) • x = 0 := localized_module.induction_on (λ _ _, rfl) x private lemma nsmul_succ' (n : ℕ) (x : localized_module S M) : n.succ • x = x + n • x := localized_module.induction_on (λ _ _, rfl) x instance : add_comm_monoid (localized_module S M) := { add := (+), add_assoc := add_assoc', zero := 0, zero_add := zero_add', add_zero := add_zero', nsmul := (•), nsmul_zero' := nsmul_zero', nsmul_succ' := nsmul_succ', add_comm := add_comm' } instance {M : Type*} [add_comm_group M] [module R M] : add_comm_group (localized_module S M) := { neg := λ p, lift_on p (λ x, localized_module.mk (-x.1) x.2) (λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, by { rw mk_eq, exact ⟨u, by simpa⟩ }), add_left_neg := λ p, begin obtain ⟨⟨m, s⟩, rfl : mk m s = p⟩ := quotient.exists_rep p, change (mk m s).lift_on (λ x, mk (-x.1) x.2) (λ ⟨m1, s1⟩ ⟨m2, s2⟩ ⟨u, hu⟩, by { rw mk_eq, exact ⟨u, by simpa⟩ }) + mk m s = 0, rw [lift_on_mk, mk_add_mk], simp end, ..(show add_comm_monoid (localized_module S M), by apply_instance) } lemma mk_neg {M : Type*} [add_comm_group M] [module R M] {m : M} {s : S} : mk (-m) s = - mk m s := rfl instance {A : Type*} [semiring A] [algebra R A] {S : submonoid R} : semiring (localized_module S A) := { mul := λ m₁ m₂, lift_on₂ m₁ m₂ (λ x₁ x₂, localized_module.mk (x₁.1 * x₂.1) (x₁.2 * x₂.2)) (begin rintros ⟨a₁, s₁⟩ ⟨a₂, s₂⟩ ⟨b₁, t₁⟩ ⟨b₂, t₂⟩ ⟨u₁, e₁⟩ ⟨u₂, e₂⟩, rw mk_eq, use u₁ * u₂, dsimp only, transitivity (u₁ • t₁ • a₁) • u₂ • t₂ • a₂, rw [← e₁, ← e₂], swap, rw eq_comm, all_goals { rw [smul_smul, mul_mul_mul_comm, ← smul_eq_mul, ← smul_eq_mul A, smul_smul_smul_comm, mul_smul, mul_smul] } end), left_distrib := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_add, mul_add, mul_smul_comm, smul_smul, ← mul_assoc, mul_right_comm] end, right_distrib := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_add, add_mul, smul_smul, ← mul_assoc, smul_mul_assoc, mul_right_comm], end, zero_mul := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [zero_mul, smul_zero]⟩, end, mul_zero := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [mul_zero, smul_zero]⟩, end, mul_assoc := begin intros x₁ x₂ x₃, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, obtain ⟨⟨a₃, s₃⟩, rfl : mk a₃ s₃ = x₃⟩ := quotient.exists_rep x₃, apply mk_eq.mpr _, use 1, simp only [one_mul, smul_smul, ← mul_assoc, mul_right_comm], end, one := mk 1 (1 : S), one_mul := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [one_mul, one_smul]⟩, end, mul_one := begin intros x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, exact mk_eq.mpr ⟨1, by simp only [mul_one, one_smul]⟩, end, ..(show add_comm_monoid (localized_module S A), by apply_instance) } instance {A : Type*} [comm_semiring A] [algebra R A] {S : submonoid R} : comm_semiring (localized_module S A) := { mul_comm := begin intros x₁ x₂, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, exact mk_eq.mpr ⟨1, by simp only [one_smul, mul_comm]⟩ end, ..(show semiring (localized_module S A), by apply_instance) } instance {A : Type*} [ring A] [algebra R A] {S : submonoid R} : ring (localized_module S A) := { ..(show add_comm_group (localized_module S A), by apply_instance), ..(show monoid (localized_module S A), by apply_instance), ..(show distrib (localized_module S A), by apply_instance) } instance {A : Type*} [comm_ring A] [algebra R A] {S : submonoid R} : comm_ring (localized_module S A) := { mul_comm := begin intros x₁ x₂, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, exact mk_eq.mpr ⟨1, by simp only [one_smul, mul_comm]⟩ end, ..(show ring (localized_module S A), by apply_instance) } lemma mk_mul_mk {A : Type*} [semiring A] [algebra R A] {a₁ a₂ : A} {s₁ s₂ : S} : mk a₁ s₁ * mk a₂ s₂ = mk (a₁ * a₂) (s₁ * s₂) := rfl instance : has_smul (localization S) (localized_module S M) := { smul := λ f x, localization.lift_on f (λ r s, lift_on x (λ p, mk (r • p.1) (s * p.2)) begin rintros ⟨m1, t1⟩ ⟨m2, t2⟩ ⟨u, h⟩, refine mk_eq.mpr ⟨u, _⟩, have h' := congr_arg ((•) (s • r)) h, simp only [← mul_smul, smul_assoc, mul_comm, mul_left_comm, submonoid.smul_def, submonoid.coe_mul] at ⊢ h', rw h', end) begin induction x using localized_module.induction_on with m t, rintros r r' s s' h, simp only [lift_on_mk, lift_on_mk, mk_eq], obtain ⟨u, eq1⟩ := localization.r_iff_exists.mp h, use u, have eq1' := congr_arg (• (t • m)) eq1, simp only [← mul_smul, smul_assoc, submonoid.smul_def, submonoid.coe_mul] at ⊢ eq1', ring_nf at ⊢ eq1', rw eq1' end } lemma mk_smul_mk (r : R) (m : M) (s t : S) : localization.mk r s • mk m t = mk (r • m) (s * t) := begin unfold has_smul.smul, rw [localization.lift_on_mk, lift_on_mk], end private lemma one_smul' (m : localized_module S M) : (1 : localization S) • m = m := begin induction m using localized_module.induction_on with m s, rw [← localization.mk_one, mk_smul_mk, one_smul, one_mul], end private lemma mul_smul' (x y : localization S) (m : localized_module S M) : (x * y) • m = x • y • m := begin induction x using localization.induction_on with data, induction y using localization.induction_on with data', rcases ⟨data, data'⟩ with ⟨⟨r, s⟩, ⟨r', s'⟩⟩, induction m using localized_module.induction_on with m t, rw [localization.mk_mul, mk_smul_mk, mk_smul_mk, mk_smul_mk, mul_smul, mul_assoc], end private lemma smul_add' (x : localization S) (y z : localized_module S M) : x • (y + z) = x • y + x • z := begin induction x using localization.induction_on with data, rcases data with ⟨r, u⟩, induction y using localized_module.induction_on with m s, induction z using localized_module.induction_on with n t, rw [mk_smul_mk, mk_smul_mk, mk_add_mk, mk_smul_mk, mk_add_mk, mk_eq], use 1, simp only [one_smul, smul_add, ← mul_smul, submonoid.smul_def, submonoid.coe_mul], ring_nf end private lemma smul_zero' (x : localization S) : x • (0 : localized_module S M) = 0 := begin induction x using localization.induction_on with data, rcases data with ⟨r, s⟩, rw [←zero_mk s, mk_smul_mk, smul_zero, zero_mk, zero_mk], end private lemma add_smul' (x y : localization S) (z : localized_module S M) : (x + y) • z = x • z + y • z := begin induction x using localization.induction_on with datax, induction y using localization.induction_on with datay, induction z using localized_module.induction_on with m t, rcases ⟨datax, datay⟩ with ⟨⟨r, s⟩, ⟨r', s'⟩⟩, rw [localization.add_mk, mk_smul_mk, mk_smul_mk, mk_smul_mk, mk_add_mk, mk_eq], use 1, simp only [one_smul, add_smul, smul_add, ← mul_smul, submonoid.smul_def, submonoid.coe_mul, submonoid.coe_one], rw add_comm, -- Commutativity of addition in the module is not applied by `ring`. ring_nf, end private lemma zero_smul' (x : localized_module S M) : (0 : localization S) • x = 0 := begin induction x using localized_module.induction_on with m s, rw [← localization.mk_zero s, mk_smul_mk, zero_smul, zero_mk], end instance is_module : module (localization S) (localized_module S M) := { smul := (•), one_smul := one_smul', mul_smul := mul_smul', smul_add := smul_add', smul_zero := smul_zero', add_smul := add_smul', zero_smul := zero_smul' } @[simp] lemma mk_cancel_common_left (s' s : S) (m : M) : mk (s' • m) (s' * s) = mk m s := mk_eq.mpr ⟨1, by { simp only [mul_smul, one_smul], rw smul_comm }⟩ @[simp] lemma mk_cancel (s : S) (m : M) : mk (s • m) s = mk m 1 := mk_eq.mpr ⟨1, by simp⟩ @[simp] lemma mk_cancel_common_right (s s' : S) (m : M) : mk (s' • m) (s * s') = mk m s := mk_eq.mpr ⟨1, by simp [mul_smul]⟩ instance is_module' : module R (localized_module S M) := { ..module.comp_hom (localized_module S M) $ (algebra_map R (localization S)) } lemma smul'_mk (r : R) (s : S) (m : M) : r • mk m s = mk (r • m) s := by erw [mk_smul_mk r m 1 s, one_mul] instance {A : Type*} [semiring A] [algebra R A] : algebra (localization S) (localized_module S A) := algebra.of_module begin intros r x₁ x₂, obtain ⟨y, s, rfl : is_localization.mk' _ y s = r⟩ := is_localization.mk'_surjective S r, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, rw [mk_mul_mk, ← localization.mk_eq_mk', mk_smul_mk, mk_smul_mk, mk_mul_mk, mul_assoc, smul_mul_assoc], end begin intros r x₁ x₂, obtain ⟨y, s, rfl : is_localization.mk' _ y s = r⟩ := is_localization.mk'_surjective S r, obtain ⟨⟨a₁, s₁⟩, rfl : mk a₁ s₁ = x₁⟩ := quotient.exists_rep x₁, obtain ⟨⟨a₂, s₂⟩, rfl : mk a₂ s₂ = x₂⟩ := quotient.exists_rep x₂, rw [mk_mul_mk, ← localization.mk_eq_mk', mk_smul_mk, mk_smul_mk, mk_mul_mk, mul_left_comm, mul_smul_comm] end lemma algebra_map_mk {A : Type*} [semiring A] [algebra R A] (a : R) (s : S) : algebra_map _ _ (localization.mk a s) = mk (algebra_map R A a) s := begin rw [algebra.algebra_map_eq_smul_one], change _ • mk _ _ = _, rw [mk_smul_mk, algebra.algebra_map_eq_smul_one, mul_one] end instance : is_scalar_tower R (localization S) (localized_module S M) := restrict_scalars.is_scalar_tower R (localization S) (localized_module S M) instance algebra' {A : Type*} [semiring A] [algebra R A] : algebra R (localized_module S A) := { commutes' := begin intros r x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, dsimp, rw [← localization.mk_one_eq_algebra_map, algebra_map_mk, mk_mul_mk, mk_mul_mk, mul_comm, algebra.commutes], end, smul_def' := begin intros r x, obtain ⟨⟨a, s⟩, rfl : mk a s = x⟩ := quotient.exists_rep x, dsimp, rw [← localization.mk_one_eq_algebra_map, algebra_map_mk, mk_mul_mk, smul'_mk, algebra.smul_def, one_mul], end, ..(algebra_map (localization S) (localized_module S A)).comp (algebra_map R $ localization S), ..(show module R (localized_module S A), by apply_instance) } section variables (S M) /-- The function `m ↦ m / 1` as an `R`-linear map. -/ @[simps] def mk_linear_map : M →ₗ[R] localized_module S M := { to_fun := λ m, mk m 1, map_add' := λ x y, by simp [mk_add_mk], map_smul' := λ r x, (smul'_mk _ _ _).symm } end /-- For any `s : S`, there is an `R`-linear map given by `a/b ↦ a/(b*s)`. -/ @[simps] def div_by (s : S) : localized_module S M →ₗ[R] localized_module S M := { to_fun := λ p, p.lift_on (λ p, mk p.1 (s * p.2)) $ λ ⟨a, b⟩ ⟨a', b'⟩ ⟨c, eq1⟩, mk_eq.mpr ⟨c, begin rw [mul_smul, mul_smul, smul_comm c, eq1, smul_comm s]; apply_instance, end⟩, map_add' := λ x y, x.induction_on₂ (begin intros m₁ m₂ t₁ t₂, simp only [mk_add_mk, localized_module.lift_on_mk, mul_smul, ←smul_add, mul_assoc, mk_cancel_common_left s], rw show s * (t₁ * t₂) = t₁ * (s * t₂), by { ext, simp only [submonoid.coe_mul], ring }, end) y, map_smul' := λ r x, x.induction_on $ by { intros, simp [localized_module.lift_on_mk, smul'_mk] } } lemma div_by_mul_by (s : S) (p : localized_module S M) : div_by s (algebra_map R (module.End R (localized_module S M)) s p) = p := p.induction_on begin intros m t, simp only [localized_module.lift_on_mk, module.algebra_map_End_apply, smul'_mk, div_by_apply], erw mk_cancel_common_left s t, end lemma mul_by_div_by (s : S) (p : localized_module S M) : algebra_map R (module.End R (localized_module S M)) s (div_by s p) = p := p.induction_on begin intros m t, simp only [localized_module.lift_on_mk, div_by_apply, module.algebra_map_End_apply, smul'_mk], erw mk_cancel_common_left s t, end end end localized_module section is_localized_module universes u v variables {R : Type*} [comm_ring R] (S : submonoid R) variables {M M' M'' : Type*} [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] (f : M →ₗ[R] M') (g : M →ₗ[R] M'') /-- The characteristic predicate for localized module. `is_localized_module S f` describes that `f : M ⟶ M'` is the localization map identifying `M'` as `localized_module S M`. -/ class is_localized_module : Prop := (map_units [] : ∀ (x : S), is_unit (algebra_map R (module.End R M') x)) (surj [] : ∀ y : M', ∃ (x : M × S), x.2 • y = f x.1) (eq_iff_exists [] : ∀ {x₁ x₂}, f x₁ = f x₂ ↔ ∃ c : S, c • x₂ = c • x₁) namespace localized_module /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `localized_module S M → M''`. -/ noncomputable def lift' (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (localized_module S M) → M'' := λ m, m.lift_on (λ p, (h $ p.2).unit⁻¹ $ g p.1) $ λ ⟨m, s⟩ ⟨m', s'⟩ ⟨c, eq1⟩, begin generalize_proofs h1 h2, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←h2.unit⁻¹.1.map_smul], symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff], dsimp, have : c • s • g m' = c • s' • g m, { erw [←g.map_smul, ←g.map_smul, ←g.map_smul, ←g.map_smul, eq1], refl, }, have : function.injective (h c).unit.inv, { rw function.injective_iff_has_left_inverse, refine ⟨(h c).unit, _⟩, intros x, change ((h c).unit.1 * (h c).unit.inv) x = x, simp only [units.inv_eq_coe_inv, is_unit.mul_coe_inv, linear_map.one_apply], }, apply_fun (h c).unit.inv, erw [units.inv_eq_coe_inv, module.End_algebra_map_is_unit_inv_apply_eq_iff, ←(h c).unit⁻¹.1.map_smul], symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←g.map_smul, ←g.map_smul, ←g.map_smul, ←g.map_smul, eq1], refl, end lemma lift'_mk (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (m : M) (s : S) : localized_module.lift' S g h (localized_module.mk m s) = (h s).unit⁻¹.1 (g m) := rfl lemma lift'_add (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (x y) : localized_module.lift' S g h (x + y) = localized_module.lift' S g h x + localized_module.lift' S g h y := localized_module.induction_on₂ begin intros a a' b b', erw [localized_module.lift'_mk, localized_module.lift'_mk, localized_module.lift'_mk], dsimp, generalize_proofs h1 h2 h3, erw [map_add, module.End_algebra_map_is_unit_inv_apply_eq_iff, smul_add, ←h2.unit⁻¹.1.map_smul, ←h3.unit⁻¹.1.map_smul], congr' 1; symmetry, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, mul_smul, ←map_smul], refl, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, mul_comm, mul_smul, ←map_smul], refl, end x y lemma lift'_smul (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (r : R) (m) : r • localized_module.lift' S g h m = localized_module.lift' S g h (r • m) := m.induction_on begin intros a b, rw [localized_module.lift'_mk, localized_module.smul'_mk, localized_module.lift'_mk], generalize_proofs h1 h2, erw [←h1.unit⁻¹.1.map_smul, ←g.map_smul], end /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `localized_module S M → M''`. -/ noncomputable def lift (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (localized_module S M) →ₗ[R] M'' := { to_fun := localized_module.lift' S g h, map_add' := localized_module.lift'_add S g h, map_smul' := λ r x, by rw [localized_module.lift'_smul, ring_hom.id_apply] } /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then `lift g m s = s⁻¹ • g m`. -/ lemma lift_mk (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (m : M) (s : S) : localized_module.lift S g h (localized_module.mk m s) = (h s).unit⁻¹.1 (g m) := rfl /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `lift g ∘ mk_linear_map = g`. -/ lemma lift_comp (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (lift S g h).comp (mk_linear_map S M) = g := begin ext x, dsimp, rw localized_module.lift_mk, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, one_smul], end /-- If `g` is a linear map `M → M''` such that all scalar multiplication by `s : S` is invertible and `l` is another linear map `localized_module S M ⟶ M''` such that `l ∘ mk_linear_map = g` then `l = lift g` -/ lemma lift_unique (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (l : localized_module S M →ₗ[R] M'') (hl : l.comp (localized_module.mk_linear_map S M) = g) : localized_module.lift S g h = l := begin ext x, induction x using localized_module.induction_on with m s, rw [localized_module.lift_mk], erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←hl, linear_map.coe_comp, function.comp_app, localized_module.mk_linear_map_apply, ←l.map_smul, localized_module.smul'_mk], congr' 1, rw localized_module.mk_eq, refine ⟨1, _⟩, simp only [one_smul], refl, end end localized_module instance localized_module_is_localized_module : is_localized_module S (localized_module.mk_linear_map S M) := { map_units := λ s, ⟨⟨algebra_map R (module.End R (localized_module S M)) s, localized_module.div_by s, fun_like.ext _ _ $ localized_module.mul_by_div_by s, fun_like.ext _ _ $ localized_module.div_by_mul_by s⟩, fun_like.ext _ _ $ λ p, p.induction_on $ by { intros, refl }⟩, surj := λ p, p.induction_on begin intros m t, refine ⟨⟨m, t⟩, _⟩, erw [localized_module.smul'_mk, localized_module.mk_linear_map_apply, submonoid.coe_subtype, localized_module.mk_cancel t ], end, eq_iff_exists := λ m1 m2, { mp := λ eq1, by simpa only [one_smul] using localized_module.mk_eq.mp eq1, mpr := λ ⟨c, eq1⟩, localized_module.mk_eq.mpr ⟨c, by simpa only [one_smul] using eq1⟩ } } namespace is_localized_module variable [is_localized_module S f] /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, there is a canonical map `localized_module S M ⟶ M'`. -/ noncomputable def from_localized_module' : localized_module S M → M' := λ p, p.lift_on (λ x, (is_localized_module.map_units f x.2).unit⁻¹ (f x.1)) begin rintros ⟨a, b⟩ ⟨a', b'⟩ ⟨c, eq1⟩, dsimp, generalize_proofs h1 h2, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←h2.unit⁻¹.1.map_smul, module.End_algebra_map_is_unit_inv_apply_eq_iff', ←linear_map.map_smul, ←linear_map.map_smul], exact ((is_localized_module.eq_iff_exists S f).mpr ⟨c, eq1⟩).symm, end @[simp] lemma from_localized_module'_mk (m : M) (s : S) : from_localized_module' S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma from_localized_module'_add (x y : localized_module S M) : from_localized_module' S f (x + y) = from_localized_module' S f x + from_localized_module' S f y := localized_module.induction_on₂ begin intros a a' b b', simp only [localized_module.mk_add_mk, from_localized_module'_mk], generalize_proofs h1 h2 h3, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, smul_add, ←h2.unit⁻¹.1.map_smul, ←h3.unit⁻¹.1.map_smul, map_add], congr' 1, all_goals { erw [module.End_algebra_map_is_unit_inv_apply_eq_iff'] }, { dsimp, erw [mul_smul, f.map_smul], refl, }, { dsimp, erw [mul_comm, f.map_smul, mul_smul], refl, }, end x y lemma from_localized_module'_smul (r : R) (x : localized_module S M) : r • from_localized_module' S f x = from_localized_module' S f (r • x) := localized_module.induction_on begin intros a b, rw [from_localized_module'_mk, localized_module.smul'_mk, from_localized_module'_mk], generalize_proofs h1, erw [f.map_smul, h1.unit⁻¹.1.map_smul], refl, end x /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, there is a canonical map `localized_module S M ⟶ M'`. -/ noncomputable def from_localized_module : localized_module S M →ₗ[R] M' := { to_fun := from_localized_module' S f, map_add' := from_localized_module'_add S f, map_smul' := λ r x, by rw [from_localized_module'_smul, ring_hom.id_apply] } lemma from_localized_module_mk (m : M) (s : S) : from_localized_module S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma from_localized_module.inj : function.injective $ from_localized_module S f := λ x y eq1, begin induction x using localized_module.induction_on with a b, induction y using localized_module.induction_on with a' b', simp only [from_localized_module_mk] at eq1, generalize_proofs h1 h2 at eq1, erw [module.End_algebra_map_is_unit_inv_apply_eq_iff, ←linear_map.map_smul, module.End_algebra_map_is_unit_inv_apply_eq_iff'] at eq1, erw [localized_module.mk_eq, ←is_localized_module.eq_iff_exists S f, f.map_smul, f.map_smul, eq1], refl, end lemma from_localized_module.surj : function.surjective $ from_localized_module S f := λ x, let ⟨⟨m, s⟩, eq1⟩ := is_localized_module.surj S f x in ⟨localized_module.mk m s, by { rw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, ←eq1], refl }⟩ lemma from_localized_module.bij : function.bijective $ from_localized_module S f := ⟨from_localized_module.inj _ _, from_localized_module.surj _ _⟩ /-- If `(M', f : M ⟶ M')` satisfies universal property of localized module, then `M'` is isomorphic to `localized_module S M` as an `R`-module. -/ @[simps] noncomputable def iso : localized_module S M ≃ₗ[R] M' := { ..from_localized_module S f, ..equiv.of_bijective (from_localized_module S f) $ from_localized_module.bij _ _} lemma iso_apply_mk (m : M) (s : S) : iso S f (localized_module.mk m s) = (is_localized_module.map_units f s).unit⁻¹ (f m) := rfl lemma iso_symm_apply_aux (m : M') : (iso S f).symm m = localized_module.mk (is_localized_module.surj S f m).some.1 (is_localized_module.surj S f m).some.2 := begin generalize_proofs _ h2, apply_fun (iso S f) using linear_equiv.injective _, rw [linear_equiv.apply_symm_apply], simp only [iso_apply, linear_map.to_fun_eq_coe, from_localized_module_mk], erw [module.End_algebra_map_is_unit_inv_apply_eq_iff', h2.some_spec], end lemma iso_symm_apply' (m : M') (a : M) (b : S) (eq1 : b • m = f a) : (iso S f).symm m = localized_module.mk a b := (iso_symm_apply_aux S f m).trans $ localized_module.mk_eq.mpr $ begin generalize_proofs h1, erw [←is_localized_module.eq_iff_exists S f, f.map_smul, f.map_smul, ←h1.some_spec, ←mul_smul, mul_comm, mul_smul, eq1], end lemma iso_symm_comp : (iso S f).symm.to_linear_map.comp f = localized_module.mk_linear_map S M := begin ext m, rw [linear_map.comp_apply, localized_module.mk_linear_map_apply], change (iso S f).symm _ = _, rw [iso_symm_apply'], exact one_smul _ _, end /-- If `M'` is a localized module and `g` is a linear map `M' → M''` such that all scalar multiplication by `s : S` is invertible, then there is a linear map `M' → M''`. -/ noncomputable def lift (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : M' →ₗ[R] M'' := (localized_module.lift S g h).comp (iso S f).symm.to_linear_map lemma lift_comp (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) : (lift S f g h).comp f = g := begin dunfold is_localized_module.lift, rw [linear_map.comp_assoc], convert localized_module.lift_comp S g h, exact iso_symm_comp _ _, end lemma lift_unique (g : M →ₗ[R] M'') (h : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) (l : M' →ₗ[R] M'') (hl : l.comp f = g) : lift S f g h = l := begin dunfold is_localized_module.lift, rw [localized_module.lift_unique S g h (l.comp (iso S f).to_linear_map), linear_map.comp_assoc, show (iso S f).to_linear_map.comp (iso S f).symm.to_linear_map = linear_map.id, from _, linear_map.comp_id], { rw [linear_equiv.comp_to_linear_map_symm_eq, linear_map.id_comp], }, { rw [linear_map.comp_assoc, ←hl], congr' 1, ext x, erw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, one_smul], }, end /-- Universal property from localized module: If `(M', f : M ⟶ M')` is a localized module then it satisfies the following universal property: For every `R`-module `M''` which every `s : S`-scalar multiplication is invertible and for every `R`-linear map `g : M ⟶ M''`, there is a unique `R`-linear map `l : M' ⟶ M''` such that `l ∘ f = g`. ``` M -----f----> M' | / |g / | / l v / M'' ``` -/ lemma is_universal : ∀ (g : M →ₗ[R] M'') (map_unit : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)), ∃! (l : M' →ₗ[R] M''), l.comp f = g := λ g h, ⟨lift S f g h, lift_comp S f g h, λ l hl, (lift_unique S f g h l hl).symm⟩ lemma ring_hom_ext (map_unit : ∀ (x : S), is_unit ((algebra_map R (module.End R M'')) x)) ⦃j k : M' →ₗ[R] M''⦄ (h : j.comp f = k.comp f) : j = k := by { rw [←lift_unique S f (k.comp f) map_unit j h, lift_unique], refl } /-- If `(M', f)` and `(M'', g)` both satisfy universal property of localized module, then `M', M''` are isomorphic as `R`-module -/ noncomputable def linear_equiv [is_localized_module S g] : M' ≃ₗ[R] M'' := (iso S f).symm.trans (iso S g) variable {S} lemma smul_injective (s : S) : function.injective (λ m : M', s • m) := ((module.End_is_unit_iff _).mp (is_localized_module.map_units f s)).injective lemma smul_inj (s : S) (m₁ m₂ : M') : s • m₁ = s • m₂ ↔ m₁ = m₂ := (smul_injective f s).eq_iff /-- `mk' f m s` is the fraction `m/s` with respect to the localization map `f`. -/ noncomputable def mk' (m : M) (s : S) : M' := from_localized_module S f (localized_module.mk m s) lemma mk'_smul (r : R) (m : M) (s : S) : mk' f (r • m) s = r • mk' f m s := by { delta mk', rw [← localized_module.smul'_mk, linear_map.map_smul] } lemma mk'_add_mk' (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ + mk' f m₂ s₂ = mk' f (s₂ • m₁ + s₁ • m₂) (s₁ * s₂) := by { delta mk', rw [← map_add, localized_module.mk_add_mk] } @[simp] lemma mk'_zero (s : S) : mk' f 0 s = 0 := by rw [← zero_smul R (0 : M), mk'_smul, zero_smul] variable (S) @[simp] lemma mk'_one (m : M) : mk' f m (1 : S) = f m := by { delta mk', rw [from_localized_module_mk, module.End_algebra_map_is_unit_inv_apply_eq_iff, submonoid.coe_one, one_smul] } variable {S} @[simp] lemma mk'_cancel (m : M) (s : S) : mk' f (s • m) s = f m := by { delta mk', rw [localized_module.mk_cancel, ← mk'_one S f], refl } @[simp] lemma mk'_cancel' (m : M) (s : S) : s • mk' f m s = f m := by rw [submonoid.smul_def, ← mk'_smul, ← submonoid.smul_def, mk'_cancel] @[simp] lemma mk'_cancel_left (m : M) (s₁ s₂ : S) : mk' f (s₁ • m) (s₁ * s₂) = mk' f m s₂ := by { delta mk', rw localized_module.mk_cancel_common_left } @[simp] lemma mk'_cancel_right (m : M) (s₁ s₂ : S) : mk' f (s₂ • m) (s₁ * s₂) = mk' f m s₁ := by { delta mk', rw localized_module.mk_cancel_common_right } lemma mk'_add (m₁ m₂ : M) (s : S) : mk' f (m₁ + m₂) s = mk' f m₁ s + mk' f m₂ s := by { rw [mk'_add_mk', ← smul_add, mk'_cancel_left] } lemma mk'_eq_mk'_iff (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ = mk' f m₂ s₂ ↔ ∃ s : S, s • s₁ • m₂ = s • s₂ • m₁ := by { delta mk', rw [(from_localized_module.inj S f).eq_iff, localized_module.mk_eq] } lemma mk'_neg {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m : M) (s : S) : mk' f (-m) s = - mk' f m s := by { delta mk', rw [localized_module.mk_neg, map_neg] } lemma mk'_sub {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m₁ m₂ : M) (s : S) : mk' f (m₁ - m₂) s = mk' f m₁ s - mk' f m₂ s := by rw [sub_eq_add_neg, sub_eq_add_neg, mk'_add, mk'_neg] lemma mk'_sub_mk' {M M' : Type*} [add_comm_group M] [add_comm_group M'] [module R M] [module R M'] (f : M →ₗ[R] M') [is_localized_module S f] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ - mk' f m₂ s₂ = mk' f (s₂ • m₁ - s₁ • m₂) (s₁ * s₂) := by rw [sub_eq_add_neg, ← mk'_neg, mk'_add_mk', smul_neg, ← sub_eq_add_neg] lemma mk'_mul_mk'_of_map_mul {M M' : Type*} [semiring M] [semiring M'] [module R M] [algebra R M'] (f : M →ₗ[R] M') (hf : ∀ m₁ m₂, f (m₁ * m₂) = f m₁ * f m₂) [is_localized_module S f] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f m₁ s₁ * mk' f m₂ s₂ = mk' f (m₁ * m₂) (s₁ * s₂) := begin symmetry, apply (module.End_algebra_map_is_unit_inv_apply_eq_iff _ _ _).mpr, simp_rw [submonoid.coe_mul, ← smul_eq_mul], rw [smul_smul_smul_comm, ← mk'_smul, ← mk'_smul], simp_rw [← submonoid.smul_def, mk'_cancel, smul_eq_mul, hf], end lemma mk'_mul_mk' {M M' : Type*} [semiring M] [semiring M'] [algebra R M] [algebra R M'] (f : M →ₐ[R] M') [is_localized_module S f.to_linear_map] (m₁ m₂ : M) (s₁ s₂ : S) : mk' f.to_linear_map m₁ s₁ * mk' f.to_linear_map m₂ s₂ = mk' f.to_linear_map (m₁ * m₂) (s₁ * s₂) := mk'_mul_mk'_of_map_mul f.to_linear_map f.map_mul m₁ m₂ s₁ s₂ variables {f} @[simp] lemma mk'_eq_iff {m : M} {s : S} {m' : M'} : mk' f m s = m' ↔ f m = s • m' := by rw [← smul_inj f s, submonoid.smul_def, ← mk'_smul, ← submonoid.smul_def, mk'_cancel] @[simp] lemma mk'_eq_zero {m : M} (s : S) : mk' f m s = 0 ↔ f m = 0 := by rw [mk'_eq_iff, smul_zero] variable (f) lemma mk'_eq_zero' {m : M} (s : S) : mk' f m s = 0 ↔ ∃ s' : S, s' • m = 0 := by simp_rw [← mk'_zero f (1 : S), mk'_eq_mk'_iff, smul_zero, one_smul, eq_comm] lemma mk_eq_mk' (s : S) (m : M) : localized_module.mk m s = mk' (localized_module.mk_linear_map S M) m s := by rw [eq_comm, mk'_eq_iff, submonoid.smul_def, localized_module.smul'_mk, ← submonoid.smul_def, localized_module.mk_cancel, localized_module.mk_linear_map_apply] variable (S) lemma eq_zero_iff {m : M} : f m = 0 ↔ ∃ s' : S, s' • m = 0 := (mk'_eq_zero (1 : S)).symm.trans (mk'_eq_zero' f _) lemma mk'_surjective : function.surjective (function.uncurry $ mk' f : M × S → M') := begin intro x, obtain ⟨⟨m, s⟩, e : s • x = f m⟩ := is_localized_module.surj S f x, exact ⟨⟨m, s⟩, mk'_eq_iff.mpr e.symm⟩ end section algebra lemma mk_of_algebra {R S S' : Type*} [comm_ring R] [comm_ring S] [comm_ring S'] [algebra R S] [algebra R S'] (M : submonoid R) (f : S →ₐ[R] S') (h₁ : ∀ x ∈ M, is_unit (algebra_map R S' x)) (h₂ : ∀ y, ∃ (x : S × M), x.2 • y = f x.1) (h₃ : ∀ x, f x = 0 → ∃ m : M, m • x = 0) : is_localized_module M f.to_linear_map := begin replace h₃ := λ x, iff.intro (h₃ x) (λ ⟨⟨m, hm⟩, e⟩, (h₁ m hm).mul_left_cancel $ by { rw ← algebra.smul_def, simpa [submonoid.smul_def] using f.congr_arg e }), constructor, { intro x, rw module.End_is_unit_iff, split, { rintros a b (e : x • a = x • b), simp_rw [submonoid.smul_def, algebra.smul_def] at e, exact (h₁ x x.2).mul_left_cancel e }, { intro a, refine ⟨((h₁ x x.2).unit⁻¹ : _) * a, _⟩, change (x : R) • (_ * a) = _, rw [algebra.smul_def, ← mul_assoc, is_unit.mul_coe_inv, one_mul] } }, { exact h₂ }, { intros, dsimp, rw [eq_comm, ← sub_eq_zero, ← map_sub, h₃], simp_rw [smul_sub, sub_eq_zero] }, end end algebra end is_localized_module end is_localized_module
05d1e9c0f020ffb63f5a0f05f4285aac5955a506
b147e1312077cdcfea8e6756207b3fa538982e12
/logic/function.lean
5407f32b67c7875bf41845b9cd3fc786213d542a
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,359
lean
/- Copyright (c) 2016 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Miscellaneous function constructions and lemmas. -/ import logic.basic data.option universes u v w namespace function section variables {α : Sort u} {β : Sort v} {f : α → β} lemma hfunext {α α': Sort u} {β : α → Sort v} {β' : α' → Sort v} {f : Πa, β a} {f' : Πa, β' a} (hα : α = α') (h : ∀a a', a == a' → f a == f' a') : f == f' := begin subst hα, have : ∀a, f a == f' a, { intro a, exact h a a (heq.refl a) }, have : β = β', { funext a, exact type_eq_of_heq (this a) }, subst this, apply heq_of_eq, funext a, exact eq_of_heq (this a) end lemma funext_iff {β : α → Sort*} {f₁ f₂ : Π (x : α), β x} : f₁ = f₂ ↔ (∀a, f₁ a = f₂ a) := iff.intro (assume h a, h ▸ rfl) funext lemma comp_apply {α : Sort u} {β : Sort v} {φ : Sort w} (f : β → φ) (g : α → β) (a : α) : (f ∘ g) a = f (g a) := rfl @[simp] theorem injective.eq_iff (I : injective f) {a b : α} : f a = f b ↔ a = b := ⟨@I _ _, congr_arg f⟩ def injective.decidable_eq [decidable_eq β] (I : injective f) : decidable_eq α | a b := decidable_of_iff _ I.eq_iff theorem cantor_surjective {α} (f : α → α → Prop) : ¬ function.surjective f | h := let ⟨D, e⟩ := h (λ a, ¬ f a a) in (iff_not_self (f D D)).1 $ iff_of_eq (congr_fun e D) theorem cantor_injective {α : Type*} (f : (α → Prop) → α) : ¬ function.injective f | i := cantor_surjective (λ a b, ∀ U, a = f U → U b) $ surjective_of_has_right_inverse ⟨f, λ U, funext $ λ a, propext ⟨λ h, h U rfl, λ h' U' e, i e ▸ h'⟩⟩ /-- `g` is a partial inverse to `f` (an injective but not necessarily surjective function) if `g y = some x` implies `f x = y`, and `g y = none` implies that `y` is not in the range of `f`. -/ def is_partial_inv {α β} (f : α → β) (g : β → option α) : Prop := ∀ x y, g y = some x ↔ f x = y theorem is_partial_inv_left {α β} {f : α → β} {g} (H : is_partial_inv f g) (x) : g (f x) = some x := (H _ _).2 rfl theorem injective_of_partial_inv {α β} {f : α → β} {g} (H : is_partial_inv f g) : injective f := λ a b h, option.some.inj $ ((H _ _).2 h).symm.trans ((H _ _).2 rfl) theorem injective_of_partial_inv_right {α β} {f : α → β} {g} (H : is_partial_inv f g) (x y b) (h₁ : b ∈ g x) (h₂ : b ∈ g y) : x = y := ((H _ _).1 h₁).symm.trans ((H _ _).1 h₂) theorem left_inverse.comp_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id := funext h theorem right_inverse.comp_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id := funext h theorem left_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) := assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a] theorem right_inverse.comp {γ} {f : α → β} {g : β → α} {h : β → γ} {i : γ → β} (hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) := left_inverse.comp hh hf local attribute [instance] classical.prop_decidable /-- We can use choice to construct explicitly a partial inverse for a given injective function `f`. -/ noncomputable def partial_inv {α β} (f : α → β) (b : β) : option α := if h : ∃ a, f a = b then some (classical.some h) else none theorem partial_inv_of_injective {α β} {f : α → β} (I : injective f) : is_partial_inv f (partial_inv f) | a b := ⟨λ h, if h' : ∃ a, f a = b then begin rw [partial_inv, dif_pos h'] at h, injection h with h, subst h, apply classical.some_spec h' end else by rw [partial_inv, dif_neg h'] at h; contradiction, λ e, e ▸ have h : ∃ a', f a' = f a, from ⟨_, rfl⟩, (dif_pos h).trans (congr_arg _ (I $ classical.some_spec h))⟩ theorem partial_inv_left {α β} {f : α → β} (I : injective f) : ∀ x, partial_inv f (f x) = some x := is_partial_inv_left (partial_inv_of_injective I) end section inv_fun variables {α : Type u} [inhabited α] {β : Sort v} {f : α → β} {s : set α} {a : α} {b : β} local attribute [instance] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else default α theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_eq' (h : ∀x∈s, ∀y∈s, f x = f y → x = y) (ha : a ∈ s) : inv_fun_on f s (f a) = a := have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h _ (inv_fun_on_mem this) _ ha (inv_fun_on_eq this) theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = default α := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] /-- The inverse of a function (which is a left inverse if `f` is injective and a right inverse if `f` is surjective). -/ noncomputable def inv_fun (f : α → β) : β → α := inv_fun_on f set.univ theorem inv_fun_eq (h : ∃a, f a = b) : f (inv_fun f b) = b := inv_fun_on_eq $ let ⟨a, ha⟩ := h in ⟨a, trivial, ha⟩ theorem inv_fun_eq_of_injective_of_right_inverse {g : β → α} (hf : injective f) (hg : right_inverse g f) : inv_fun f = g := funext $ assume b, hf begin rw [hg b], exact inv_fun_eq ⟨g b, hg b⟩ end lemma right_inverse_inv_fun (hf : surjective f) : right_inverse (inv_fun f) f := assume b, inv_fun_eq $ hf b lemma left_inverse_inv_fun (hf : injective f) : left_inverse (inv_fun f) f := assume b, have f (inv_fun f (f b)) = f b, from inv_fun_eq ⟨b, rfl⟩, hf this lemma inv_fun_surjective (hf : injective f) : surjective (inv_fun f) := surjective_of_has_right_inverse ⟨_, left_inverse_inv_fun hf⟩ lemma inv_fun_comp (hf : injective f) : inv_fun f ∘ f = id := funext $ left_inverse_inv_fun hf lemma injective.has_left_inverse (hf : injective f) : has_left_inverse f := ⟨inv_fun f, left_inverse_inv_fun hf⟩ lemma injective_iff_has_left_inverse : injective f ↔ has_left_inverse f := ⟨injective.has_left_inverse, injective_of_has_left_inverse⟩ end inv_fun section surj_inv variables {α : Sort u} {β : Sort v} {f : α → β} /-- The inverse of a surjective function. (Unlike `inv_fun`, this does not require `α` to be inhabited.) -/ noncomputable def surj_inv {f : α → β} (h : surjective f) (b : β) : α := classical.some (h b) lemma surj_inv_eq (h : surjective f) (b) : f (surj_inv h b) = b := classical.some_spec (h b) lemma right_inverse_surj_inv (hf : surjective f) : right_inverse (surj_inv hf) f := surj_inv_eq hf lemma left_inverse_surj_inv (hf : bijective f) : left_inverse (surj_inv hf.2) f := right_inverse_of_injective_of_left_inverse hf.1 (right_inverse_surj_inv hf.2) lemma surjective.has_right_inverse (hf : surjective f) : has_right_inverse f := ⟨_, right_inverse_surj_inv hf⟩ lemma surjective_iff_has_right_inverse : surjective f ↔ has_right_inverse f := ⟨surjective.has_right_inverse, surjective_of_has_right_inverse⟩ lemma bijective_iff_has_inverse : bijective f ↔ ∃ g, left_inverse g f ∧ right_inverse g f := ⟨λ hf, ⟨_, left_inverse_surj_inv hf, right_inverse_surj_inv hf.2⟩, λ ⟨g, gl, gr⟩, ⟨injective_of_left_inverse gl, surjective_of_has_right_inverse ⟨_, gr⟩⟩⟩ lemma injective_surj_inv (h : surjective f) : injective (surj_inv h) := injective_of_has_left_inverse ⟨f, right_inverse_surj_inv h⟩ end surj_inv section update variables {α : Sort u} {β : α → Sort v} [decidable_eq α] def update (f : Πa, β a) (a' : α) (v : β a') (a : α) : β a := if h : a = a' then eq.rec v h.symm else f a @[simp] lemma update_same {a : α} {v : β a} {f : Πa, β a} : update f a v a = v := dif_pos rfl @[simp] lemma update_noteq {a a' : α} {v : β a'} {f : Πa, β a} (h : a ≠ a') : update f a' v a = f a := dif_neg h end update end function
f1cd08aee610182240d77843112ac8d8eb5b7109
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finset/basic.lean
d5f90462749fcbf600ba482ca22b49a742a4d064
[ "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
111,219
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro -/ import data.int.basic import data.multiset.finset_ops import tactic.apply import tactic.monotonicity import tactic.nth_rewrite /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. `finset.card`, the size of a finset is defined in `data.finset.card`. This is then used to define `fintype.card`, the size of a type. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.sup`/`finset.bUnion` for finite unions. * `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. See `finset.inf` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.union`: see "The lattice structure on subsets of finsets" * `finset.inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.product`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open multiset subtype nat function universes u variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := s.2.erase_dup instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type u} : has_coe_to_sort (finset α) (Type u) := ⟨λ s, {x // x ∈ s}⟩ instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (s : finset ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α (∈ s) } instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) : can_lift (s → α) (ι → α) := pi_finset_coe.can_lift ι (λ _, α) s instance finset_coe.can_lift (s : finset α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } @[simp, norm_cast] lemma coe_sort_coe (s : finset α) : ((s : set α) : Sort*) = s := rfl /-! ### Subset and strict subset relations -/ section subset variables {s t : finset α} instance : has_subset (finset α) := ⟨λ s t, ∀ ⦃a⦄, a ∈ s → a ∈ t⟩ instance : has_ssubset (finset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := λ s a, id, le_trans := λ s t u hst htu a ha, htu $ hst ha, le_antisymm := λ s t hst hts, ext $ λ a, ⟨@hst _, @hts _⟩ } instance : is_refl (finset α) (⊆) := has_le.le.is_refl instance : is_trans (finset α) (⊆) := has_le.le.is_trans instance : is_antisymm (finset α) (⊆) := has_le.le.is_antisymm instance : is_irrefl (finset α) (⊂) := has_lt.lt.is_irrefl instance : is_trans (finset α) (⊂) := has_lt.lt.is_trans instance : is_asymm (finset α) (⊂) := has_lt.lt.is_asymm instance : is_nonstrict_strict_order (finset α) (⊆) (⊂) := ⟨λ _ _, iff.rfl⟩ lemma subset_def : s ⊆ t ↔ s.1 ⊆ t.1 := iff.rfl lemma ssubset_def : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ protected lemma subset.rfl {s :finset α} : s ⊆ s := subset.refl _ protected theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset lemma not_mem_mono {s t : finset α} (h : s ⊆ t) {a : α} : a ∉ t → a ∉ s := mt $ @h _ theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff theorem not_subset (s t : finset α) : ¬(s ⊆ t) ↔ ∃ x ∈ s, ¬(x ∈ t) := by simp only [←finset.coe_subset, set.not_subset, exists_prop, finset.mem_coe] @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h end subset -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans /-! ### Order embedding from `finset α` to `set α` -/ /-- Coercion to `set α` as an `order_embedding`. -/ def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩ @[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl @[simp] lemma nonempty_coe_sort (s : finset α) : nonempty ↥s ↔ s.nonempty := nonempty_subtype alias coe_nonempty ↔ _ finset.nonempty.to_set lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero @[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ := λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := by { rw nonempty_iff_ne_empty, exact not_not, } theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem is_empty_elim /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : finset α)) : x = y := mem_singleton.1 h theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl lemma singleton_injective : injective (singleton : α → finset α) := λ a b h, mem_singleton.1 (h ▸ mem_singleton_self _) theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := singleton_injective.eq_iff @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } @[simp, norm_cast] lemma coe_eq_singleton {α : Type*} {s : finset α} {a : α} : (s : set α) = {a} ↔ s = {a} := by rw [←finset.coe_singleton, finset.coe_inj] lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { intros h, subst h, simp, }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, }, end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := begin split, { intro hs, apply or.imp_right _ s.eq_empty_or_nonempty, rintro ⟨t, ht⟩, apply subset.antisymm hs, rwa [singleton_subset_iff, ←mem_singleton.1 (hs ht)] }, rintro (rfl | rfl), { exact empty_subset _ }, exact subset.refl _, end @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] lemma mem_cons_self (a : α) (s : finset α) {h} : a ∈ cons a s h := mem_cons.2 $ or.inl rfl @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] @[simp] lemma coe_cons {a s h} : (@cons α a s h : set α) = insert a s := by { ext, simp } @[simp] lemma cons_subset_cons {a s hs t ht} : @cons α a s hs ⊆ cons a t ht ↔ s ⊆ t := by rwa [← coe_subset, coe_cons, coe_cons, set.insert_subset_insert_iff, coe_subset] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty section /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype end lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- To prove a proposition about a nonempty `s : finset α`, it suffices to show it holds for all singletons and that if it holds for nonempty `t : finset α`, then it also holds for the `finset` obtained by inserting an element in `t`. -/ @[elab_as_eliminator] lemma nonempty.cons_induction {α : Type*} {p : Π s : finset α, s.nonempty → Prop} (h₀ : ∀ a, p {a} (singleton_nonempty _)) (h₁ : ∀ ⦃a⦄ s (h : a ∉ s) hs, p s hs → p (finset.cons a s h) (nonempty_cons h)) {s : finset α} (hs : s.nonempty) : p s hs := begin induction s using finset.cons_induction with a t ha h, { exact (not_nonempty_empty hs).elim, }, obtain rfl | ht := t.eq_empty_or_nonempty, { exact h₀ a }, { exact h₁ t ha ht (h ht) } end /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s₁ t₁ s₂ t₂ : finset α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∪ s₂ ⊆ t₁ ∪ t₂ := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_subset_left {s₁ s₂ s₃ : finset α} (h : s₁ ∪ s₂ ⊆ s₃) : s₁ ⊆ s₃ := subset.trans (subset_union_left _ _) h theorem union_subset_right {s₁ s₂ s₃ : finset α} (h : s₁ ∪ s₂ ⊆ s₃) : s₂ ⊆ s₃ := subset.trans (subset_union_right _ _) h theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma exists_mem_subset_of_subset_bUnion_of_directed_on {α ι : Type*} {f : ι → set α} {c : set ι} {a : ι} (hac : a ∈ c) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { intros, use [a, hac], simp }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hic : i ∈ c, hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hjc, hbj⟩ : ∃ j ∈ c, b ∈ f j, by simpa [set.mem_Union₂] using hbtc (t.mem_insert_self b), rcases hc j hjc i hic with ⟨k, hkc, hk, hk'⟩, use [k, hkc], rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ -- TODO: some of these results may have simpler proofs, once there are enough results -- to obtain the `lattice` instance. theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl instance {α : Type u} : order_bot (finset α) := { bot := ∅, bot_le := empty_subset } @[simp] lemma bot_eq_empty {α : Type u} : (⊥ : finset α) = ∅ := rfl instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } @[simp] theorem union_left_idem (s t : finset α) : s ∪ (s ∪ t) = s ∪ t := sup_left_idem @[simp] theorem union_right_idem (s t : finset α) : s ∪ t ∪ t = s ∪ t := sup_right_idem @[simp] theorem inter_left_idem (s t : finset α) : s ∩ (s ∩ t) = s ∩ t := inf_left_idem @[simp] theorem inter_right_idem (s t : finset α) : s ∩ t ∩ t = s ∩ t := inf_right_idem theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff {s₁ s₂ s₃ : finset α} : s₁ ∪ s₂ ⊆ s₃ ↔ s₁ ⊆ s₃ ∧ s₂ ⊆ s₃ := (sup_le_iff : s₁ ⊔ s₂ ≤ s₃ ↔ s₁ ≤ s₃ ∧ s₂ ≤ s₃) lemma subset_inter_iff {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ ∩ s₃ ↔ s₁ ⊆ s₂ ∧ s₁ ⊆ s₃ := (le_inf_iff : s₁ ≤ s₂ ⊓ s₃ ↔ s₁ ≤ s₂ ∧ s₁ ≤ s₃) theorem inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := (inf_eq_left : s ⊓ t = s ↔ s ≤ t) theorem inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := (inf_eq_right : t ⊓ s = s ↔ s ≤ t) lemma ite_subset_union (s s' : finset α) (P : Prop) [decidable P] : ite P s s' ⊆ s ∪ s' := ite_le_sup s s' P lemma inter_subset_ite (s s' : finset α) (P : Prop) [decidable P] : s ∩ s' ⊆ ite P s s' := inf_le_ite s s' P /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 -- While this can be solved by `simp`, this lemma is eligible for `dsimp` @[nolint simp_nf, simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl @[simp] lemma erase_singleton (a : α) : ({a} : finset α).erase a = ∅ := begin ext x, rw [mem_erase, mem_singleton, not_and_self], refl, end theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ lemma subset_erase {a : α} {s t : finset α} : s ⊆ t.erase a ↔ s ⊆ t ∧ a ∉ s := ⟨λ h, ⟨h.trans (erase_subset _ _), λ ha, not_mem_erase _ _ (h ha)⟩, λ h b hb, mem_erase.2 ⟨ne_of_mem_of_not_mem hb h.2, h.1 hb⟩⟩ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h @[simp] theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h lemma erase_idem {a : α} {s : finset α} : erase (erase s a) a = erase s a := by simp lemma erase_right_comm {a b : α} {s : finset α} : erase (erase s a) b = erase (erase s b) a := by { ext x, simp only [mem_erase, ←and_assoc], rw and_comm (x ≠ a) } theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp /-! ### sdiff -/ variables {s t : finset α} {a : α} /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le tsub_le_self s₁.2⟩⟩ @[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff : a ∈ s \ t ↔ a ∈ s ∧ a ∉ t := mem_sub_of_nodup s.2 @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.order_bot } lemma not_mem_sdiff_of_mem_right (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := sup_sdiff_cancel_right h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := sdiff_inf @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := sdiff_inf_self_left @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := sdiff_inf_self_right @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := sdiff_bot @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem sdiff_union_self_eq_union : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left lemma union_sdiff_symm : s ∪ (t \ s) = t ∪ (s \ t) := sup_sdiff_symm lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma sdiff_eq_empty_iff_subset : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma sdiff_ssubset (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt (le_iff_subset.2 h) ht.ne_empty lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } @[simp] lemma sdiff_singleton_not_mem_eq_self (s : finset α) {a : α} (ha : a ∉ s) : s \ {a} = s := by simp only [sdiff_singleton_eq_erase, ha, erase_eq_of_not_mem, not_false_iff] lemma sdiff_erase {A : finset α} {x : α} (hx : x ∈ A) : A \ A.erase x = {x} := begin rw [← sdiff_singleton_eq_erase, sdiff_sdiff_right_self], exact inf_eq_right.2 (singleton_subset_iff.2 hx), end lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_sdiff_eq_self (h : t ⊆ s) : s \ (s \ t) = t := sdiff_sdiff_eq_self h lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] -- TODO: fix this in norm_cast @[norm_cast move] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, simp only [← piecewise_coe, coe_insert, ← set.piecewise_insert], end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ lemma monotone_filter_left (p : α → Prop) [decidable_pred p] : monotone (filter p) := λ _ _, filter_subset_filter p lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := multiset.subset_of_le (multiset.monotone_filter_right s.val h) @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_erase (a : α) (s : finset α) : filter p (erase s a) = erase (filter p s) a := by { ext x, simp only [and_assoc, mem_filter, iff_self, mem_erase] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ tsub_pos_of_lt $ mem_range.1 hx @[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 := ⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne', λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩ @[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] lemma nonempty_range_succ : (range $ n + 1).nonempty := nonempty_range_iff.2 n.succ_ne_zero end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply tsub_add_cancel_of_le, simpa using j.2 end, right_inv := λ j, add_tsub_cancel_right _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 n.erase_dup.symm lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l = l' := by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} := by rw [singleton_eq_cons, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq] @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } lemma val_le_iff_val_subset {a : finset α} {b : multiset α} : a.val ≤ b ↔ a.val ⊆ b := multiset.le_iff_subset a.nodup end finset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := by { rintro ⟨⟨l⟩, hl⟩ _, exact ⟨l, hl, (to_finset_eq hl).symm⟩ } theorem to_finset_surjective : surjective (to_finset : list α → finset α) := λ s, let ⟨l, _, hls⟩ := to_finset_surj_on (set.mem_univ s) in ⟨l, hls⟩ lemma to_finset_eq_iff_perm_erase_dup {l l' : list α} : l.to_finset = l'.to_finset ↔ l.erase_dup ~ l'.erase_dup := by simp [finset.ext_iff, perm_ext (nodup_erase_dup _) (nodup_erase_dup _)] lemma to_finset.ext_iff {a b : list α} : a.to_finset = b.to_finset ↔ ∀ x, x ∈ a ↔ x ∈ b := by simp only [finset.ext_iff, mem_to_finset] lemma to_finset.ext {a b : list α} : (∀ x, x ∈ a ↔ x ∈ b) → a.to_finset = b.to_finset := to_finset.ext_iff.mpr lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_erase_dup.mpr h.erase_dup lemma perm_of_nodup_nodup_to_finset_eq {l l' : list α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l ~ l' := begin rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h end @[simp] lemma to_finset_append {l l' : list α} : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) lemma to_finset_repeat_of_ne_zero {a : α} {n : ℕ} (hn : n ≠ 0): (list.repeat a n).to_finset = {a} := by { ext x, simp [hn, list.mem_repeat] } @[simp] lemma to_finset_union (l l' : list α) : (l ∪ l').to_finset = l.to_finset ∪ l'.to_finset := by {ext, simp} @[simp] lemma to_finset_inter (l l' : list α) : (l ∩ l').to_finset = l.to_finset ∩ l'.to_finset := by {ext, simp} @[simp] lemma to_finset_eq_empty_iff (l : list α) : l.to_finset = ∅ ↔ l = nil := by { cases l; simp } end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl @[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s := by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ } /-- If the only elements outside `s` are those left fixed by `σ`, then mapping by `σ` has no effect. -/ lemma map_perm {σ : equiv.perm α} (hs : {a | σ a ≠ a} ⊆ s) : s.map (σ : α ↪ α) = s := begin ext i, rw mem_map, obtain hi | hi := eq_or_ne (σ i) i, { refine ⟨_, λ h, ⟨i, h, hi⟩⟩, rintro ⟨j, hj, h⟩, rwa σ.injective (hi.trans h.symm) }, { refine iff_of_true ⟨σ.symm i, hs $ λ h, hi _, σ.apply_symm_apply _⟩ (hs hi), convert congr_arg σ h; exact (σ.apply_symm_apply _).symm } end theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f := mem_map_of_mem f x.prop @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f := calc ↑(s.map f) = f '' s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) : s.map (equiv.cast h).to_embedding == s := by { subst h, simp } theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl @[simp] theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪o finset β := order_embedding.of_map_le_iff (map f) (λ _ _, map_subset_map) @[simp] theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := (map_embedding f).injective.eq_iff @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := eq_of_veq (map_filter _ _ _) theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := coe_injective $ by simp only [coe_map, coe_union, set.image_union] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := coe_injective $ by simp only [coe_map, coe_inter, set.image_inter f.injective] @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := coe_injective $ by simp only [coe_map, coe_singleton, set.image_singleton] @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ @[simp] lemma map_nonempty : (s.map f).nonempty ↔ s.nonempty := by rw [nonempty_iff_ne_empty, nonempty_iff_ne_empty, ne.def, map_eq_empty] alias map_nonempty ↔ _ finset.nonempty.map lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f g : α → β} {s : finset α} {a b : β} @[simp] lemma mem_image : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] lemma mem_image_of_mem (f : α → β) {a} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ @[simp] lemma mem_image_const : a ∈ s.image (const α b) ↔ s.nonempty ∧ b = a := begin rw mem_image, simp only [exists_prop, const_apply, exists_and_distrib_right], refl, end lemma mem_image_const_self : a ∈ s.image (const α a) ↔ s.nonempty := mem_image_const.trans $ and_iff_left rfl instance [can_lift β α] : can_lift (finset β) (finset α) := { cond := λ s, ∀ x ∈ s, can_lift.cond α x, coe := image can_lift.coe, prf := begin rintro ⟨⟨l⟩, hd : l.nodup⟩ hl, lift l to list α using hl, refine ⟨⟨l, list.nodup_of_nodup_map _ hd⟩, ext $ λ a, _⟩, simp end } lemma image_congr (h : (s : set α).eq_on f g) : finset.image f s = finset.image g s := by { ext, simp_rw mem_image, exact bex_congr (λ x hx, by rw h hx) } lemma _root_.function.injective.mem_finset_image {f : α → β} (hf : function.injective f) {s : finset α} {x : α} : f x ∈ s.image f ↔ x ∈ s := begin refine ⟨λ h, _, finset.mem_image_of_mem f⟩, obtain ⟨y, hy, heq⟩ := mem_image.1 h, exact hf heq ▸ hy, end lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ @[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty := ⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := (nodup_map_on H s.2).erase_dup @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] @[simp] theorem image_id' [decidable_eq α] : s.image (λ x, x) = s := image_id theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] lemma image_erase [decidable_eq α] {f : α → β} (hf : injective f) (s : finset α) (a : α) : (s.erase a).image f = (s.image f).erase (f a) := begin ext b, simp only [mem_image, exists_prop, mem_erase], split, { rintro ⟨a', ⟨haa', ha'⟩, rfl⟩, exact ⟨hf.ne haa', a', ha', rfl⟩ }, { rintro ⟨h, a', ha', rfl⟩, exact ⟨a', ⟨ne_of_apply_ne _ h, ha'⟩, rfl⟩ } end @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := begin split, { rintros ⟨i, hi⟩, simp only [mem_image, exists_prop, mem_range], exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ }, { rintro h, simp only [mem_image, exists_prop, set.mem_range, mem_range] at *, rcases h with ⟨i, hi, ha⟩, use ⟨i, ha⟩ }, end lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) lemma range_add (a b : ℕ) : range (a + b) = range a ∪ (range b).map (add_left_embedding a) := by { rw [←val_inj, union_val], exact multiset.range_add_eq_union a b } @[simp] lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_image_coe [decidable_eq α] {s : finset α} : s.attach.image coe = s := finset.attach_image_val @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq (s.map f).2.erase_dup.symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] @[simp] lemma map_erase [decidable_eq α] (f : α ↪ β) (s : finset α) (a : α) : (s.erase a).map f = (s.map f).erase (f a) := by { simp_rw map_eq_image, exact s.image_erase f.2 a } /-! ### Subtype -/ /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl @[mono] lemma subtype_mono {p : α → Prop} [decidable_pred p] : monotone (finset.subtype p) := λ s t h x hx, mem_subtype.2 $ h $ mem_subtype.1 hx /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, simp [and_comm _ (_ = _), @and.left_comm _ (_ = _), and_comm (p x) (x ∈ s)] end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, letI : can_lift β t := ⟨f ∘ coe, λ y, y ∈ f '' t, λ y ⟨x, hxt, hy⟩, ⟨⟨x, hxt⟩, hy⟩⟩, lift s to finset t using h, refine ⟨s.map (embedding.subtype _), map_subtype_subset _, _⟩, ext y, simp end lemma range_sdiff_zero {n : ℕ} : range (n + 1) \ {0} = (range n).image nat.succ := begin induction n with k hk, { simp }, nth_rewrite 1 range_succ, rw [range_succ, image_insert, ←hk, insert_sdiff_of_not_mem], simp end end image lemma _root_.multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm section to_list /-- Produce a list of the elements in the finite set using choice. -/ @[reducible] noncomputable def to_list (s : finset α) : list α := s.1.to_list lemma nodup_to_list (s : finset α) : s.to_list.nodup := by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup } @[simp] lemma mem_to_list {a : α} (s : finset α) : a ∈ s.to_list ↔ a ∈ s := by { rw [to_list, ←multiset.mem_coe, multiset.coe_to_list], exact iff.rfl } @[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := by simp [to_list] @[simp, norm_cast] lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := by { classical, ext, simp } @[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s := by { ext, simp } lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) : ∃ (l : list α), l.nodup ∧ l.to_finset = s := ⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩ lemma to_list_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).to_list ~ a :: s.to_list := (list.perm_ext (nodup_to_list _) (by simp [h, nodup_to_list s])).2 $ λ x, by simp only [list.mem_cons_iff, finset.mem_to_list, finset.mem_cons] lemma to_list_insert [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : (insert a s).to_list ~ a :: s.to_list := cons_eq_insert _ _ h ▸ to_list_cons _ end to_list section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop] @[simp] lemma coe_bUnion : (s.bUnion t : set β) = ⋃ x ∈ (s : set α), t x := by simp only [set.ext_iff, mem_bUnion, set.mem_Union, iff_self, mem_coe, implies_true_iff] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] theorem bUnion_congr {s₁ s₂ : finset α} {t₁ t₂ : α → finset β} (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.bUnion t₁ = s₂.bUnion t₂ := ext $ λ x, by simp [hs, ht] { contextual := tt } theorem bUnion_subset {s' : finset β} : s.bUnion t ⊆ s' ↔ ∀ x ∈ s, t x ⊆ s' := by simp only [subset_iff, mem_bUnion]; exact ⟨λ H a ha b hb, H ⟨a, ha, hb⟩, λ H b ⟨a, ha, hb⟩, H a ha hb⟩ @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := begin classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] end theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bUnion t = s.bUnion (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bUnion_insert, ih]) theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bUnion t).image f = s.bUnion (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bUnion_insert, image_union, ih]) lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) : (s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) := begin ext, simp only [finset.mem_bUnion, exists_prop], simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc], rw exists_comm, end theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem {s : finset α} (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := begin apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)), exact subset_of_eq singleton_bUnion.symm, end @[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β] {s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h, λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩ lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm] @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := by { rw bUnion_singleton, exact image_id } lemma filter_bUnion (s : finset α) (f : α → finset β) (p : β → Prop) [decidable_pred p] : (s.bUnion f).filter p = s.bUnion (λ a, (f a).filter p) := begin ext b, simp only [mem_bUnion, exists_prop, mem_filter], split, { rintro ⟨⟨a, ha, hba⟩, hb⟩, exact ⟨a, ha, hba, hb⟩ }, { rintro ⟨a, ha, hba, hb⟩, exact ⟨⟨a, ha, hba⟩, hb⟩ } end lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λa, s.filter $ (λc, f c = a)) = s := ext $ λ b, by simpa using h b lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s := bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g) lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } @[simp] lemma bUnion_nonempty : (s.bUnion t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty, ← exists_and_distrib_left, @exists_swap α] lemma nonempty.bUnion (hs : s.nonempty) (ht : ∀ x ∈ s, (t x).nonempty) : (s.bUnion t).nonempty := bUnion_nonempty.2 $ hs.imp $ λ x hx, ⟨hx, ht x hx⟩ end bUnion /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] lemma not_disjoint_iff {s t : finset α} : ¬disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t := not_forall.trans $ exists_congr $ λ a, begin rw [finset.inf_eq_inter, finset.mem_inter], exact not_not, end theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem disjoint_singleton_left {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton_right {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans disjoint_singleton_left @[simp] lemma disjoint_singleton {a b : α} : disjoint ({a} : finset α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton] @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_filter_filter_neg (s : finset α) (p : α → Prop) [decidable_pred p] : disjoint (s.filter p) (s.filter $ λ a, ¬ p a) := (disjoint_filter.2 $ λ a _, id).symm lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } end disjoint /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp } @[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl @[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr := by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] } end equiv namespace multiset variable [decidable_eq α] lemma disjoint_to_finset {m1 m2 : multiset α} : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset namespace list variable [decidable_eq α] lemma disjoint_to_finset_iff_disjoint {l l' : list α} : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' := multiset.disjoint_to_finset end list
2850180e9d5de094483743e8861dc98bc04b59ac
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/03_Propositions_and_Proofs.org.30.lean
cd0ac84e699581e79a0760b18560923c296c40ec
[]
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
343
lean
/- page 42 -/ import standard variables p q : Prop theorem and_swap : p ∧ q ↔ q ∧ p := iff.intro (assume H : p ∧ q, show q ∧ p, from and.intro (and.right H) (and.left H)) (assume H : q ∧ p, show p ∧ q, from and.intro (and.right H) (and.left H)) -- BEGIN premise H : p ∧ q example : q ∧ p := iff.mp (and_swap p q) H -- END
f02b331b2b099d046d40ab82464ce74fc356a744
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/library/init/algebra/classes.lean
9af0964932c08b149890da1aca9fc591a71b6751
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,851
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 -/ prelude import init.logic universes u class is_commutative (α : Type u) (op : α → α → α) : Prop := (comm : ∀ a b, op a b = op b a) class is_associative (α : Type u) (op : α → α → α) : Prop := (assoc : ∀ a b c, op (op a b) c = op a (op b c)) -- TODO: better notation for out_param class is_left_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_id : ∀ a, op o a = a) class is_right_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_id : ∀ a, op a o = a) class is_left_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_null : ∀ a, op o a = o) class is_right_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_null : ∀ a, op a o = o) class is_left_cancel (α : Type u) (op : α → α → α) : Prop := (left_cancel : ∀ a b c, op a b = op a c → b = c) class is_right_cancel (α : Type u) (op : α → α → α) : Prop := (right_cancel : ∀ a b c, op a b = op c b → a = c) class is_idempotent (α : Type u) (op : α → α → α) : Prop := (idempotent : ∀ a, op a a = a) class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (left_distrib : ∀ a b c, op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c)) class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (right_distrib : ∀ a b c, op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c)) class is_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (left_inv : ∀ a, op (inv a) a = o) class is_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (right_inv : ∀ a, op a (inv a) = o) class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (left_inv : ∀ a, p a → op (inv a) a = o) class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (right_inv : ∀ a, p a → op a (inv a) = o) class is_distinct (α : Type u) (a : α) (b : α) : Prop := (distinct : a ≠ b) /- -- The following type class doesn't seem very useful, a regular simp lemma should work for this. class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out_param $ β → α) : Prop := (inv : ∀ a, g (f a) = a) -- The following one can also be handled using a regular simp lemma class is_idempotent (α : Type u) (f : α → α) : Prop := (idempotent : ∀ a, f (f a) = f a) -/
80aa1737765fe7a38db9955b0eafccfde6792967
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/ring_theory/noetherian.lean
4050516074fb106cade420bea70bc3ba236e761d
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
23,017
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal_operations import linear_algebra.basis import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff zero_ne_one hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
315eb15e90389a862f875b972a0b72c00f7c0ddc
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/measure_theory/integration.lean
4824b6d4fd2f27d263e1b161c4f1bc9a7166d840
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
56,289
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl Lebesgue integral on `ennreal`. We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. -/ import algebra.pi_instances measure_theory.measure_space measure_theory.borel_space noncomputable theory open set (hiding restrict restrict_apply) filter open_locale classical topological_space namespace measure_theory variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (measurable_sn : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := by cases f; cases g; congr; exact funext H /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ ∃ a, f a = b := finite.mem_to_finset lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := iff.intro (by simp [set.eq_empty_iff_forall_not_mem, mem_range]) (by simp [set.eq_empty_iff_forall_not_mem, mem_range]) /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_subset (set.finite_singleton b) $ by rintro _ ⟨a, rfl⟩; simp⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ @[simp] theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl lemma range_const (α) [measurable_space α] [ne : nonempty α] (b : β) : (const α b).range = {b} := begin ext b', simp [mem_range], tauto end lemma is_measurable_cut (p : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | p a b}) : is_measurable {a | p a (f a)} := begin rw (_ : {a | p a (f a)} = ⋃ b ∈ set.range f, {a | p a b} ∩ f ⁻¹' {b}), { exact is_measurable.bUnion (countable_finite f.finite) (λ b _, is_measurable.inter (h b) (f.measurable_sn _)) }, ext a, simp, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ end theorem preimage_measurable (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, by simp [is_measurable.const]) /-- A simple function is measurable -/ theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, preimage_measurable f s def ite {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨λ a, if a ∈ s then f a else g a, λ x, by letI : measurable_space β := ⊤; exact measurable.if hs f.measurable g.measurable _ trivial, finite_subset (finite_union f.finite g.finite) begin rintro _ ⟨a, rfl⟩, by_cases a ∈ s; simp [h], exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] end⟩ @[simp] theorem ite_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : ite hs f g a = if a ∈ s then f a else g a := rfl /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, is_measurable_cut (λa b, g b a ∈ ({c} : set γ)) f (λ b, (g b).measurable_sn c), finite_subset (finite_bUnion f.finite (λ b, (g b).finite)) $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict [has_zero β] (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then ite hs f (const α 0) else const α 0 @[simp] theorem restrict_apply [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by unfold_coes; simp [restrict, hs]; apply ite_apply hs theorem restrict_preimage [has_zero β] (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by ext a; dsimp [preimage]; rw [restrict_apply]; by_cases a ∈ s; simp [h, hs, ht] /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) @[simp] theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := begin ext c, simp only [mem_range, exists_prop, mem_range, finset.mem_image, map_apply], split, { rintros ⟨a, rfl⟩, exact ⟨f a, ⟨_, rfl⟩, rfl⟩ }, { rintros ⟨_, ⟨a, rfl⟩, rfl⟩, exact ⟨_, rfl⟩ } end lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = (⋃b∈f.range.filter (λb, g b ∈ s), f ⁻¹' {b}) := begin /- True because `f` only takes finitely many values. -/ ext a', simp only [mem_Union, set.mem_preimage, exists_prop, set.mem_preimage, map_apply, finset.mem_filter, mem_range, mem_singleton_iff, exists_eq_right'], split, { assume eq, exact ⟨⟨_, rfl⟩, eq⟩ }, { rintros ⟨_, eq⟩, exact eq } end lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = (⋃b∈f.range.filter (λb, g b = c), f ⁻¹' {b}) := begin rw map_preimage, have : (λb, g b = c) = λb, g b ∈ _root_.singleton c, funext, rw [eq_iff_iff, mem_singleton_iff], rw this end /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← prod_singleton_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp] lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl @[simp] lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := { add := (+), zero := 0, add_assoc := assume f g h, ext (assume a, add_assoc _ _ _), zero_add := assume f, ext (assume a, zero_add _), add_zero := assume f, ext (assume a, add_zero _) } instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := { add_comm := λ f g, ext (λa, add_comm _ _), .. simple_func.add_monoid } instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ instance [add_group β] : add_group (α →ₛ β) := { neg := has_neg.neg, add_left_neg := λf, ext (λa, add_left_neg _), .. simple_func.add_monoid } instance [add_comm_group β] : add_comm_group (α →ₛ β) := { add_comm := λ f g, ext (λa, add_comm _ _) , .. simple_func.add_group } variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map (λb, k • b)⟩ instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := { one_smul := λ f, ext (λa, one_smul _ _), mul_smul := λ x y f, ext (λa, mul_smul _ _ _), smul_add := λ r f g, ext (λa, smul_add _ _ _), smul_zero := λ r, ext (λa, smul_zero _), add_smul := λ r s f, ext (λa, add_smul _ _ _), zero_smul := λ f, ext (λa, zero_smul _ _) } instance [ring K] [add_comm_group β] [module K β] : module K (α →ₛ β) := { .. simple_func.semimodule } instance [field K] [add_comm_group β] [module K β] : vector_space K (α →ₛ β) := { .. simple_func.module } lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map (λb, k • b) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : _root_.measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf.preimage $ is_measurable_of_is_closed $ is_closed_ge' _) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : _root_.measurable f) (hg : _root_.measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] (i : ℕ → β) (f : α → β) (a : α) (hf : _root_.measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := nnreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : _root_.measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : _root_.measurable f) (hg : _root_.measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measure_space α] lemma volume_bUnion_preimage (s : finset β) (f : α →ₛ β) : volume (⋃b ∈ s, f ⁻¹' {b}) = s.sum (λb, volume (f ⁻¹' {b})) := begin /- Taking advantage of the fact that `f ⁻¹' {b}` are disjoint for `b ∈ s`. -/ rw [volume_bUnion_finset], { simp only [pairwise_on, (on), finset.mem_coe, ne.def], rintros _ _ _ _ ne _ ⟨h₁, h₂⟩, simp only [mem_singleton_iff, mem_preimage] at h₁ h₂, rw [← h₁, h₂] at ne, exact ne rfl }, exact assume a ha, preimage_measurable _ _ end /-- Integral of a simple function whose codomain is `ennreal`. -/ def integral (f : α →ₛ ennreal) : ennreal := f.range.sum (λ x, x * volume (f ⁻¹' {x})) /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_integral (g : β → ennreal) (f : α →ₛ β) : (f.map g).integral = f.range.sum (λ x, g x * volume (f ⁻¹' {x})) := begin simp only [integral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, volume_bUnion_preimage, finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h } end lemma zero_integral : (0 : α →ₛ ennreal).integral = 0 := begin refine (finset.sum_eq_zero_iff_of_nonneg $ assume _ _, zero_le _).2 _, assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, exact zero_mul _ end lemma add_integral (f g : α →ₛ ennreal) : (f + g).integral = f.integral + g.integral := calc (f + g).integral = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x}) + x.2 * volume (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_integral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = (pair f g).range.sum (λx, x.1 * volume (pair f g ⁻¹' {x})) + (pair f g).range.sum (λx, x.2 * volume (pair f g ⁻¹' {x})) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).integral + ((pair f g).map prod.snd).integral : by rw [map_integral, map_integral] ... = integral f + integral g : rfl lemma const_mul_integral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).integral = x * f.integral := calc (f.map (λa, x * a)).integral = f.range.sum (λr, x * r * volume (f ⁻¹' {r})) : by rw [map_integral] ... = f.range.sum (λr, x * (r * volume (f ⁻¹' {r}))) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.integral : finset.mul_sum.symm lemma mem_restrict_range [has_zero β] {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (∃a∈s, f a = r) := begin simp only [mem_range, restrict_apply, hs], split, { rintros ⟨a, ha⟩, split_ifs at ha, { exact or.inr ⟨a, h, ha⟩ }, { exact or.inl ⟨ha.symm, assume eq, h $ eq.symm ▸ trivial⟩ } }, { rintros (⟨rfl, h⟩ | ⟨a, ha, rfl⟩), { have : ¬ ∀a, a ∈ s := assume this, h $ eq_univ_of_forall this, rcases not_forall.1 this with ⟨a, ha⟩, refine ⟨a, _⟩, rw [if_neg ha] }, { refine ⟨a, _⟩, rw [if_pos ha] } } end lemma restrict_preimage' {r : ennreal} {s : set α} (f : α →ₛ ennreal) (hs : is_measurable s) (hr : r ≠ 0) : (restrict f s) ⁻¹' {r} = (f ⁻¹' {r} ∩ s) := begin ext a, by_cases a ∈ s; simp [hs, h, hr.symm] end lemma restrict_integral (f : α →ₛ ennreal) (s : set α) (hs : is_measurable s) : (restrict f s).integral = f.range.sum (λr, r * volume (f ⁻¹' {r} ∩ s)) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { assume r hr, rcases (mem_restrict_range hs).1 hr with ⟨rfl, h⟩ | ⟨a, ha, rfl⟩, { simp }, { assume _, exact mem_range.2 ⟨a, rfl⟩ } }, { assume a b _ _ _ _ h, exact h }, { assume r hr, by_cases r0 : r = 0, { simp [r0] }, assume h0, rcases mem_range.1 hr with ⟨a, rfl⟩, have : f ⁻¹' {f a} ∩ s ≠ ∅, { assume h, simpa [h] using h0 }, rcases ne_empty_iff_nonempty.1 this with ⟨a', eq', ha'⟩, refine ⟨_, (mem_restrict_range hs).2 (or.inr ⟨a', ha', _⟩), _, rfl⟩, { simpa using eq' }, { rwa [restrict_preimage' _ hs r0] } }, { assume r hr ne, by_cases r = 0, { simp [h] }, rw [restrict_preimage' _ hs h] } end lemma restrict_const_integral (c : ennreal) (s : set α) (hs : is_measurable s) : (restrict (const α c) s).integral = c * volume s := have (@const α ennreal _ c) ⁻¹' {c} = univ, begin refine eq_univ_of_forall (assume a, _), simp, end, calc (restrict (const α c) s).integral = c * volume ((const α c) ⁻¹' {c} ∩ s) : begin rw [restrict_integral (const α c) s hs], refine finset.sum_eq_single c _ _, { assume r hr, rcases mem_range.1 hr with ⟨a, rfl⟩, contradiction }, { by_cases nonempty α, { assume ne, rcases h with ⟨a⟩, exfalso, exact ne (mem_range.2 ⟨a, rfl⟩) }, { assume empty, have : (@const α ennreal _ c) ⁻¹' {c} ∩ s = ∅, { ext a, exfalso, exact h ⟨a⟩ }, simp only [this, volume_empty, mul_zero] } } end ... = c * volume s : by rw [this, univ_inter] lemma integral_sup_le (f g : α →ₛ ennreal) : f.integral ⊔ g.integral ≤ (f ⊔ g).integral := calc f.integral ⊔ g.integral = ((pair f g).map prod.fst).integral ⊔ ((pair f g).map prod.snd).integral : rfl ... ≤ (pair f g).range.sum (λx, (x.1 ⊔ x.2) * volume (pair f g ⁻¹' {x})) : begin rw [map_integral, map_integral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).integral : by rw [sup_eq_map₂, map_integral] lemma integral_le_integral (f g : α →ₛ ennreal) (h : f ≤ g) : f.integral ≤ g.integral := calc f.integral ≤ f.integral ⊔ g.integral : le_sup_left ... ≤ (f ⊔ g).integral : integral_sup_le _ _ ... = g.integral : by rw [sup_of_le_right h] lemma integral_congr (f g : α →ₛ ennreal) (h : ∀ₘ a, f a = g a) : f.integral = g.integral := show ((pair f g).map prod.fst).integral = ((pair f g).map prod.snd).integral, from begin rw [map_integral, map_integral], refine finset.sum_congr rfl (assume p hp, _), rcases mem_range.1 hp with ⟨a, rfl⟩, by_cases eq : f a = g a, { dsimp only [pair_apply], rw eq }, { have : volume ((pair f g) ⁻¹' {(f a, g a)}) = 0, { refine volume_mono_null (assume a' ha', _) h, simp at ha', show f a' ≠ g a', rwa [ha'.1, ha'.2] }, simp [this] } end lemma integral_map {β} [measure_space β] (f : α →ₛ ennreal) (g : β →ₛ ennreal)(m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → volume s = volume (m ⁻¹' s)) : f.integral = g.integral := have f_eq : (f : α → ennreal) = g ∘ m := funext eq, have vol_f : ∀r, volume (f ⁻¹' {r}) = volume (g ⁻¹' {r}), by { assume r, rw [h, f_eq, preimage_comp], exact measurable_sn _ _ }, begin simp [integral, vol_f], refine finset.sum_subset _ _, { simp [finset.subset_iff, f_eq], rintros r a rfl, exact ⟨_, rfl⟩ }, { assume r hrg hrf, rw [simple_func.mem_range, not_exists] at hrf, have : f ⁻¹' {r} = ∅ := set.eq_empty_of_subset_empty (assume a, by simpa using hrf a), simp [(vol_f _).symm, this] } end end measure section fin_vol_supp variables [measure_space α] [has_zero β] [has_zero γ] open finset ennreal protected def fin_vol_supp (f : α →ₛ β) : Prop := ∀b ≠ 0, volume (f ⁻¹' {b}) < ⊤ lemma fin_vol_supp_map {f : α →ₛ β} {g : β → γ} (hf : f.fin_vol_supp) (hg : g 0 = 0) : (f.map g).fin_vol_supp := begin assume c hc, simp only [map_preimage, volume_bUnion_preimage], apply sum_lt_top, intro b, simp only [mem_filter, mem_range, mem_singleton_iff, and_imp, exists_imp_distrib], intros a fab gbc, apply hf, intro b0, rw [b0, hg] at gbc, rw gbc at hc, contradiction end lemma fin_vol_supp_of_fin_vol_supp_map (f : α →ₛ β) {g : β → γ} (h : (f.map g).fin_vol_supp) (hg : ∀b, g b = 0 → b = 0) : f.fin_vol_supp := begin assume b hb, by_cases b_mem : b ∈ f.range, { have gb0 : g b ≠ 0, { assume h, have := hg b h, contradiction }, have : f ⁻¹' {b} ⊆ (f.map g) ⁻¹' {g b}, rw [coe_map, @preimage_comp _ _ _ f g, preimage_subset_preimage_iff], { simp only [set.mem_preimage, set.mem_singleton, set.singleton_subset_iff] }, { rw set.singleton_subset_iff, rw mem_range at b_mem, exact b_mem }, exact lt_of_le_of_lt (volume_mono this) (h (g b) gb0) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, volume_empty], exact with_top.zero_lt_top } end lemma fin_vol_supp_pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_vol_supp) (hg : g.fin_vol_supp) : (pair f g).fin_vol_supp := begin rintros ⟨b, c⟩ hbc, rw [pair_preimage_singleton], rw [ne.def, prod.eq_iff_fst_eq_snd_eq, not_and_distrib] at hbc, refine or.elim hbc (λ h : b≠0, _) (λ h : c≠0, _), { calc _ ≤ volume (f ⁻¹' {b}) : volume_mono (set.inter_subset_left _ _) ... < ⊤ : hf _ h }, { calc _ ≤ volume (g ⁻¹' {c}) : volume_mono (set.inter_subset_right _ _) ... < ⊤ : hg _ h }, end lemma integral_lt_top_of_fin_vol_supp {f : α →ₛ ennreal} (h₁ : ∀ₘ a, f a < ⊤) (h₂ : f.fin_vol_supp) : integral f < ⊤ := begin rw integral, apply sum_lt_top, intros a ha, have : f ⁻¹' {⊤} = -{a : α | f a < ⊤}, { ext, simp }, have vol_top : volume (f ⁻¹' {⊤}) = 0, { rw [this, volume, ← measure.mem_a_e_iff], exact h₁ }, by_cases hat : a = ⊤, { rw [hat, vol_top, mul_zero], exact with_top.zero_lt_top }, { by_cases haz : a = 0, { rw [haz, zero_mul], exact with_top.zero_lt_top }, apply mul_lt_top, { rw ennreal.lt_top_iff_ne_top, exact hat }, apply h₂, exact haz } end lemma fin_vol_supp_of_integral_lt_top {f : α →ₛ ennreal} (h : integral f < ⊤) : f.fin_vol_supp := begin assume b hb, rw [integral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, volume_empty], exact with_top.zero_lt_top } end /-- A technical lemma dealing with the definition of `integrable` in `l1_space.lean`. -/ lemma integral_map_coe_lt_top {f : α →ₛ β} {g : β → nnreal} (h : f.fin_vol_supp) (hg : g 0 = 0) : integral (f.map ((coe : nnreal → ennreal) ∘ g)) < ⊤ := integral_lt_top_of_fin_vol_supp (by { filter_upwards[], assume a, simp only [mem_set_of_eq, map_apply], exact ennreal.coe_lt_top}) (by { apply fin_vol_supp_map h, simp only [hg, function.comp_app, ennreal.coe_zero] }) end fin_vol_supp end simple_func section lintegral open simple_func variable [measure_space α] /-- The lower Lebesgue integral -/ def lintegral (f : α → ennreal) : ennreal := ⨆ (s : α →ₛ ennreal) (hf : f ≥ s), s.integral notation `∫⁻` binders `, ` r:(scoped f, lintegral f) := r theorem simple_func.lintegral_eq_integral (f : α →ₛ ennreal) : (∫⁻ a, f a) = f.integral := le_antisymm (supr_le $ assume s, supr_le $ assume hs, integral_le_integral _ _ hs) (le_supr_of_le f $ le_supr_of_le (le_refl f) $ le_refl _) lemma lintegral_le_lintegral (f g : α → ennreal) (h : f ≤ g) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := supr_le_supr $ assume s, supr_le $ assume hs, le_supr_of_le (le_trans hs h) (le_refl _) lemma lintegral_eq_nnreal (f : α → ennreal) : (∫⁻ a, f a) = (⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map (coe : nnreal → ennreal)), (s.map (coe : nnreal → ennreal)).integral) := begin let c : nnreal → ennreal := coe, refine le_antisymm (supr_le $ assume s, supr_le $ assume hs, _) (supr_le $ assume s, supr_le $ assume hs, le_supr_of_le (s.map c) $ le_supr _ hs), by_cases ∀ₘ a, s a ≠ ⊤, { have : f ≥ (s.map ennreal.to_nnreal).map c := le_trans (assume a, ennreal.coe_to_nnreal_le_self) hs, refine le_supr_of_le (s.map ennreal.to_nnreal) (le_supr_of_le this (le_of_eq $ integral_congr _ _ _)), exact filter.mem_sets_of_superset h (assume a ha, (ennreal.coe_to_nnreal ha).symm) }, { have h_vol_s : volume {a : α | s a = ⊤} ≠ 0, { simp [measure_theory.all_ae_iff, set.compl_set_of] at h, assumption }, let n : ℕ → (α →ₛ nnreal) := λn, restrict (const α (n : nnreal)) (s ⁻¹' {⊤}), have n_le_s : ∀i, (n i).map c ≤ s, { assume i a, dsimp [n, c], rw [restrict_apply _ (s.preimage_measurable _)], split_ifs with ha, { simp at ha, exact ha.symm ▸ le_top }, { exact zero_le _ } }, have approx_s : ∀ (i : ℕ), ↑i * volume {a : α | s a = ⊤} ≤ integral (map c (n i)), { assume i, have : {a : α | s a = ⊤} = s ⁻¹' {⊤}, { ext a, simp }, rw [this, ← restrict_const_integral _ _ (s.preimage_measurable _)], { refine integral_le_integral _ _ (assume a, le_of_eq _), simp [n, c, restrict_apply, s.preimage_measurable], split_ifs; simp [ennreal.coe_nat] }, }, calc s.integral ≤ ⊤ : le_top ... = (⨆i:ℕ, (i : ennreal) * volume {a | s a = ⊤}) : by rw [← ennreal.supr_mul, ennreal.supr_coe_nat, ennreal.top_mul, if_neg h_vol_s] ... ≤ (⨆i, ((n i).map c).integral) : supr_le_supr approx_s ... ≤ ⨆ (s : α →ₛ nnreal) (hf : f ≥ s.map c), (s.map c).integral : have ∀i, ((n i).map c : α → ennreal) ≤ f := assume i, le_trans (n_le_s i) hs, (supr_le $ assume i, le_supr_of_le (n i) (le_supr (λh, ((n i).map c).integral) (this i))) } end /-- Monotone convergence theorem -- somtimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let c : nnreal → ennreal := coe in let F (a:α) := ⨆n, f n a in have hF : measurable F := measurable.supr hf, show (∫⁻ a, F a) = (⨆n, ∫⁻ a, f n a), begin refine le_antisymm _ _, { rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * integral (s.map c) = (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r})) : by rw [← const_mul_integral, integral, eq_rs] ... ≤ (rs.map c).range.sum (λr, r * volume (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ (rs.map c).range.sum (λr, (⨆n, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}))) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [volume, measure_Union_eq_supr_nat _ (mono x), ennreal.mul_supr], { assume i, refine is_measurable.inter ((rs.map c).preimage_measurable _) _, refine (hf i).preimage _, exact is_measurable_of_is_closed (is_closed_ge' _) } end) ... ≤ ⨆n, (rs.map c).range.sum (λr, r * volume ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (volume_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).integral) : begin refine supr_le_supr (assume n, _), rw [restrict_integral _ _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2, ext a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_integral], refine lintegral_le_lintegral _ _ (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end }, { exact supr_le (assume n, lintegral_le_lintegral _ _ $ assume a, le_supr _ n) } end lemma lintegral_eq_supr_eapprox_integral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a) = (⨆n, (eapprox f n).integral) := calc (∫⁻ a, f a) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).integral) : by congr; ext n; rw [(eapprox f n).lintegral_eq_integral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a) = (∫⁻ a, f a) + (∫⁻ a, g a) := calc (∫⁻ a, f a + g a) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a)) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a)) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).integral + (eapprox g n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_integral, ← simple_func.lintegral_eq_integral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add' (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).integral) + (⨆n, (eapprox g n).integral) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.integral_le_integral _ _ (monotone_eapprox _ h) } ... = (∫⁻ a, f a) + (∫⁻ a, g a) : by rw [lintegral_eq_supr_eapprox_integral hf, lintegral_eq_supr_eapprox_integral hg] @[simp] lemma lintegral_zero : (∫⁻ a:α, 0) = 0 := show (∫⁻ a:α, (0 : α →ₛ ennreal) a) = 0, by rw [simple_func.lintegral_eq_integral, zero_integral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, s.sum (λb, f b a)) = s.sum (λb, ∫⁻ a, f b a) := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp [has], rw [lintegral_add (hf _) (measurable_finset_sum s hf), ih] } end lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := calc (∫⁻ a, r * f a) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a)) : by congr; funext a; rw [← supr_eapprox_apply f hf, ennreal.mul_supr]; refl ... = (⨆n, r * (eapprox f n).integral) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_integral, ← simple_func.lintegral_eq_integral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_integral hf] lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a) ≤ (∫⁻ a, r * f a) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_integral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a) = r * (∫⁻ a, f a) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_supr_const (r : ennreal) {s : set α} (hs : is_measurable s) : (∫⁻ a, ⨆(h : a ∈ s), r) = r * volume s := begin rw [← restrict_const_integral r s hs, ← (restrict (const α r) s).lintegral_eq_integral], congr; ext a; by_cases a ∈ s; simp [h, hs] end lemma lintegral_le_lintegral_ae {f g : α → ennreal} (h : ∀ₘ a, f a ≤ g a) : (∫⁻ a, f a) ≤ (∫⁻ a, g a) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : - t ∈ (@measure_space.μ α _).a_e, { rw [measure.mem_a_e_iff, compl_compl, ht0] }, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict (- t)) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (s.integral_congr _ _), filter_upwards [this], refine assume a hnt, _, by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : ∀ₘ a, f a = g a) : (∫⁻ a, f a) = (∫⁻ a, g a) := le_antisymm (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h) (lintegral_le_lintegral_ae $ by filter_upwards [h] assume a h, le_of_eq h.symm) -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : ∀ₘ a, f a = f' a) (g : β → ennreal) : (∫⁻ a, g (f a)) = (∫⁻ a, g (f' a)) := begin apply lintegral_congr_ae, filter_upwards [h], assume a, simp only [mem_set_of_eq], assume h, rw h end -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : ∀ₘ a, f₁ a = f₁' a) (h₂ : ∀ₘ a, f₂ a = f₂' a) (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a)) = (∫⁻ a, g (f₁' a) (f₂' a)) := begin apply lintegral_congr_ae, filter_upwards [h₁, h₂], assume a, simp only [mem_set_of_eq], repeat { assume h, rw h } end lemma simple_func.lintegral_map (f : α →ₛ β) (g : β → ennreal) : (∫⁻ a, (f.map g) a) = ∫⁻ a, g (f a) := by { apply lintegral_congr_ae, filter_upwards [], assume a, exact map_apply _ _ _ } lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : lintegral f = 0 ↔ (∀ₘ a, f a = 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ₘ a, f a < n⁻¹, { assume n, have : is_measurable {a : α | f a ≥ n⁻¹ }, { exact hf _ (is_measurable_of_is_closed $ is_closed_ge' _) }, have : (n : ennreal)⁻¹ * volume {a | f a ≥ n⁻¹ } = 0, { rw [← simple_func.restrict_const_integral _ _ this, ← le_zero_iff_eq, ← simple_func.lintegral_eq_integral], refine le_trans (lintegral_le_lintegral _ _ _) (le_of_eq h), assume a, by_cases h : (n : ennreal)⁻¹ ≤ f a; simp [h, (≥), this] }, rw [ennreal.mul_eq_zero, ennreal.inv_eq_zero] at this, simpa [ennreal.nat_ne_top, all_ae_iff] using this }, filter_upwards [all_ae_all_iff.2 this], dsimp, assume a ha, by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc lintegral f = lintegral (λa:α, 0) : lintegral_congr_ae h ... = 0 : lintegral_zero } end /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ₘ a, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a) = (⨆n, ∫⁻ a, f n a) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (all_ae_iff.1 (all_ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ₘ a, ∀n, g n a = f n a, begin have := hs.2.2, rw [← compl_compl s] at this, filter_upwards [(measure.mem_a_e_iff (-s)).2 this] assume a ha n, if_neg ha end, calc (∫⁻ a, ⨆n, f n a) = (∫⁻ a, ⨆n, g n a) : lintegral_congr_ae begin filter_upwards [g_eq_f], assume a ha, congr, funext, exact (ha n).symm end ... = ⨆n, (∫⁻ a, g n a) : lintegral_supr (assume n, measurable.if hs.2.1 measurable_const (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a) : begin congr, funext, apply lintegral_congr_ae, filter_upwards [g_eq_f] assume a ha, ha n end lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : lintegral g < ⊤) (h_le : ∀ₘ a, g a ≤ f a) : (∫⁻ a, f a - g a) = (∫⁻ a, f a) - (∫⁻ a, g a) := begin rw [← ennreal.add_right_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_le_lintegral_ae h_le), ← lintegral_add (ennreal.measurable.sub hf hg) hg], show (∫⁻ (a : α), f a - g a + g a) = ∫⁻ (a : α), f a, apply lintegral_congr_ae, filter_upwards [h_le], simp only [add_comm, mem_set_of_eq], assume a ha, exact ennreal.add_sub_cancel_of_le ha end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, ∀ₘ a, f n.succ a ≤ f n a) (h_fin : lintegral (f 0) < ⊤) : (∫⁻ a, ⨅n, f n a) = (⨅n, ∫⁻ a, f n a) := have fn_le_f0 : (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0), from lintegral_le_lintegral _ _ (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a) ≤ lintegral (f 0), from infi_le_of_le 0 (le_refl _), (ennreal.sub_left_inj h_fin fn_le_f0 fn_le_f0').1 $ show lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = lintegral (f 0) - (⨅n, ∫⁻ a, f n a), from calc lintegral (f 0) - (∫⁻ a, ⨅n, f n a) = ∫⁻ a, f 0 a - ⨅n, f n a : (lintegral_sub (h_meas 0) (measurable.infi h_meas) (calc (∫⁻ a, ⨅n, f n a) ≤ lintegral (f 0) : lintegral_le_lintegral _ _ (assume a, infi_le _ _) ... < ⊤ : h_fin ) (all_ae_of_all $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a : lintegral_supr_ae (assume n, ennreal.measurable.sub (h_meas 0) (h_meas n)) (assume n, by filter_upwards [h_mono n] assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, lintegral (f 0) - ∫⁻ a, f n a : have h_mono : ∀ₘ a, ∀n:ℕ, f n.succ a ≤ f n a := all_ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ₘa, f n a ≤ f 0 a := assume n, begin filter_upwards [h_mono], simp only [mem_set_of_eq], assume a, assume h, induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc (∫⁻ a, f n a) ≤ ∫⁻ a, f 0 a : lintegral_le_lintegral_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = lintegral (f 0) - (⨅n, ∫⁻ a, f n a) : ennreal.sub_infi.symm section priority -- for some reason the next proof fails without changing the priority of this instance local attribute [instance, priority 1000] classical.prop_decidable /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : (∫⁻ a, liminf at_top (λ n, f n a)) ≤ liminf at_top (λ n, lintegral (f n)) := calc (∫⁻ a, liminf at_top (λ n, f n a)) = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a : congr rfl (funext (assume a, liminf_eq_supr_infi_of_nat)) ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a : lintegral_supr begin assume n, apply measurable.infi, assume i, by_cases h : i ≥ n, {convert h_meas i, simp [h]}, {convert measurable_const, simp [h]} end begin assume n m hnm a, simp only [le_infi_iff], assume i hi, refine infi_le_of_le i (infi_le_of_le (le_trans hnm hi) (le_refl _)) end ... ≤ ⨆n:ℕ, ⨅i≥n, lintegral (f i) : supr_le_supr $ assume n, le_infi $ assume i, le_infi $ assume hi, lintegral_le_lintegral _ _ $ assume a, infi_le_of_le i $ infi_le_of_le hi $ le_refl _ ... = liminf at_top (λ n, lintegral (f n)) : liminf_eq_supr_infi_of_nat.symm end priority lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, ∀ₘa, f n a ≤ g a) (h_fin : lintegral g < ⊤) : limsup at_top (λn, lintegral (f n)) ≤ ∫⁻ a, limsup at_top (λn, f n a) := calc limsup at_top (λn, lintegral (f n)) = ⨅n:ℕ, ⨆i≥n, lintegral (f i) : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a : infi_le_infi $ assume n, supr_le $ assume i, supr_le $ assume hi, lintegral_le_lintegral _ _ $ assume a, le_supr_of_le i $ le_supr_of_le hi (le_refl _) ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a : (lintegral_infi_ae (assume n, @measurable.supr _ _ _ _ _ _ _ _ _ (λ i a, supr (λ (h : i ≥ n), f i a)) (assume i, measurable.supr_Prop (hf_meas i))) (assume n, all_ae_of_all $ assume a, begin simp only [supr_le_iff], assume i hi, refine le_supr_of_le i _, rw [supr_pos _], exact le_refl _, exact nat.le_of_succ_le hi end ) (lt_of_le_of_lt (lintegral_le_lintegral_ae begin filter_upwards [all_ae_all_iff.2 h_bound], simp only [supr_le_iff, mem_set_of_eq], assume a ha i hi, exact ha i end ) h_fin)).symm ... = ∫⁻ a, limsup at_top (λn, f n a) : lintegral_congr_ae $ all_ae_of_all $ assume a, limsup_eq_infi_supr_of_nat.symm /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, ∀ₘ a, F n a ≤ bound a) (h_fin : lintegral bound < ⊤) (h_lim : ∀ₘ a, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, lintegral (F n)) at_top (𝓝 (lintegral f)) := begin have limsup_le_lintegral := calc limsup at_top (λ (n : ℕ), lintegral (F n)) ≤ ∫⁻ (a : α), limsup at_top (λn, F n a) : limsup_lintegral_le hF_meas h_bound h_fin ... = lintegral f : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, limsup_eq_of_tendsto at_top_ne_bot h, have lintegral_le_liminf := calc lintegral f = ∫⁻ (a : α), liminf at_top (λ (n : ℕ), F n a) : lintegral_congr_ae $ by filter_upwards [h_lim] assume a h, (liminf_eq_of_tendsto at_top_ne_bot h).symm ... ≤ liminf at_top (λ n, lintegral (F n)) : lintegral_liminf_le hF_meas, have liminf_eq_limsup := le_antisymm (liminf_le_limsup (map_ne_bot at_top_ne_bot)) (le_trans limsup_le_lintegral lintegral_le_liminf), have liminf_eq_lintegral : liminf at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm (by convert limsup_le_lintegral) lintegral_le_liminf, have limsup_eq_lintegral : limsup at_top (λ n, lintegral (F n)) = lintegral f := le_antisymm limsup_le_lintegral begin convert lintegral_le_liminf, exact liminf_eq_limsup.symm end, exact tendsto_of_liminf_eq_limsup ⟨liminf_eq_lintegral, limsup_eq_lintegral⟩ end /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.has_countable_basis) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ₘ a, F n a ≤ bound a) (h_fin : lintegral bound < ⊤) (h_lim : ∀ₘ a, tendsto (λ n, F n a) l (nhds (f a))) : tendsto (λn, lintegral (F n)) l (nhds (lintegral f)) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { filter_upwards [h_lim], simp only [mem_set_of_eq], assume a h_lim, apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : (∫⁻ a, ⨆b, f b a) = (⨆b, ∫⁻ a, f b a) := begin by_cases hβ : ¬ nonempty β, { have : ∀f : β → ennreal, (⨆(b : β), f b) = 0 := assume f, supr_eq_bot.2 (assume b, (hβ ⟨b⟩).elim), simp [this] }, cases of_not_not hβ with b, haveI iβ : inhabited β := ⟨b⟩, clear hβ b, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc (∫⁻ a, ⨆ b, f b a) = (∫⁻ a, ⨆ n, f (h_directed.sequence f n) a) : by simp only [this] ... = (⨆ n, ∫⁻ a, f (h_directed.sequence f n) a) : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = (⨆ b, ∫⁻ a, f b a) : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, lintegral (f b)) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_le_lintegral _ _ $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : (∫⁻ a, ∑ i, f i a) = (∑ i, ∫⁻ a, f i a) := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact measurable_finset_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end end lintegral namespace measure def integral [measurable_space α] (m : measure α) (f : α → ennreal) : ennreal := @lintegral α { μ := m } f variables [measurable_space α] {m : measure α} @[simp] lemma integral_zero : m.integral (λa, 0) = 0 := @lintegral_zero α { μ := m } lemma integral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : (map g m).integral f = m.integral (f ∘ g) := begin rw [integral, integral, lintegral_eq_supr_eapprox_integral, lintegral_eq_supr_eapprox_integral], { congr, funext n, symmetry, apply simple_func.integral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, exact hf.comp hg, assumption end lemma integral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : (dirac a).integral f = f a := have ∀f:α →ₛ ennreal, @simple_func.integral α {μ := dirac a} f = f a, begin assume f, have : ∀r, @volume α { μ := dirac a } (⇑f ⁻¹' {r}) = ⨆ h : f a = r, 1, { assume r, transitivity, apply dirac_apply, apply simple_func.measurable_sn, refine supr_congr_Prop _ _; simp }, transitivity, apply finset.sum_eq_single (f a), { assume b hb h, simp [this, ne.symm h], }, { assume h, simp at h, exact (h a rfl).elim }, { rw [this], simp } end, begin rw [integral, lintegral_eq_supr_eapprox_integral], { simp [this, simple_func.supr_eapprox_apply f hf] }, assumption end def with_density (m : measure α) (f : α → ennreal) : measure α := if hf : measurable f then measure.of_measurable (λs hs, m.integral (λa, ⨆(h : a ∈ s), f a)) (by simp) begin assume s hs hd, have : ∀a, (⨆ (h : a ∈ ⋃i, s i), f a) = (∑i, (⨆ (h : a ∈ s i), f a)), { assume a, by_cases ha : ∃j, a ∈ s j, { rcases ha with ⟨j, haj⟩, have : ∀i, a ∈ s i ↔ j = i := assume i, iff.intro (assume hai, by_contradiction $ assume hij, hd j i hij ⟨haj, hai⟩) (by rintros rfl; assumption), simp [this, ennreal.tsum_supr_eq] }, { have : ∀i, ¬ a ∈ s i, { simpa using ha }, simp [this] } }, simp only [this], apply lintegral_tsum, { assume i, simp [supr_eq_if], exact measurable.if (hs i) hf measurable_const } end else 0 lemma with_density_apply {m : measure α} {f : α → ennreal} {s : set α} (hf : measurable f) (hs : is_measurable s) : m.with_density f s = m.integral (λa, ⨆(h : a ∈ s), f a) := by rw [with_density, dif_pos hf]; exact measure.of_measurable_apply s hs end measure end measure_theory
14a032dc1344a49386144a269fde13b6a7a4e4e6
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/analysis/complex/real_deriv.lean
c940d5c8b8ed8ade71e100e568a22802c3c803c2
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,481
lean
/- Copyright (c) Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yourong Zang -/ import analysis.calculus.times_cont_diff import analysis.complex.conformal import analysis.calculus.conformal.normed_space /-! # Real differentiability of complex-differentiable functions `has_deriv_at.real_of_complex` expresses that, if a function on `ℂ` is differentiable (over `ℂ`), then its restriction to `ℝ` is differentiable over `ℝ`, with derivative the real part of the complex derivative. `differentiable_at.conformal_at` states that a real-differentiable function with a nonvanishing differential from the complex plane into an arbitrary complex-normed space is conformal at a point if it's holomorphic at that point. This is a version of Cauchy-Riemann equations. `conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj` proves that a real-differential function with a nonvanishing differential between the complex plane is conformal at a point if and only if it's holomorphic or antiholomorphic at that point. ## TODO * The classical form of Cauchy-Riemann equations * On a connected open set `u`, a function which is `conformal_at` each point is either holomorphic throughout or antiholomorphic throughout. ## Warning We do NOT require conformal functions to be orientation-preserving in this file. -/ section real_deriv_of_complex /-! ### Differentiability of the restriction to `ℝ` of complex functions -/ open complex variables {e : ℂ → ℂ} {e' : ℂ} {z : ℝ} /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_strict_deriv_at.real_of_complex (h : has_strict_deriv_at e e' z) : has_strict_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_strict_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_strict_fderiv_at, have B : has_strict_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_strict_fderiv_at.restrict_scalars ℝ, have C : has_strict_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_strict_fderiv_at, simpa using (C.comp z (B.comp z A)).has_strict_deriv_at end /-- If a complex function is differentiable at a real point, then the induced real function is also differentiable at this point, with a derivative equal to the real part of the complex derivative. -/ theorem has_deriv_at.real_of_complex (h : has_deriv_at e e' z) : has_deriv_at (λx:ℝ, (e x).re) e'.re z := begin have A : has_fderiv_at (coe : ℝ → ℂ) of_real_clm z := of_real_clm.has_fderiv_at, have B : has_fderiv_at e ((continuous_linear_map.smul_right 1 e' : ℂ →L[ℂ] ℂ).restrict_scalars ℝ) (of_real_clm z) := h.has_fderiv_at.restrict_scalars ℝ, have C : has_fderiv_at re re_clm (e (of_real_clm z)) := re_clm.has_fderiv_at, simpa using (C.comp z (B.comp z A)).has_deriv_at end theorem times_cont_diff_at.real_of_complex {n : with_top ℕ} (h : times_cont_diff_at ℂ n e z) : times_cont_diff_at ℝ n (λ x : ℝ, (e x).re) z := begin have A : times_cont_diff_at ℝ n (coe : ℝ → ℂ) z, from of_real_clm.times_cont_diff.times_cont_diff_at, have B : times_cont_diff_at ℝ n e z := h.restrict_scalars ℝ, have C : times_cont_diff_at ℝ n re (e z), from re_clm.times_cont_diff.times_cont_diff_at, exact C.comp z (B.comp z A) end theorem times_cont_diff.real_of_complex {n : with_top ℕ} (h : times_cont_diff ℂ n e) : times_cont_diff ℝ n (λ x : ℝ, (e x).re) := times_cont_diff_iff_times_cont_diff_at.2 $ λ x, h.times_cont_diff_at.real_of_complex variables {E : Type*} [normed_group E] [normed_space ℂ E] lemma has_strict_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv' {f : ℂ → E} {x : ℂ} {f' : E} (h : has_deriv_at f f' x) : has_fderiv_at f (re_clm.smul_right f' + I • im_clm.smul_right f') x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv' {f : ℂ → E} {s : set ℂ} {x : ℂ} {f' : E} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (re_clm.smul_right f' + I • im_clm.smul_right f') s x := by simpa only [complex.restrict_scalars_one_smul_right'] using h.has_fderiv_within_at.restrict_scalars ℝ lemma has_strict_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_strict_deriv_at f f' x) : has_strict_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_strict_fderiv_at.restrict_scalars ℝ lemma has_deriv_at.complex_to_real_fderiv {f : ℂ → ℂ} {f' x : ℂ} (h : has_deriv_at f f' x) : has_fderiv_at f (f' • (1 : ℂ →L[ℝ] ℂ)) x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_at.restrict_scalars ℝ lemma has_deriv_within_at.complex_to_real_fderiv {f : ℂ → ℂ} {s : set ℂ} {f' x : ℂ} (h : has_deriv_within_at f f' s x) : has_fderiv_within_at f (f' • (1 : ℂ →L[ℝ] ℂ)) s x := by simpa only [complex.restrict_scalars_one_smul_right] using h.has_fderiv_within_at.restrict_scalars ℝ end real_deriv_of_complex section conformality /-! ### Conformality of real-differentiable complex maps -/ open complex continuous_linear_map variables /-- A real differentiable function of the complex plane into some complex normed space `E` is conformal at a point `z` if it is holomorphic at that point with a nonvanishing differential. This is a version of the Cauchy-Riemann equations. -/ lemma differentiable_at.conformal_at {E : Type*} [normed_group E] [normed_space ℝ E] [normed_space ℂ E] [is_scalar_tower ℝ ℂ E] {z : ℂ} {f : ℂ → E} (hf' : fderiv ℝ f z ≠ 0) (h : differentiable_at ℂ f z) : conformal_at f z := begin rw conformal_at_iff_is_conformal_map_fderiv, rw (h.has_fderiv_at.restrict_scalars ℝ).fderiv at ⊢ hf', apply is_conformal_map_complex_linear, contrapose! hf' with w, simp [w] end /-- A complex function is conformal if and only if the function is holomorphic or antiholomorphic with a nonvanishing differential. -/ lemma conformal_at_iff_differentiable_at_or_differentiable_at_comp_conj {f : ℂ → ℂ} {z : ℂ} : conformal_at f z ↔ (differentiable_at ℂ f z ∨ differentiable_at ℂ (f ∘ conj) (conj z)) ∧ fderiv ℝ f z ≠ 0 := begin rw conformal_at_iff_is_conformal_map_fderiv, rw is_conformal_map_iff_is_complex_or_conj_linear, apply and_congr_left, intros h, have h_diff := h.imp_symm fderiv_zero_of_not_differentiable_at, apply or_congr, { rw differentiable_at_iff_restrict_scalars ℝ h_diff }, rw ← conj_conj z at h_diff, rw differentiable_at_iff_restrict_scalars ℝ (h_diff.comp _ conj_cle.differentiable_at), refine exists_congr (λ g, rfl.congr _), have : fderiv ℝ conj (conj z) = _ := conj_cle.fderiv, simp [fderiv.comp _ h_diff conj_cle.differentiable_at, this, conj_conj], end end conformality
d312ee6c32b3cdc907db8f318bdf21f50bf3695c
9028d228ac200bbefe3a711342514dd4e4458bff
/src/analysis/calculus/specific_functions.lean
1d8e35b73c0e0c9ac4a6ae81900db9bdfe8ebc82
[ "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
7,778
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 analysis.calculus.extend_deriv import analysis.calculus.iterated_deriv import analysis.special_functions.exp_log /-! # Smoothness of specific functions The real function `exp_neg_inv_glue` given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0` is a basic building block to construct smooth partitions of unity. We prove that it is `C^∞` in `exp_neg_inv_glue.smooth`. -/ noncomputable theory open_locale classical topological_space open polynomial real filter set /-- `exp_neg_inv_glue` is the real function given by `x ↦ exp (-1/x)` for `x > 0` and `0` for `x ≤ 0`. is a basic building block to construct smooth partitions of unity. Its main property is that it vanishes for `x ≤ 0`, it is positive for `x > 0`, and the junction between the two behaviors is flat enough to retain smoothness. The fact that this function is `C^∞` is proved in `exp_neg_inv_glue.smooth`. -/ def exp_neg_inv_glue (x : ℝ) : ℝ := if x ≤ 0 then 0 else exp (-x⁻¹) namespace exp_neg_inv_glue /-- Our goal is to prove that `exp_neg_inv_glue` is `C^∞`. For this, we compute its successive derivatives for `x > 0`. The `n`-th derivative is of the form `P_aux n (x) exp(-1/x) / x^(2 n)`, where `P_aux n` is computed inductively. -/ noncomputable def P_aux : ℕ → polynomial ℝ | 0 := 1 | (n+1) := X^2 * (P_aux n).derivative + (1 - C ↑(2 * n) * X) * (P_aux n) /-- Formula for the `n`-th derivative of `exp_neg_inv_glue`, as an auxiliary function `f_aux`. -/ def f_aux (n : ℕ) (x : ℝ) : ℝ := if x ≤ 0 then 0 else (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n) /-- The `0`-th auxiliary function `f_aux 0` coincides with `exp_neg_inv_glue`, by definition. -/ lemma f_aux_zero_eq : f_aux 0 = exp_neg_inv_glue := begin ext x, by_cases h : x ≤ 0, { simp [exp_neg_inv_glue, f_aux, h] }, { simp [h, exp_neg_inv_glue, f_aux, ne_of_gt (not_le.1 h), P_aux] } end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` (given in this statement in unfolded form) is the `n+1`-th auxiliary function, since the polynomial `P_aux (n+1)` was chosen precisely to ensure this. -/ lemma f_aux_deriv (n : ℕ) (x : ℝ) (hx : x ≠ 0) : has_deriv_at (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin have A : ∀k:ℕ, 2 * (k + 1) - 1 = 2 * k + 1, by omega, convert (((P_aux n).has_deriv_at x).mul (((has_deriv_at_exp _).comp x (has_deriv_at_inv hx).neg))).div (has_deriv_at_pow (2 * n) x) (pow_ne_zero _ hx) using 1, field_simp [hx, P_aux], -- `ring_exp` can't solve `p ∨ q` goal generated by `mul_eq_mul_right_iff` cases n; simp [nat.succ_eq_add_one, A, -mul_eq_mul_right_iff]; ring_exp end /-- For positive values, the derivative of the `n`-th auxiliary function `f_aux n` is the `n+1`-th auxiliary function. -/ lemma f_aux_deriv_pos (n : ℕ) (x : ℝ) (hx : 0 < x) : has_deriv_at (f_aux n) ((P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n + 1))) x := begin apply (f_aux_deriv n x (ne_of_gt hx)).congr_of_eventually_eq, have : Ioi (0 : ℝ) ∈ 𝓝 x := lt_mem_nhds hx, filter_upwards [this], assume y hy, have : ¬(y ≤ 0), by simpa using hy, simp [f_aux, this] end /-- To get differentiability at `0` of the auxiliary functions, we need to know that their limit is `0`, to be able to apply general differentiability extension theorems. This limit is checked in this lemma. -/ lemma f_aux_limit (n : ℕ) : tendsto (λx, (P_aux n).eval x * exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0) := begin have A : tendsto (λx, (P_aux n).eval x) (𝓝[Ioi 0] 0) (𝓝 ((P_aux n).eval 0)) := (P_aux n).continuous_within_at, have B : tendsto (λx, exp (-x⁻¹) / x^(2 * n)) (𝓝[Ioi 0] 0) (𝓝 0), { convert (tendsto_pow_mul_exp_neg_at_top_nhds_0 (2 * n)).comp tendsto_inv_zero_at_top, ext x, field_simp }, convert A.mul B; simp [mul_div_assoc] end /-- Deduce from the limiting behavior at `0` of its derivative and general differentiability extension theorems that the auxiliary function `f_aux n` is differentiable at `0`, with derivative `0`. -/ lemma f_aux_deriv_zero (n : ℕ) : has_deriv_at (f_aux n) 0 0 := begin -- we check separately differentiability on the left and on the right have A : has_deriv_within_at (f_aux n) (0 : ℝ) (Iic 0) 0, { apply (has_deriv_at_const (0 : ℝ) (0 : ℝ)).has_deriv_within_at.congr, { assume y hy, simp at hy, simp [f_aux, hy] }, { simp [f_aux, le_refl] } }, have B : has_deriv_within_at (f_aux n) (0 : ℝ) (Ici 0) 0, { have diff : differentiable_on ℝ (f_aux n) (Ioi 0) := λx hx, (f_aux_deriv_pos n x hx).differentiable_at.differentiable_within_at, -- next line is the nontrivial bit of this proof, appealing to differentiability -- extension results. apply has_deriv_at_interval_left_endpoint_of_tendsto_deriv diff _ self_mem_nhds_within, { refine (f_aux_limit (n+1)).congr' _, apply mem_sets_of_superset self_mem_nhds_within (λx hx, _), simp [(f_aux_deriv_pos n x hx).deriv] }, { have : f_aux n 0 = 0, by simp [f_aux, le_refl], simp only [continuous_within_at, this], refine (f_aux_limit n).congr' _, apply mem_sets_of_superset self_mem_nhds_within (λx hx, _), have : ¬(x ≤ 0), by simpa using hx, simp [f_aux, this] } }, simpa using A.union B, end /-- At every point, the auxiliary function `f_aux n` has a derivative which is equal to `f_aux (n+1)`. -/ lemma f_aux_has_deriv_at (n : ℕ) (x : ℝ) : has_deriv_at (f_aux n) (f_aux (n+1) x) x := begin -- check separately the result for `x < 0`, where it is trivial, for `x > 0`, where it is done -- in `f_aux_deriv_pos`, and for `x = 0`, done in -- `f_aux_deriv_zero`. rcases lt_trichotomy x 0 with hx|hx|hx, { have : f_aux (n+1) x = 0, by simp [f_aux, le_of_lt hx], rw this, apply (has_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq, have : Iio (0 : ℝ) ∈ 𝓝 x := gt_mem_nhds hx, filter_upwards [this], assume y hy, simp [f_aux, le_of_lt hy] }, { have : f_aux (n + 1) 0 = 0, by simp [f_aux, le_refl], rw [hx, this], exact f_aux_deriv_zero n }, { have : f_aux (n+1) x = (P_aux (n+1)).eval x * exp (-x⁻¹) / x^(2 * (n+1)), by simp [f_aux, not_le_of_gt hx], rw this, exact f_aux_deriv_pos n x hx }, end /-- The successive derivatives of the auxiliary function `f_aux 0` are the functions `f_aux n`, by induction. -/ lemma f_aux_iterated_deriv (n : ℕ) : iterated_deriv n (f_aux 0) = f_aux n := begin induction n with n IH, { simp }, { simp [iterated_deriv_succ, IH], ext x, exact (f_aux_has_deriv_at n x).deriv } end /-- The function `exp_neg_inv_glue` is smooth. -/ theorem smooth : times_cont_diff ℝ ⊤ (exp_neg_inv_glue) := begin rw ← f_aux_zero_eq, apply times_cont_diff_of_differentiable_iterated_deriv (λ m hm, _), rw f_aux_iterated_deriv m, exact λ x, (f_aux_has_deriv_at m x).differentiable_at end /-- The function `exp_neg_inv_glue` vanishes on `(-∞, 0]`. -/ lemma zero_of_nonpos {x : ℝ} (hx : x ≤ 0) : exp_neg_inv_glue x = 0 := by simp [exp_neg_inv_glue, hx] /-- The function `exp_neg_inv_glue` is positive on `(0, +∞)`. -/ lemma pos_of_pos {x : ℝ} (hx : 0 < x) : 0 < exp_neg_inv_glue x := by simp [exp_neg_inv_glue, not_le.2 hx, exp_pos] /-- The function exp_neg_inv_glue` is nonnegative. -/ lemma nonneg (x : ℝ) : 0 ≤ exp_neg_inv_glue x := begin cases le_or_gt x 0, { exact ge_of_eq (zero_of_nonpos h) }, { exact le_of_lt (pos_of_pos h) } end end exp_neg_inv_glue
93215cdcc93a057cbf8a8e7aaf76bdc4f72a16da
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/category/Group/basic.lean
95088d35ea5772f18ad1361d570da1853610d59d
[ "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
9,173
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := bundled group /-- The category of additive groups and group morphisms -/ add_decl_doc AddGroup namespace Group @[to_additive] instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Group AddGroup /-- Construct a bundled `Group` from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ add_decl_doc AddGroup.of @[to_additive] instance (G : Group) : group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [group R] : (Group.of R : Type u) = R := rfl @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : inhabited Group := ⟨1⟩ @[to_additive] instance one.unique : unique (1 : Group) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[ext, to_additive] lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } -- should to_additive do this automatically? attribute [ext] AddGroup.ext @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _ end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := bundled comm_group /-- The category of additive commutative groups and group morphisms. -/ add_decl_doc AddCommGroup /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ abbreviation Ab := AddCommGroup namespace CommGroup @[to_additive] instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommGroup AddCommGroup /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ add_decl_doc AddCommGroup.of @[to_additive] instance comm_group_instance (G : CommGroup) : comm_group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_group R] : (CommGroup.of R : Type u) = R := rfl @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : inhabited CommGroup := ⟨1⟩ @[to_additive] instance one.unique : unique (1 : CommGroup) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive,ext] lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddCommGroup.ext @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _ @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. @[to_additive] example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 := by simp [h] namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G := gmultiples_hom G g @[simp] lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) := λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp @[ext] lemma int_hom_ext {G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f := λ g₁ g₂ h, begin have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f := begin ext, simpa [as_hom_apply] using h, end, have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0, apply as_hom_injective t1, end end AddCommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso, simps] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ add_decl_doc add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[to_additive add_equiv.to_AddCommGroup_iso, simps] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ add_decl_doc add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`.", simps] def Group_iso_to_mul_equiv {X Y : Group} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`.", simps] def CommGroup_iso_to_mul_equiv {X Y : CommGroup} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut @[to_additive] instance Group.forget_reflects_isos : reflects_isomorphisms (forget Group.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Group).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_Group_iso }, end } @[to_additive] instance CommGroup.forget_reflects_isos : reflects_isomorphisms (forget CommGroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommGroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact { ..e.to_CommGroup_iso }, end }
5f571439cbd767f9a29fa85cdeb91dd35fe35777
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Compiler/IR/LiveVars.lean
bbdaa02d0b1e767d814431ec551151c698e7a44a
[ "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
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
6,953
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 -/ import Lean.Compiler.IR.Basic import Lean.Compiler.IR.FreeVars namespace Lean.IR /-! Remark: in the paper "Counting Immutable Beans" the concepts of free and live variables coincide because the paper does *not* consider join points. For example, consider the function body `B` ``` let x := ctor_0; jmp block_1 x ``` in a context where we have the join point `block_1` defined as ``` block_1 (x : obj) : obj := let z := ctor_0 x y; ret z ``` The variable `y` is live in the function body `B` since it occurs in `block_1` which is "invoked" by `B`. -/ namespace IsLive /-- We use `State Context` instead of `ReaderT Context Id` because we remove non local joint points from `Context` whenever we visit them instead of maintaining a set of visited non local join points. Remark: we don't need to track local join points because we assume there is no variable or join point shadowing in our IR. -/ abbrev M := StateM LocalContext abbrev visitVar (w : Index) (x : VarId) : M Bool := pure (HasIndex.visitVar w x) abbrev visitJP (w : Index) (x : JoinPointId) : M Bool := pure (HasIndex.visitJP w x) abbrev visitArg (w : Index) (a : Arg) : M Bool := pure (HasIndex.visitArg w a) abbrev visitArgs (w : Index) (as : Array Arg) : M Bool := pure (HasIndex.visitArgs w as) abbrev visitExpr (w : Index) (e : Expr) : M Bool := pure (HasIndex.visitExpr w e) partial def visitFnBody (w : Index) : FnBody → M Bool | FnBody.vdecl _ _ v b => visitExpr w v <||> visitFnBody w b | FnBody.jdecl _ _ v b => visitFnBody w v <||> visitFnBody w b | FnBody.set x _ y b => visitVar w x <||> visitArg w y <||> visitFnBody w b | FnBody.uset x _ y b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.sset x _ _ y _ b => visitVar w x <||> visitVar w y <||> visitFnBody w b | FnBody.setTag x _ b => visitVar w x <||> visitFnBody w b | FnBody.inc x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.dec x _ _ _ b => visitVar w x <||> visitFnBody w b | FnBody.del x b => visitVar w x <||> visitFnBody w b | FnBody.mdata _ b => visitFnBody w b | FnBody.jmp j ys => visitArgs w ys <||> do let ctx ← get match ctx.getJPBody j with | some b => -- `j` is not a local join point since we assume we cannot shadow join point declarations. -- Instead of marking the join points that we have already been visited, we permanently remove `j` from the context. set (ctx.eraseJoinPointDecl j) *> visitFnBody w b | none => -- `j` must be a local join point. So do nothing since we have already visite its body. pure false | FnBody.ret x => visitArg w x | FnBody.case _ x _ alts => visitVar w x <||> alts.anyM (fun alt => visitFnBody w alt.body) | FnBody.unreachable => pure false end IsLive /-- Return true if `x` is live in the function body `b` in the context `ctx`. Remark: the context only needs to contain all (free) join point declarations. Recall that we say that a join point `j` is free in `b` if `b` contains `FnBody.jmp j ys` and `j` is not local. -/ def FnBody.hasLiveVar (b : FnBody) (ctx : LocalContext) (x : VarId) : Bool := (IsLive.visitFnBody x.idx b).run' ctx abbrev LiveVarSet := VarIdSet abbrev JPLiveVarMap := Std.RBMap JoinPointId LiveVarSet (fun j₁ j₂ => compare j₁.idx j₂.idx) instance : Inhabited LiveVarSet where default := {} def mkLiveVarSet (x : VarId) : LiveVarSet := Std.RBTree.empty.insert x namespace LiveVars abbrev Collector := LiveVarSet → LiveVarSet @[inline] private def skip : Collector := fun s => s @[inline] private def collectVar (x : VarId) : Collector := fun s => s.insert x private def collectArg : Arg → Collector | Arg.var x => collectVar x | _ => skip private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun s => as.foldl (fun s a => f a s) s private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def accumulate (s' : LiveVarSet) : Collector := fun s => s'.fold (fun s x => s.insert x) s private def collectJP (m : JPLiveVarMap) (j : JoinPointId) : Collector := match m.find? j with | some xs => accumulate xs | none => skip -- unreachable for well-formed code private def bindVar (x : VarId) : Collector := fun s => s.erase x private def bindParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => s.erase p.x) s def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x ∘ collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x ∘ collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit _ => skip | Expr.isShared x => collectVar x | Expr.isTaggedPtr x => collectVar x partial def collectFnBody : FnBody → JPLiveVarMap → Collector | FnBody.vdecl x _ v b, m => collectExpr v ∘ bindVar x ∘ collectFnBody b m | FnBody.jdecl j ys v b, m => let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; let m := m.insert j jLiveVars; collectFnBody b m | FnBody.set x _ y b, m => collectVar x ∘ collectArg y ∘ collectFnBody b m | FnBody.setTag x _ b, m => collectVar x ∘ collectFnBody b m | FnBody.uset x _ y b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.sset x _ _ y _ b, m => collectVar x ∘ collectVar y ∘ collectFnBody b m | FnBody.inc x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.dec x _ _ _ b, m => collectVar x ∘ collectFnBody b m | FnBody.del x b, m => collectVar x ∘ collectFnBody b m | FnBody.mdata _ b, m => collectFnBody b m | FnBody.ret x, _ => collectArg x | FnBody.case _ x _ alts, m => collectVar x ∘ collectArray alts (fun alt => collectFnBody alt.body m) | FnBody.unreachable, _ => skip | FnBody.jmp j xs, m => collectJP m j ∘ collectArgs xs def updateJPLiveVarMap (j : JoinPointId) (ys : Array Param) (v : FnBody) (m : JPLiveVarMap) : JPLiveVarMap := let jLiveVars := (bindParams ys ∘ collectFnBody v m) {}; m.insert j jLiveVars end LiveVars def updateLiveVars (e : Expr) (v : LiveVarSet) : LiveVarSet := LiveVars.collectExpr e v def collectLiveVars (b : FnBody) (m : JPLiveVarMap) (v : LiveVarSet := {}) : LiveVarSet := LiveVars.collectFnBody b m v export LiveVars (updateJPLiveVarMap) end Lean.IR
ff40f9311298984c1d0959f0d126b60416c6b8ea
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/MatchAltView.lean
40c47578c98be73697f4baa384d6b46743170f69
[ "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
667
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Term namespace Lean.Elab.Term /- This modules assumes "match"-expressions use the following syntax. ```lean def matchDiscr := leading_parser optional (try (ident >> checkNoWsBefore "no space before ':'" >> ":")) >> termParser def «match» := leading_parser:leadPrec "match " >> sepBy1 matchDiscr ", " >> optType >> " with " >> matchAlts ``` -/ structure MatchAltView where ref : Syntax patterns : Array Syntax rhs : Syntax deriving Inhabited end Lean.Elab.Term
00ccb35a9007c4249c3a716ccb4fc62a47ff9d9b
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/def_brec_reflexive.lean
bd6baa6eb49395479c6272adf1170ce388058bdb
[ "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
277
lean
inductive inftree (A : Type*) | leaf : A → inftree | node : (nat → inftree) → inftree open inftree definition {u} szn {A : Type (u+1)} (n : nat) : inftree A → inftree A → nat | (leaf a) t2 := 1 | (node c) (leaf b) := 0 | (node c) (node d) := szn (c n) (d n)
a2af9a143a9668bd0124dd5bfd7efad5bd5720f4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/real.lean
ad071db4779b1184da8dae00aa5a3878a2a08766
[ "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
12,849
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 -/ import topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.uniform_mul_action import topology.algebra.ring.basic import topology.algebra.star import topology.algebra.order.field import ring_theory.subring.basic import group_theory.archimedean import algebra.order.group.bounds import algebra.periodic import topology.instances.int /-! # Topological properties of ℝ > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory open classical filter int metric set topological_space open_locale classical topology filter uniformity interval universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : noncompact_space ℝ := int.closed_embedding_coe_real.noncompact_space theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ h₁ h₂⟩ theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ instance : has_continuous_star ℝ := ⟨continuous_id⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : proper_space ℝ := { is_compact_closed_ball := λx r, by { rw real.closed_ball_eq_Icc, apply is_compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) @[simp] lemma real.cocompact_eq : cocompact ℝ = at_bot ⊔ at_top := by simp only [← comap_dist_right_at_top_eq_cocompact (0 : ℝ), real.dist_eq, sub_zero, comap_abs_at_top] /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, |y - x| < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ |x|) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abs ε0 r0 in ⟨δ, δ0, λ a b h, Hδ (H _ a.2) (H _ b.2) h⟩ lemma real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | |r| / 2 < |x|} (half_pos r0) (λ x h, le_of_lt h)) (is_open.mem_nhds ((is_open_lt' (|r| / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.continuous.inv [topological_space α] {f : α → ℝ} (h : ∀a, f a ≠ 0) (hf : continuous f) : continuous (λa, (f a)⁻¹) := show continuous ((has_inv.inv ∘ @subtype.val ℝ (λr, r ≠ 0)) ∘ λa, ⟨f a, h a⟩), from real.continuous_inv.comp (hf.subtype_mk _) lemma real.uniform_continuous_const_mul {x : ℝ} : uniform_continuous ((*) x) := uniform_continuous_const_smul x lemma real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, |(x : ℝ × ℝ).1| < r₁ ∧ |x.2| < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε0 in ⟨δ, δ0, λ a b h, let ⟨h₁, h₂⟩ := max_lt_iff.1 h in Hδ (H _ a.2).1 (H _ b.2).2 h₁ h₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | |x| < |a₁| + 1} ×ˢ {x | |x| < |a₂| + 1}) (λ x, id)) (is_open.mem_nhds (((is_open_gt' (|a₁| + 1)).preimage continuous_abs).prod ((is_open_gt' (|a₂| + 1)).preimage continuous_abs )) ⟨lt_add_one (|a₁|), lt_add_one (|a₂|)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw real.closed_ball_eq_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨bdd_below_Icc.mono hr, bdd_above_Icc.mono hr⟩ end, λ h, bounded_of_bdd_above_of_bdd_below h.2 h.1⟩ lemma real.subset_Icc_Inf_Sup_of_bounded {s : set ℝ} (h : bounded s) : s ⊆ Icc (Inf s) (Sup s) := subset_Icc_cInf_cSup (real.bounded_iff_bdd_below_bdd_above.1 h).1 (real.bounded_iff_bdd_below_bdd_above.1 h).2 end section periodic namespace function lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : 0 < c) (hf : continuous f) : is_compact (range f) := begin convert is_compact_Icc.image hf, ext x, refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩, rintros ⟨y, h1⟩, obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico₀ hc y, exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩, end /-- A continuous, periodic function has compact range. -/ lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : is_compact (range f) := begin cases lt_or_gt_of_ne hc with hneg hpos, exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf], end /-- A continuous, periodic function is bounded. -/ lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : bounded (range f) := (hp.compact_of_continuous hc hf).bounded end function end periodic section subgroups namespace int open metric /-- Under the coercion from `ℤ` to `ℝ`, inverse images of compact sets are finite. -/ lemma tendsto_coe_cofinite : tendsto (coe : ℤ → ℝ) cofinite (cocompact ℝ) := begin refine tendsto_cocompact_of_tendsto_dist_comp_at_top (0 : ℝ) _, simp only [filter.tendsto_at_top, eventually_cofinite, not_le, ← mem_ball], change ∀ r : ℝ, (coe ⁻¹' (ball (0 : ℝ) r)).finite, simp [real.ball_eq_Ioo, set.finite_Ioo], end /-- For nonzero `a`, the "multiples of `a`" map `zmultiples_hom` from `ℤ` to `ℝ` is discrete, i.e. inverse images of compact sets are finite. -/ lemma tendsto_zmultiples_hom_cofinite {a : ℝ} (ha : a ≠ 0) : tendsto (zmultiples_hom ℝ a) cofinite (cocompact ℝ) := begin convert (tendsto_cocompact_mul_right₀ ha).comp int.tendsto_coe_cofinite, ext n, simp, end end int namespace add_subgroup /-- The subgroup "multiples of `a`" (`zmultiples a`) is a discrete subgroup of `ℝ`, i.e. its intersection with compact sets is finite. -/ lemma tendsto_zmultiples_subtype_cofinite (a : ℝ) : tendsto (zmultiples a).subtype cofinite (cocompact ℝ) := begin rcases eq_or_ne a 0 with rfl | ha, { rw add_subgroup.zmultiples_zero_eq_bot, intros K hK, rw [filter.mem_map, mem_cofinite], apply set.to_finite }, intros K hK, have H := int.tendsto_zmultiples_hom_cofinite ha hK, simp only [filter.mem_map, mem_cofinite, ← preimage_compl] at ⊢ H, rw [← (zmultiples_hom ℝ a).range_restrict_surjective.image_preimage ((zmultiples a).subtype ⁻¹' Kᶜ), ← preimage_comp, ← add_monoid_hom.coe_comp_range_restrict], exact finite.image _ H, end end add_subgroup /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, |x - g| < ε, by simpa only [real.mem_closure_iff, abs_sub_comm], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
587f00eff7c483acdbe7acb567e3403bff43d31a
4727251e0cd73359b15b664c3170e5d754078599
/src/data/nat/sqrt.lean
3df252d2a0672b54265210d4520163982cc7ba4a
[ "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
9,632
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, Johannes Hölzl, Mario Carneiro -/ import data.int.basic /-! # Square root of natural numbers This file defines an efficient binary implementation of the square root function that returns the unique `r` such that `r * r ≤ n < (r + 1) * (r + 1)`. It takes advantage of the binary representation by replacing the multiplication by 2 appearing in `(a + b)^2 = a^2 + 2 * a * b + b^2` by a bitmask manipulation. ## Reference See [Wikipedia, *Methods of computing square roots*] (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)). -/ namespace nat theorem sqrt_aux_dec {b} (h : b ≠ 0) : shiftr b 2 < b := begin simp only [shiftr_eq_div_pow], apply (nat.div_lt_iff_lt_mul' (dec_trivial : 0 < 4)).2, have := nat.mul_lt_mul_of_pos_left (dec_trivial : 1 < 4) (nat.pos_of_ne_zero h), rwa mul_one at this end /-- Auxiliary function for `nat.sqrt`. See e.g. <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> -/ def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ @[pp_nodot] def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end theorem sqrt_aux_0 (r n) : sqrt_aux 0 r n = r := by rw sqrt_aux; simp local attribute [simp] sqrt_aux_0 theorem sqrt_aux_1 {r n b} (h : b ≠ 0) {n'} (h₂ : r + b + n' = n) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r + b) n' := by rw sqrt_aux; simp only [h, h₂.symm, int.coe_nat_add, if_false]; rw [add_comm _ (n':ℤ), add_sub_cancel, sqrt_aux._match_1] theorem sqrt_aux_2 {r n b} (h : b ≠ 0) (h₂ : n < r + b) : sqrt_aux b r n = sqrt_aux (shiftr b 2) (div2 r) n := begin rw sqrt_aux; simp only [h, h₂, if_false], cases int.eq_neg_succ_of_lt_zero (sub_lt_zero.2 (int.coe_nat_lt_coe_nat_of_lt h₂)) with k e, rw [e, sqrt_aux._match_1] end private def is_sqrt (n q : ℕ) : Prop := q*q ≤ n ∧ n < (q+1)*(q+1) local attribute [-simp] mul_eq_mul_left_iff mul_eq_mul_right_iff private lemma sqrt_aux_is_sqrt_lemma (m r n : ℕ) (h₁ : r*r ≤ n) (m') (hm : shiftr (2^m * 2^m) 2 = m') (H1 : n < (r + 2^m) * (r + 2^m) → is_sqrt n (sqrt_aux m' (r * 2^m) (n - r * r))) (H2 : (r + 2^m) * (r + 2^m) ≤ n → is_sqrt n (sqrt_aux m' ((r + 2^m) * 2^m) (n - (r + 2^m) * (r + 2^m)))) : is_sqrt n (sqrt_aux (2^m * 2^m) ((2*r)*2^m) (n - r*r)) := begin have b0 : 2 ^ m * 2 ^ m ≠ 0, from mul_self_ne_zero.2 (pow_ne_zero m two_ne_zero), have lb : n - r * r < 2 * r * 2^m + 2^m * 2^m ↔ n < (r+2^m)*(r+2^m), { rw [tsub_lt_iff_right h₁], simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_comm, add_assoc, add_left_comm] }, have re : div2 (2 * r * 2^m) = r * 2^m, { rw [div2_val, mul_assoc, nat.mul_div_cancel_left _ (dec_trivial:2>0)] }, cases lt_or_ge n ((r+2^m)*(r+2^m)) with hl hl, { rw [sqrt_aux_2 b0 (lb.2 hl), hm, re], apply H1 hl }, { cases le.dest hl with n' e, rw [@sqrt_aux_1 (2 * r * 2^m) (n-r*r) (2^m * 2^m) b0 (n - (r + 2^m) * (r + 2^m)), hm, re, ← right_distrib], { apply H2 hl }, apply eq.symm, apply tsub_eq_of_eq_add_rev, rw [← add_assoc, (_ : r*r + _ = _)], exact (add_tsub_cancel_of_le hl).symm, simp [left_distrib, right_distrib, two_mul, mul_comm, mul_assoc, add_assoc] }, end private lemma sqrt_aux_is_sqrt (n) : ∀ m r, r*r ≤ n → n < (r + 2^(m+1)) * (r + 2^(m+1)) → is_sqrt n (sqrt_aux (2^m * 2^m) (2*r*2^m) (n - r*r)) | 0 r h₁ h₂ := by apply sqrt_aux_is_sqrt_lemma 0 r n h₁ 0 rfl; intro h; simp; [exact ⟨h₁, h⟩, exact ⟨h, h₂⟩] | (m+1) r h₁ h₂ := begin apply sqrt_aux_is_sqrt_lemma (m+1) r n h₁ (2^m * 2^m) (by simp [shiftr, pow_succ, div2_val, mul_comm, mul_left_comm]; repeat {rw @nat.mul_div_cancel_left _ 2 dec_trivial}); intro h, { have := sqrt_aux_is_sqrt m r h₁ h, simpa [pow_succ, mul_comm, mul_assoc] }, { rw [pow_succ', mul_two, ← add_assoc] at h₂, have := sqrt_aux_is_sqrt m (r + 2^(m+1)) h h₂, rwa show (r + 2^(m + 1)) * 2^(m+1) = 2 * (r + 2^(m + 1)) * 2^m, by simp [pow_succ, mul_comm, mul_left_comm] } end private lemma sqrt_is_sqrt (n : ℕ) : is_sqrt n (sqrt n) := begin generalize e : size n = s, cases s with s; simp [e, sqrt], { rw [size_eq_zero.1 e, is_sqrt], exact dec_trivial }, { have := sqrt_aux_is_sqrt n (div2 s) 0 (zero_le _), simp [show 2^div2 s * 2^div2 s = shiftl 1 (bit0 (div2 s)), by { generalize: div2 s = x, change bit0 x with x+x, rw [one_shiftl, pow_add] }] at this, apply this, rw [← pow_add, ← mul_two], apply size_le.1, rw e, apply (@div_lt_iff_lt_mul _ _ 2 dec_trivial).1, rw [div2_val], apply lt_succ_self } end theorem sqrt_le (n : ℕ) : sqrt n * sqrt n ≤ n := (sqrt_is_sqrt n).left theorem sqrt_le' (n : ℕ) : (sqrt n) ^ 2 ≤ n := eq.trans_le (sq (sqrt n)) (sqrt_le n) theorem lt_succ_sqrt (n : ℕ) : n < succ (sqrt n) * succ (sqrt n) := (sqrt_is_sqrt n).right theorem lt_succ_sqrt' (n : ℕ) : n < (succ (sqrt n)) ^ 2 := trans_rel_left (λ i j, i < j) (lt_succ_sqrt n) (sq (succ (sqrt n))).symm theorem sqrt_le_add (n : ℕ) : n ≤ sqrt n * sqrt n + sqrt n + sqrt n := by rw ← succ_mul; exact le_of_lt_succ (lt_succ_sqrt n) theorem le_sqrt {m n : ℕ} : m ≤ sqrt n ↔ m*m ≤ n := ⟨λ h, le_trans (mul_self_le_mul_self h) (sqrt_le n), λ h, le_of_lt_succ $ mul_self_lt_mul_self_iff.2 $ lt_of_le_of_lt h (lt_succ_sqrt n)⟩ theorem le_sqrt' {m n : ℕ} : m ≤ sqrt n ↔ m ^ 2 ≤ n := by simpa only [pow_two] using le_sqrt theorem sqrt_lt {m n : ℕ} : sqrt m < n ↔ m < n*n := lt_iff_lt_of_le_iff_le le_sqrt theorem sqrt_lt' {m n : ℕ} : sqrt m < n ↔ m < n ^ 2 := lt_iff_lt_of_le_iff_le le_sqrt' theorem sqrt_le_self (n : ℕ) : sqrt n ≤ n := le_trans (le_mul_self _) (sqrt_le n) theorem sqrt_le_sqrt {m n : ℕ} (h : m ≤ n) : sqrt m ≤ sqrt n := le_sqrt.2 (le_trans (sqrt_le _) h) @[simp] lemma sqrt_zero : sqrt 0 = 0 := by rw [sqrt, size_zero, sqrt._match_1] theorem sqrt_eq_zero {n : ℕ} : sqrt n = 0 ↔ n = 0 := ⟨λ h, nat.eq_zero_of_le_zero $ le_of_lt_succ $ (@sqrt_lt n 1).1 $ by rw [h]; exact dec_trivial, by { rintro rfl, simp }⟩ theorem eq_sqrt {n q} : q = sqrt n ↔ q*q ≤ n ∧ n < (q+1)*(q+1) := ⟨λ e, e.symm ▸ sqrt_is_sqrt n, λ ⟨h₁, h₂⟩, le_antisymm (le_sqrt.2 h₁) (le_of_lt_succ $ sqrt_lt.2 h₂)⟩ theorem eq_sqrt' {n q} : q = sqrt n ↔ q ^ 2 ≤ n ∧ n < (q+1) ^ 2 := by simpa only [pow_two] using eq_sqrt theorem le_three_of_sqrt_eq_one {n : ℕ} (h : sqrt n = 1) : n ≤ 3 := le_of_lt_succ $ (@sqrt_lt n 2).1 $ by rw [h]; exact dec_trivial theorem sqrt_lt_self {n : ℕ} (h : 1 < n) : sqrt n < n := sqrt_lt.2 $ by have := nat.mul_lt_mul_of_pos_left h (lt_of_succ_lt h); rwa [mul_one] at this theorem sqrt_pos {n : ℕ} : 0 < sqrt n ↔ 0 < n := le_sqrt theorem sqrt_add_eq (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n*n + a) = n := le_antisymm (le_of_lt_succ $ sqrt_lt.2 $ by rw [succ_mul, mul_succ, add_succ, add_assoc]; exact lt_succ_of_le (nat.add_le_add_left h _)) (le_sqrt.2 $ nat.le_add_right _ _) theorem sqrt_add_eq' (n : ℕ) {a : ℕ} (h : a ≤ n + n) : sqrt (n ^ 2 + a) = n := (congr_arg (λ i, sqrt (i + a)) (sq n)).trans (sqrt_add_eq n h) theorem sqrt_eq (n : ℕ) : sqrt (n*n) = n := sqrt_add_eq n (zero_le _) theorem sqrt_eq' (n : ℕ) : sqrt (n ^ 2) = n := sqrt_add_eq' n (zero_le _) @[simp] lemma sqrt_one : sqrt 1 = 1 := sqrt_eq 1 theorem sqrt_succ_le_succ_sqrt (n : ℕ) : sqrt n.succ ≤ n.sqrt.succ := le_of_lt_succ $ sqrt_lt.2 $ lt_succ_of_le $ succ_le_succ $ le_trans (sqrt_le_add n) $ add_le_add_right (by refine add_le_add (nat.mul_le_mul_right _ _) _; exact nat.le_add_right _ 2) _ theorem exists_mul_self (x : ℕ) : (∃ n, n * n = x) ↔ sqrt x * sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq], λ h, ⟨sqrt x, h⟩⟩ theorem exists_mul_self' (x : ℕ) : (∃ n, n ^ 2 = x) ↔ (sqrt x) ^ 2 = x := by simpa only [pow_two] using exists_mul_self x theorem sqrt_mul_sqrt_lt_succ (n : ℕ) : sqrt n * sqrt n < n + 1 := lt_succ_iff.mpr (sqrt_le _) theorem sqrt_mul_sqrt_lt_succ' (n : ℕ) : (sqrt n) ^ 2 < n + 1 := lt_succ_iff.mpr (sqrt_le' _) theorem succ_le_succ_sqrt (n : ℕ) : n + 1 ≤ (sqrt n + 1) * (sqrt n + 1) := le_of_pred_lt (lt_succ_sqrt _) theorem succ_le_succ_sqrt' (n : ℕ) : n + 1 ≤ (sqrt n + 1) ^ 2 := le_of_pred_lt (lt_succ_sqrt' _) /-- There are no perfect squares strictly between m² and (m+1)² -/ theorem not_exists_sq {n m : ℕ} (hl : m * m < n) (hr : n < (m + 1) * (m + 1)) : ¬ ∃ t, t * t = n := begin rintro ⟨t, rfl⟩, have h1 : m < t, from nat.mul_self_lt_mul_self_iff.mpr hl, have h2 : t < m + 1, from nat.mul_self_lt_mul_self_iff.mpr hr, exact (not_lt_of_ge $ le_of_lt_succ h2) h1 end theorem not_exists_sq' {n m : ℕ} (hl : m ^ 2 < n) (hr : n < (m + 1) ^ 2) : ¬ ∃ t, t ^ 2 = n := by simpa only [pow_two] using not_exists_sq (by simpa only [pow_two] using hl) (by simpa only [pow_two] using hr) end nat
f8e81ca96385e41ac482ddcbc3f8921c51f9958e
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/metric_space/closeds.lean
627843838cc967f9ddfa4db4be1bcbd571c54bd3
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
21,566
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.metric_space.hausdorff_distance topology.opens analysis.specific_limits /-! # Closed subsets This file defines the metric and emetric space structure on the types of closed subsets and nonempty compact subsets of a metric or emetric space. The Hausdorff distance induces an emetric space structure on the type of closed subsets of an emetric space, called `closeds`. Its completeness, resp. compactness, resp. second-countability, follow from the corresponding properties of the original space. In a metric space, the type of nonempty compact subsets (called `nonempty_compacts`) also inherits a metric space structure from the Hausdorff distance, as the Hausdorff edistance is always finite in this context. -/ noncomputable theory open_locale classical open_locale topological_space universe u open classical set function topological_space filter namespace emetric section variables {α : Type u} [emetric_space α] {s : set α} /-- In emetric spaces, the Hausdorff edistance defines an emetric space structure on the type of closed subsets -/ instance closeds.emetric_space : emetric_space (closeds α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq ((Hausdorff_edist_zero_iff_eq_of_closed s.property t.property).1 h) } /-- The edistance to a closed set depends continuously on the point and the set -/ lemma continuous_inf_edist_Hausdorff_edist : continuous (λp : α × (closeds α), inf_edist p.1 (p.2).val) := begin refine continuous_of_le_add_edist 2 (by simp) _, rintros ⟨x, s⟩ ⟨y, t⟩, calc inf_edist x (s.val) ≤ inf_edist x (t.val) + Hausdorff_edist (t.val) (s.val) : inf_edist_le_inf_edist_add_Hausdorff_edist ... ≤ (inf_edist y (t.val) + edist x y) + Hausdorff_edist (t.val) (s.val) : add_le_add_right' inf_edist_le_inf_edist_add_edist ... = inf_edist y (t.val) + (edist x y + Hausdorff_edist (s.val) (t.val)) : by simp [add_comm, add_left_comm, Hausdorff_edist_comm] ... ≤ inf_edist y (t.val) + (edist (x, s) (y, t) + edist (x, s) (y, t)) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = inf_edist y (t.val) + 2 * edist (x, s) (y, t) : by rw [← mul_two, mul_comm] end /-- Subsets of a given closed subset form a closed set -/ lemma is_closed_subsets_of_is_closed (hs : is_closed s) : is_closed {t : closeds α | t.val ⊆ s} := begin refine is_closed_of_closure_subset (λt ht x hx, _), -- t : closeds α, ht : t ∈ closure {t : closeds α | t.val ⊆ s}, -- x : α, hx : x ∈ t.val -- goal : x ∈ s have : x ∈ closure s, { refine mem_closure_iff.2 (λε εpos, _), rcases mem_closure_iff.1 ht ε εpos with ⟨u, hu, Dtu⟩, -- u : closeds α, hu : u ∈ {t : closeds α | t.val ⊆ s}, hu' : edist t u < ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dtu with ⟨y, hy, Dxy⟩, -- y : α, hy : y ∈ u.val, Dxy : edist x y < ε exact ⟨y, hu hy, Dxy⟩ }, rwa closure_eq_of_is_closed hs at this, end /-- By definition, the edistance on `closeds α` is given by the Hausdorff edistance -/ lemma closeds.edist_eq {s t : closeds α} : edist s t = Hausdorff_edist s.val t.val := rfl /-- In a complete space, the type of closed subsets is complete for the Hausdorff edistance. -/ instance closeds.complete_space [complete_space α] : complete_space (closeds α) := begin /- We will show that, if a sequence of sets `s n` satisfies `edist (s n) (s (n+1)) < 2^{-n}`, then it converges. This is enough to guarantee completeness, by a standard completeness criterion. We use the shorthand `B n = 2^{-n}` in ennreal. -/ let B : ℕ → ennreal := λ n, (2⁻¹)^n, have B_pos : ∀ n, (0:ennreal) < B n, by simp [B, ennreal.pow_pos], have B_ne_top : ∀ n, B n ≠ ⊤, by simp [B, ennreal.div_def, ennreal.pow_ne_top], /- Consider a sequence of closed sets `s n` with `edist (s n) (s (n+1)) < B n`. We will show that it converges. The limit set is t0 = ⋂n, closure (⋃m≥n, s m). We will have to show that a point in `s n` is close to a point in `t0`, and a point in `t0` is close to a point in `s n`. The completeness then follows from a standard criterion. -/ refine complete_of_convergent_controlled_sequences B B_pos (λs hs, _), let t0 := ⋂n, closure (⋃m≥n, (s m).val), let t : closeds α := ⟨t0, is_closed_Inter (λ_, is_closed_closure)⟩, use t, -- The inequality is written this way to agree with `edist_le_of_edist_le_geometric_of_tendsto₀` have I1 : ∀n:ℕ, ∀x ∈ (s n).val, ∃y ∈ t0, edist x y ≤ 2 * B n, { /- This is the main difficulty of the proof. Starting from `x ∈ s n`, we want to find a point in `t0` which is close to `x`. Define inductively a sequence of points `z m` with `z n = x` and `z m ∈ s m` and `edist (z m) (z (m+1)) ≤ B m`. This is possible since the Hausdorff distance between `s m` and `s (m+1)` is at most `B m`. This sequence is a Cauchy sequence, therefore converging as the space is complete, to a limit which satisfies the required properties. -/ assume n x hx, obtain ⟨z, hz₀, hz⟩ : ∃ z : Π l, (s (n+l)).val, (z 0:α) = x ∧ ∀ k, edist (z k:α) (z (k+1):α) ≤ B n / 2^k, { -- We prove existence of the sequence by induction. have : ∀ (l : ℕ) (z : (s (n+l)).val), ∃ z' : (s (n+l+1)).val, edist (z:α) z' ≤ B n / 2^l, { assume l z, obtain ⟨z', z'_mem, hz'⟩ : ∃ z' ∈ (s (n+l+1)).val, edist (z:α) z' < B n / 2^l, { apply exists_edist_lt_of_Hausdorff_edist_lt z.2, simp only [B, ennreal.div_def, ennreal.inv_pow'], rw [← pow_add], apply hs; simp }, exact ⟨⟨z', z'_mem⟩, le_of_lt hz'⟩ }, use [λ k, nat.rec_on k ⟨x, hx⟩ (λl z, some (this l z)), rfl], exact λ k, some_spec (this k _) }, -- it follows from the previous bound that `z` is a Cauchy sequence have : cauchy_seq (λ k, ((z k):α)), from cauchy_seq_of_edist_le_geometric_two (B n) (B_ne_top n) hz, -- therefore, it converges rcases cauchy_seq_tendsto_of_complete this with ⟨y, y_lim⟩, use y, -- the limit point `y` will be the desired point, in `t0` and close to our initial point `x`. -- First, we check it belongs to `t0`. have : y ∈ t0 := mem_Inter.2 (λk, mem_closure_of_tendsto (by simp) y_lim begin simp only [exists_prop, set.mem_Union, filter.mem_at_top_sets, set.mem_preimage, set.preimage_Union], exact ⟨k, λ m hm, ⟨n+m, zero_add k ▸ add_le_add (zero_le n) hm, (z m).2⟩⟩ end), use this, -- Then, we check that `y` is close to `x = z n`. This follows from the fact that `y` -- is the limit of `z k`, and the distance between `z n` and `z k` has already been estimated. rw [← hz₀], exact edist_le_of_edist_le_geometric_two_of_tendsto₀ (B n) hz y_lim }, have I2 : ∀n:ℕ, ∀x ∈ t0, ∃y ∈ (s n).val, edist x y ≤ 2 * B n, { /- For the (much easier) reverse inequality, we start from a point `x ∈ t0` and we want to find a point `y ∈ s n` which is close to `x`. `x` belongs to `t0`, the intersection of the closures. In particular, it is well approximated by a point `z` in `⋃m≥n, s m`, say in `s m`. Since `s m` and `s n` are close, this point is itself well approximated by a point `y` in `s n`, as required. -/ assume n x xt0, have : x ∈ closure (⋃m≥n, (s m).val), by apply mem_Inter.1 xt0 n, rcases mem_closure_iff.1 this (B n) (B_pos n) with ⟨z, hz, Dxz⟩, -- z : α, Dxz : edist x z < B n, simp only [exists_prop, set.mem_Union] at hz, rcases hz with ⟨m, ⟨m_ge_n, hm⟩⟩, -- m : ℕ, m_ge_n : m ≥ n, hm : z ∈ (s m).val have : Hausdorff_edist (s m).val (s n).val < B n := hs n m n m_ge_n (le_refl n), rcases exists_edist_lt_of_Hausdorff_edist_lt hm this with ⟨y, hy, Dzy⟩, -- y : α, hy : y ∈ (s n).val, Dzy : edist z y < B n exact ⟨y, hy, calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... ≤ B n + B n : add_le_add' (le_of_lt Dxz) (le_of_lt Dzy) ... = 2 * B n : (two_mul _).symm ⟩ }, -- Deduce from the above inequalities that the distance between `s n` and `t0` is at most `2 B n`. have main : ∀n:ℕ, edist (s n) t ≤ 2 * B n := λn, Hausdorff_edist_le_of_mem_edist (I1 n) (I2 n), -- from this, the convergence of `s n` to `t0` follows. refine (tendsto_at_top _).2 (λε εpos, _), have : tendsto (λn, 2 * B n) at_top (𝓝 (2 * 0)), from ennreal.tendsto.const_mul (ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 $ by simp [ennreal.one_lt_two]) (or.inr $ by simp), rw mul_zero at this, obtain ⟨N, hN⟩ : ∃ N, ∀ b ≥ N, ε > 2 * B b, from ((tendsto_order.1 this).2 ε εpos).exists_forall_of_at_top, exact ⟨N, λn hn, lt_of_le_of_lt (main n) (hN n hn)⟩ end /-- In a compact space, the type of closed subsets is compact. -/ instance closeds.compact_space [compact_space α] : compact_space (closeds α) := ⟨begin /- by completeness, it suffices to show that it is totally bounded, i.e., for all ε>0, there is a finite set which is ε-dense. start from a set `s` which is ε-dense in α. Then the subsets of `s` are finitely many, and ε-dense for the Hausdorff distance. -/ refine compact_of_totally_bounded_is_closed (emetric.totally_bounded_iff.2 (λε εpos, _)) is_closed_univ, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases emetric.totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 (@compact_univ α _ _)).1 δ δpos with ⟨s, fs, hs⟩, -- s : set α, fs : finite s, hs : univ ⊆ ⋃ (y : α) (H : y ∈ s), eball y δ -- we first show that any set is well approximated by a subset of `s`. have main : ∀ u : set α, ∃v ⊆ s, Hausdorff_edist u v ≤ δ, { assume u, let v := {x : α | x ∈ s ∧ ∃y∈u, edist x y < δ}, existsi [v, ((λx hx, hx.1) : v ⊆ s)], refine Hausdorff_edist_le_of_mem_edist _ _, { assume x hx, have : x ∈ ⋃y ∈ s, ball y δ := hs (by simp), rcases mem_bUnion_iff.1 this with ⟨y, ys, dy⟩, have : edist y x < δ := by simp at dy; rwa [edist_comm] at dy, exact ⟨y, ⟨ys, ⟨x, hx, this⟩⟩, le_of_lt dy⟩ }, { rintros x ⟨hx1, ⟨y, yu, hy⟩⟩, exact ⟨y, yu, le_of_lt hy⟩ }}, -- introduce the set F of all subsets of `s` (seen as members of `closeds α`). let F := {f : closeds α | f.val ⊆ s}, use F, split, -- `F` is finite { apply @finite_of_finite_image _ _ F (λf, f.val), { exact subtype.val_injective.inj_on F }, { refine finite_subset (finite_subsets_of_finite fs) (λb, _), simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib], assume x hx hx', rwa hx' at hx }}, -- `F` is ε-dense { assume u _, rcases main u.val with ⟨t0, t0s, Dut0⟩, have : is_closed t0 := closed_of_compact _ (finite_subset fs t0s).compact, let t : closeds α := ⟨t0, this⟩, have : t ∈ F := t0s, have : edist u t < ε := lt_of_le_of_lt Dut0 δlt, apply mem_bUnion_iff.2, exact ⟨t, ‹t ∈ F›, this⟩ } end⟩ /-- In an emetric space, the type of non-empty compact subsets is an emetric space, where the edistance is the Hausdorff edistance -/ instance nonempty_compacts.emetric_space : emetric_space (nonempty_compacts α) := { edist := λs t, Hausdorff_edist s.val t.val, edist_self := λs, Hausdorff_edist_self, edist_comm := λs t, Hausdorff_edist_comm, edist_triangle := λs t u, Hausdorff_edist_triangle, eq_of_edist_eq_zero := λs t h, subtype.eq $ begin have : closure (s.val) = closure (t.val) := Hausdorff_edist_zero_iff_closure_eq_closure.1 h, rwa [closure_eq_iff_is_closed.2 (closed_of_compact _ s.property.2), closure_eq_iff_is_closed.2 (closed_of_compact _ t.property.2)] at this, end } /-- `nonempty_compacts.to_closeds` is a uniform embedding (as it is an isometry) -/ lemma nonempty_compacts.to_closeds.uniform_embedding : uniform_embedding (@nonempty_compacts.to_closeds α _ _) := isometry.uniform_embedding $ λx y, rfl /-- The range of `nonempty_compacts.to_closeds` is closed in a complete space -/ lemma nonempty_compacts.is_closed_in_closeds [complete_space α] : is_closed (range $ @nonempty_compacts.to_closeds α _ _) := begin have : range nonempty_compacts.to_closeds = {s : closeds α | s.val.nonempty ∧ compact s.val}, from range_inclusion _, rw this, refine is_closed_of_closure_subset (λs hs, ⟨_, _⟩), { -- take a set set t which is nonempty and at a finite distance of s rcases mem_closure_iff.1 hs ⊤ ennreal.coe_lt_top with ⟨t, ht, Dst⟩, rw edist_comm at Dst, -- since `t` is nonempty, so is `s` exact nonempty_of_Hausdorff_edist_ne_top ht.1 (ne_of_lt Dst) }, { refine compact_iff_totally_bounded_complete.2 ⟨_, is_complete_of_is_closed s.property⟩, refine totally_bounded_iff.2 (λε εpos, _), -- we have to show that s is covered by finitely many eballs of radius ε -- pick a nonempty compact set t at distance at most ε/2 of s rcases mem_closure_iff.1 hs (ε/2) (ennreal.half_pos εpos) with ⟨t, ht, Dst⟩, -- cover this space with finitely many balls of radius ε/2 rcases totally_bounded_iff.1 (compact_iff_totally_bounded_complete.1 ht.2).1 (ε/2) (ennreal.half_pos εpos) with ⟨u, fu, ut⟩, refine ⟨u, ⟨fu, λx hx, _⟩⟩, -- u : set α, fu : finite u, ut : t.val ⊆ ⋃ (y : α) (H : y ∈ u), eball y (ε / 2) -- then s is covered by the union of the balls centered at u of radius ε rcases exists_edist_lt_of_Hausdorff_edist_lt hx Dst with ⟨z, hz, Dxz⟩, rcases mem_bUnion_iff.1 (ut hz) with ⟨y, hy, Dzy⟩, have : edist x y < ε := calc edist x y ≤ edist x z + edist z y : edist_triangle _ _ _ ... < ε/2 + ε/2 : ennreal.add_lt_add Dxz Dzy ... = ε : ennreal.add_halves _, exact mem_bUnion hy this }, end /-- In a complete space, the type of nonempty compact subsets is complete. This follows from the same statement for closed subsets -/ instance nonempty_compacts.complete_space [complete_space α] : complete_space (nonempty_compacts α) := (complete_space_iff_is_complete_range nonempty_compacts.to_closeds.uniform_embedding).2 $ is_complete_of_is_closed nonempty_compacts.is_closed_in_closeds /-- In a compact space, the type of nonempty compact subsets is compact. This follows from the same statement for closed subsets -/ instance nonempty_compacts.compact_space [compact_space α] : compact_space (nonempty_compacts α) := ⟨begin rw embedding.compact_iff_compact_image nonempty_compacts.to_closeds.uniform_embedding.embedding, rw [image_univ], exact nonempty_compacts.is_closed_in_closeds.compact end⟩ /-- In a second countable space, the type of nonempty compact subsets is second countable -/ instance nonempty_compacts.second_countable_topology [second_countable_topology α] : second_countable_topology (nonempty_compacts α) := begin haveI : separable_space (nonempty_compacts α) := begin /- To obtain a countable dense subset of `nonempty_compacts α`, start from a countable dense subset `s` of α, and then consider all its finite nonempty subsets. This set is countable and made of nonempty compact sets. It turns out to be dense: by total boundedness, any compact set `t` can be covered by finitely many small balls, and approximations in `s` of the centers of these balls give the required finite approximation of `t`. -/ have : separable_space α := by apply_instance, rcases this.exists_countable_closure_eq_univ with ⟨s, cs, s_dense⟩, let v0 := {t : set α | finite t ∧ t ⊆ s}, let v : set (nonempty_compacts α) := {t : nonempty_compacts α | t.val ∈ v0}, refine ⟨⟨v, ⟨_, _⟩⟩⟩, { have : countable (subtype.val '' v), { refine countable_subset (λx hx, _) (countable_set_of_finite_subset cs), rcases (mem_image _ _ _).1 hx with ⟨y, ⟨hy, yx⟩⟩, rw ← yx, exact hy }, apply countable_of_injective_of_countable_image _ this, apply subtype.val_injective.inj_on }, { refine subset.antisymm (subset_univ _) (λt ht, mem_closure_iff.2 (λε εpos, _)), -- t is a compact nonempty set, that we have to approximate uniformly by a a set in `v`. rcases dense εpos with ⟨δ, δpos, δlt⟩, -- construct a map F associating to a point in α an approximating point in s, up to δ/2. have Exy : ∀x, ∃y, y ∈ s ∧ edist x y < δ/2, { assume x, have : x ∈ closure s := by rw s_dense; exact mem_univ _, rcases mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, hy⟩, exact ⟨y, ⟨ys, hy⟩⟩ }, let F := λx, some (Exy x), have Fspec : ∀x, F x ∈ s ∧ edist x (F x) < δ/2 := λx, some_spec (Exy x), -- cover `t` with finitely many balls. Their centers form a set `a` have : totally_bounded t.val := (compact_iff_totally_bounded_complete.1 t.property.2).1, rcases totally_bounded_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨a, af, ta⟩, -- a : set α, af : finite a, ta : t.val ⊆ ⋃ (y : α) (H : y ∈ a), eball y (δ / 2) -- replace each center by a nearby approximation in `s`, giving a new set `b` let b := F '' a, have : finite b := finite_image _ af, have tb : ∀x ∈ t.val, ∃y ∈ b, edist x y < δ, { assume x hx, rcases mem_bUnion_iff.1 (ta hx) with ⟨z, za, Dxz⟩, existsi [F z, mem_image_of_mem _ za], calc edist x (F z) ≤ edist x z + edist z (F z) : edist_triangle _ _ _ ... < δ/2 + δ/2 : ennreal.add_lt_add Dxz (Fspec z).2 ... = δ : ennreal.add_halves _ }, -- keep only the points in `b` that are close to point in `t`, yielding a new set `c` let c := {y ∈ b | ∃x∈t.val, edist x y < δ}, have : finite c := finite_subset ‹finite b› (λx hx, hx.1), -- points in `t` are well approximated by points in `c` have tc : ∀x ∈ t.val, ∃y ∈ c, edist x y ≤ δ, { assume x hx, rcases tb x hx with ⟨y, yv, Dxy⟩, have : y ∈ c := by simp [c, -mem_image]; exact ⟨yv, ⟨x, hx, Dxy⟩⟩, exact ⟨y, this, le_of_lt Dxy⟩ }, -- points in `c` are well approximated by points in `t` have ct : ∀y ∈ c, ∃x ∈ t.val, edist y x ≤ δ, { rintros y ⟨hy1, ⟨x, xt, Dyx⟩⟩, have : edist y x ≤ δ := calc edist y x = edist x y : edist_comm _ _ ... ≤ δ : le_of_lt Dyx, exact ⟨x, xt, this⟩ }, -- it follows that their Hausdorff distance is small have : Hausdorff_edist t.val c ≤ δ := Hausdorff_edist_le_of_mem_edist tc ct, have Dtc : Hausdorff_edist t.val c < ε := lt_of_le_of_lt this δlt, -- the set `c` is not empty, as it is well approximated by a nonempty set have hc : c.nonempty, from nonempty_of_Hausdorff_edist_ne_top t.property.1 (ne_top_of_lt Dtc), -- let `d` be the version of `c` in the type `nonempty_compacts α` let d : nonempty_compacts α := ⟨c, ⟨hc, ‹finite c›.compact⟩⟩, have : c ⊆ s, { assume x hx, rcases (mem_image _ _ _).1 hx.1 with ⟨y, ⟨ya, yx⟩⟩, rw ← yx, exact (Fspec y).1 }, have : d ∈ v := ⟨‹finite c›, this⟩, -- we have proved that `d` is a good approximation of `t` as requested exact ⟨d, ‹d ∈ v›, Dtc⟩ }, end, apply second_countable_of_separable, end end --section end emetric --namespace namespace metric section variables {α : Type u} [metric_space α] /-- `nonempty_compacts α` inherits a metric space structure, as the Hausdorff edistance between two such sets is finite. -/ instance nonempty_compacts.metric_space : metric_space (nonempty_compacts α) := emetric_space.to_metric_space $ λx y, Hausdorff_edist_ne_top_of_nonempty_of_bounded x.2.1 y.2.1 (bounded_of_compact x.2.2) (bounded_of_compact y.2.2) /-- The distance on `nonempty_compacts α` is the Hausdorff distance, by construction -/ lemma nonempty_compacts.dist_eq {x y : nonempty_compacts α} : dist x y = Hausdorff_dist x.val y.val := rfl lemma lipschitz_inf_dist_set (x : α) : lipschitz_with 1 (λ s : nonempty_compacts α, inf_dist x s.val) := lipschitz_with.of_le_add $ assume s t, by { rw dist_comm, exact inf_dist_le_inf_dist_add_Hausdorff_dist (edist_ne_top t s) } lemma lipschitz_inf_dist : lipschitz_with 2 (λ p : α × (nonempty_compacts α), inf_dist p.1 p.2.val) := @lipschitz_with.uncurry' _ _ _ _ _ _ (λ (x : α) (s : nonempty_compacts α), inf_dist x s.val) 1 1 (λ s, lipschitz_inf_dist_pt s.val) lipschitz_inf_dist_set lemma uniform_continuous_inf_dist_Hausdorff_dist : uniform_continuous (λp : α × (nonempty_compacts α), inf_dist p.1 (p.2).val) := lipschitz_inf_dist.uniform_continuous end --section end metric --namespace
a19734a41dc05197e0e3569c3a5cbf87b5409960
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/equiv/mul_add.lean
cfc75d50c0789d568a9394439b5317d9b6a789d2
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,320
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov -/ import algebra.group.type_tags import algebra.group_with_zero import data.equiv.set /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {A : Type*} {B : Type*} {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {G : Type*} {H : Type*} /-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive inverse from a bijection which preserves addition."] def mul_hom.inverse [has_mul M] [has_mul N] (f : mul_hom M N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : mul_hom N M := { to_fun := g, map_mul' := λ x y, calc g (x * y) = g (f (g x) * f (g y)) : by rw [h₂ x, h₂ y] ... = g (f (g x * g y)) : by rw f.map_mul ... = g x * g y : h₁ _, } /-- The inverse of a bijective `monoid_hom` is a `monoid_hom`. -/ @[to_additive "The inverse of a bijective `add_monoid_hom` is an `add_monoid_hom`.", simps] def monoid_hom.inverse {A B : Type*} [monoid A] [monoid B] (f : A →* B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →* A := { to_fun := g, map_one' := by rw [← f.map_one, h₁], .. (f : mul_hom A B).inverse g h₁ h₂, } set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, mul_hom M N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) (λ _, M → N) := ⟨mul_equiv.to_fun⟩ variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑f.to_equiv = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication (canonical form). -/ @[simp, to_additive] lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := f.map_mul' /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := e.to_equiv.bijective @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := e.to_equiv.injective @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := e.to_equiv.surjective /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} @[to_additive] instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul, .. h.to_equiv.symm} @[simp, to_additive] lemma inv_fun_eq_symm {f : M ≃* N} : f.inv_fun = f.symm := rfl /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive "See Note custom simps projection"] def simps.symm_apply (e : M ≃* N) : N → M := e.symm initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply) initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] lemma to_equiv_mk (f : M → N) (g : N → M) (h₁ h₂ h₃) : (mk f g h₁ h₂ h₃).to_equiv = ⟨f, g, h₁, h₂⟩ := rfl @[simp, to_additive] lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, h₂, h₃⟩ := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M → N) (g h₁ h₂ h₃) : (mul_equiv.mk f g h₁ h₂ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- e.right_inv in canonical form -/ @[simp, to_additive] lemma apply_symm_apply (e : M ≃* N) : ∀ y, e (e.symm y) = y := e.to_equiv.apply_symm_apply /-- e.left_inv in canonical form -/ @[simp, to_additive] lemma symm_apply_apply (e : M ≃* N) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp, to_additive] theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp, to_additive] theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp, to_additive] theorem coe_refl : ⇑(refl M) = id := rfl @[to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem coe_trans (e₁ : M ≃* N) (e₂ : N ≃* P) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem symm_trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (p : P) : (e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := begin have h₁ : f.to_equiv = g.to_equiv := equiv.ext h, cases f, cases g, congr, { exact (funext h) }, { exact congr_arg equiv.inv_fun h₁ } end @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) : (⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) : (mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := h ▸ rfl /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := λ _ _, subsingleton.elim _ _, ..equiv_of_unique_of_unique } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique_of_unique , uniq := λ _, ext $ λ x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative equiv of monoids sends 1 to 1 (and is hence a monoid isomorphism). -/ @[simp, to_additive] lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 := by rw [←mul_one (h 1), ←h.apply_symm_apply 1, ←h.map_mul, one_mul] @[simp, to_additive] lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := h.map_one ▸ h.to_equiv.apply_eq_iff_eq @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := ⟨mt h.map_eq_one_iff.2, mt h.map_eq_one_iff.1⟩ /-- A bijective `monoid` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_monoid` homomorphism is an isomorphism"] noncomputable def of_bijective {M N} [mul_one_class M] [mul_one_class N] (f : M →* N) (hf : function.bijective f) : M ≃* N := { map_mul' := f.map_mul', ..equiv.of_bijective f hf } /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive.", simps apply] def arrow_congr {M N P Q : Type*} [mul_one_class P] [mul_one_class Q] (f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) := { to_fun := λ h n, g (h (f.symm n)), inv_fun := λ k m, g.symm (k (f m)), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid.", simps apply] def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) := { to_fun := λ h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := λ k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A family of multiplicative equivalences `Π j, (Ms j ≃* Ns j)` generates a multiplicative equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `mul_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `mul_equiv.arrow_congr`. -/ @[to_additive add_equiv.Pi_congr_right "A family of additive equivalences `Π j, (Ms j ≃+ Ns j)` generates an additive equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `add_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `add_equiv.arrow_congr`.", simps apply] def Pi_congr_right {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Π j, Ms j) ≃* (Π j, Ns j) := { to_fun := λ x j, es j (x j), inv_fun := λ x j, (es j).symm (x j), map_mul' := λ x y, funext $ λ j, (es j).map_mul (x j) (y j), .. equiv.Pi_congr_right (λ j, (es j).to_equiv) } @[simp] lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, mul_one_class (Ms j)] : Pi_congr_right (λ j, mul_equiv.refl (Ms j)) = mul_equiv.refl _ := rfl @[simp] lemma Pi_congr_right_symm {η : Type*} {Ms Ns : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Pi_congr_right es).symm = (Pi_congr_right $ λ i, (es i).symm) := rfl @[simp] lemma Pi_congr_right_trans {η : Type*} {Ms Ns Ps : η → Type*} [Π j, mul_one_class (Ms j)] [Π j, mul_one_class (Ns j)] [Π j, mul_one_class (Ps j)] (es : ∀ j, Ms j ≃* Ns j) (fs : ∀ j, Ns j ≃* Ps j) : (Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[simp, to_additive] lemma map_inv [group G] [group H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := h.to_monoid_hom.map_inv x end mul_equiv /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive "Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms.", simps {fully_applied := ff}] def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M →* N) (g : N →* M) (h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun h₂, map_mul' := f.map_mul } /-- An additive equivalence of additive groups preserves subtraction. -/ lemma add_equiv.map_sub [add_group A] [add_group B] (h : A ≃+ B) (x y : A) : h (x - y) = h x - h y := h.to_add_monoid_hom.map_sub x y /-- A group is isomorphic to its group of units. -/ @[to_additive to_add_units "An additive group is isomorphic to its group of additive units"] def to_units [group G] : G ≃* units G := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } @[simp, to_additive coe_to_add_units] lemma coe_to_units [group G] (g : G) : (to_units g : G) = g := rfl protected lemma group.is_unit {G} [group G] (x : G) : is_unit x := (to_units x).is_unit namespace units @[simp, to_additive] lemma coe_inv [group G] (u : units G) : ↑u⁻¹ = (u⁻¹ : G) := to_units.symm.map_inv u variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : units M ≃* units N := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_left (u : units M) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma mul_left_symm (u : units M) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_right (u : units M) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma mul_right_symm (u : units M) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl end units namespace equiv section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl /-- extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl variable (G) /-- Inversion on a `group` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type.", simps apply {fully_applied := ff}] protected def inv : perm G := { to_fun := λa, a⁻¹, inv_fun := λa, a⁻¹, left_inv := assume a, inv_inv a, right_inv := assume a, inv_inv a } variable {G} @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl /-- A version of `equiv.mul_left a b⁻¹` that is defeq to `a / b`. -/ @[to_additive /-" A version of `equiv.add_left a (-b)` that is defeq to `a - b`. "-/, simps] protected def div_left (a : G) : G ≃ G := { to_fun := λ b, a / b, inv_fun := λ b, b⁻¹ * a, left_inv := λ b, by simp [div_eq_mul_inv], right_inv := λ b, by simp [div_eq_mul_inv] } @[to_additive] lemma div_left_eq_inv_trans_mul_left (a : G) : equiv.div_left a = (equiv.inv G).trans (equiv.mul_left a) := ext $ λ _, div_eq_mul_inv _ _ /-- A version of `equiv.mul_right a⁻¹ b` that is defeq to `b / a`. -/ @[to_additive /-" A version of `equiv.add_right (-a) b` that is defeq to `b - a`. "-/, simps] protected def div_right (a : G) : G ≃ G := { to_fun := λ b, b / a, inv_fun := λ b, b * a, left_inv := λ b, by simp [div_eq_mul_inv], right_inv := λ b, by simp [div_eq_mul_inv] } @[to_additive] lemma div_right_eq_mul_right_inv (a : G) : equiv.div_right a = equiv.mul_right a⁻¹ := ext $ λ _, div_eq_mul_inv _ _ end group section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_left₀ (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, a * x, inv_fun := λ x, a⁻¹ * x, left_inv := λ x, by { dsimp, rw [← mul_assoc, inv_mul_cancel ha, one_mul] }, right_inv := λ x, by { dsimp, rw [← mul_assoc, mul_inv_cancel ha, one_mul] } } /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_right₀ (a : G) (ha : a ≠ 0) : perm G := { to_fun := λ x, x * a, inv_fun := λ x, x * a⁻¹, left_inv := λ x, by { dsimp, rw [mul_assoc, mul_inv_cancel ha, mul_one] }, right_inv := λ x, by { dsimp, rw [mul_assoc, inv_mul_cancel ha, mul_one] } } end group_with_zero end equiv /-- When the group is commutative, `equiv.inv` is a `mul_equiv`. There is a variant of this `mul_equiv.inv' G : G ≃* Gᵒᵖ` for the non-commutative case. -/ @[to_additive "When the `add_group` is commutative, `equiv.neg` is an `add_equiv`."] def mul_equiv.inv (G : Type*) [comm_group G] : G ≃* G := { to_fun := has_inv.inv, inv_fun := has_inv.inv, map_mul' := mul_inv, ..equiv.inv G} section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags
7753eace7d0a360ec8f04e2ffb5e03d1c64ea6f8
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/extract.lean
30c4de76e9d31bd27d2fdf1a6863944eb5c0a1a3
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
1,544
lean
#eval "abc" /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next; it₁.extract it₂ /- some "" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; it₁.extract it₁ /- none -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next; it₂.extract it₁ /- some "abc" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.next.next.prev.next; it₁.extract it₂ /- some "bcde" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator.next; let it₂ := it₁.next.next.next.next; it₁.extract it₂ /- some "abcde" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.next.next.next.next; it₁.extract it₂ /- some "ab" -/ #eval let s₁ := "abcde"; let s₂ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := s₂.mkIterator.next.next; it₁.extract it₂ /- none -/ #eval let s₁ := "abcde"; let s₂ := "abhde"; let it₁ := s₁.mkIterator; let it₂ := s₂.mkIterator.next.next; it₁.extract it₂ /- none -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.setCurr 'a'; it₁.extract it₂ /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := it₁.next.setCurr 'b'; it₁.extract it₂ /- some "a" -/ #eval let s₁ := "abcde"; let it₁ := s₁.mkIterator; let it₂ := (it₁.next.setCurr 'a').setCurr 'b'; it₁.extract it₂
a77d9fae27e590eaea78d1ec934b5f6ecc40cbe9
856e2e1615a12f95b551ed48fa5b03b245abba44
/src/data/polynomial/ring_division.lean
29077d011334edfdb288c101c60d8a60bf9c8ce4
[ "Apache-2.0" ]
permissive
pimsp/mathlib
8b77e1ccfab21703ba8fbe65988c7de7765aa0e5
913318ca9d6979686996e8d9b5ebf7e74aae1c63
refs/heads/master
1,669,812,465,182
1,597,133,610,000
1,597,133,610,000
281,890,685
1
0
null
1,595,491,577,000
1,595,491,576,000
null
UTF-8
Lean
false
false
13,778
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.basic import data.polynomial.div import data.polynomial.algebra_map /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : polynomial R} variables [comm_ring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.nat_degree := nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0) {z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) : 0 < p.degree := nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj) end comm_ring section integral_domain variables [integral_domain R] {p q : polynomial R} instance : integral_domain (polynomial R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nontrivial, ..polynomial.comm_ring } lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq), with_bot.coe_add, ← degree_eq_nat_degree hp, ← degree_eq_nat_degree hq, degree_mul] @[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := if hp0 : p = 0 then if hn0 : n = 0 then by simp [hp0, hn0] else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp else nat_degree_pow' (by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0) lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a := by simp_rw [is_root, eval_mul, mul_eq_zero] lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := root_mul.1 h lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp only [hp, zero_mul, le_refl] else by rw [degree_mul, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _ end lemma exists_finset_roots : ∀ {p : polynomial R} (hp : p ≠ 0), ∃ s : finset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by simpa only [not_mem_empty, false_iff, not_exists] using h⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial R) : finset R := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) : ((p - C a).roots.card : with_bot ℕ) ≤ degree p := calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) : card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le ... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0 lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) : (p - C a).roots.card ≤ nat_degree p := with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree (λ h, by simp [*, lt_irrefl] at *))) @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma roots_mul (hpq : p * q ≠ 0) : (p * q).roots = p.roots ∪ q.roots := finset.ext $ λ r, by rw [mem_union, mem_roots hpq, mem_roots (mul_ne_zero_iff.1 hpq).1, mem_roots (mul_ne_zero_iff.1 hpq).2, root_mul] @[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := (mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans (by rw [is_root.def, eval_sub, eval_C, sub_eq_zero]) @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := finset.ext $ λ s, by rw [mem_roots (X_sub_C_ne_zero r), root_X_sub_C, mem_singleton, eq_comm] lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : polynomial R) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : finset R := roots ((X : polynomial R) ^ n - C a) @[simp] lemma mem_nth_roots {R : Type*} [integral_domain R] {n : ℕ} (hn : 0 < n) {a x : R} : x ∈ nth_roots n a ↔ x ^ n = a := by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {R : Type*} [integral_domain R] (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := if hn : n = 0 then if h : (X : polynomial R) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, card_empty] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := if hp0 : p = 0 then by simp [hp0] else calc coeff (p.comp q) (nat_degree p * nat_degree q) = p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) : by rw [comp, eval₂, coeff_sum] ... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) : finset.sum_eq_single _ begin assume b hbs hbp, have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]), have : coeff p b ≠ 0, rwa finsupp.mem_support_iff at hbs, refine coeff_eq_zero_of_degree_lt _, rw [degree_mul], erw degree_C this, rw [degree_pow, zero_add, degree_eq_nat_degree hq0, ← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id], rw mul_lt_mul_right, apply lt_of_le_of_ne, assumption', swap, omega, exact le_nat_degree_of_ne_zero this, end begin intro h, contrapose! hp0, rw finsupp.mem_support_iff at h, push_neg at h, rwa ← leading_coeff_eq_zero, end ... = _ : have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p), by rw [leading_coeff, nat_degree_pow], by rw [coeff_C_mul, this, leading_coeff_pow] lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q := le_antisymm nat_degree_comp_le (if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul] else if hqd0 : nat_degree q = 0 then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree, by rw [eq_C_of_degree_le_zero this]; simp else le_nat_degree_of_ne_zero $ have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero], calc coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p : coeff_comp_degree_mul_degree hqd0 ... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0))) 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]; refl lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 := let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq, have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq, have nat_degree (1 : polynomial R) = nat_degree (p * q), from congr_arg _ hq, by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm, _root_.add_eq_zero_iff, ← with_bot.coe_eq_coe, ← degree_eq_nat_degree hp0] at this; exact this.1 @[simp] lemma degree_coe_units (u : units (polynomial R)) : degree (u : polynomial R) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ @[simp] lemma nat_degree_coe_units (u : units (polynomial R)) : nat_degree (u : polynomial R) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f := ⟨λ hf, ⟨f.coeff 0, is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf, (eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩, λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩ lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) : coeff (u : polynomial R) 0 ≠ 0 := begin conv in (0) {rw [← nat_degree_coe_units u]}, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.coe_ne_zero _ end lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q := let ⟨u, hu⟩ := h in by simp [hu.symm] lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) : degree p = 1 := let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg, this.elim (λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x, have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h, by rw h₁ at h₂; exact absurd h₂ dec_trivial) (λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero]) theorem prime_X_sub_C {r : R} : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : polynomial R) := by simpa only [C_0, sub_zero] using (prime_X_sub_C : prime (X - C 0 : polynomial R)) lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : prime p := have p = X - C (- p.coeff 0), by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1, this.symm ▸ prime_X_sub_C theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) := irreducible_of_prime prime_X_sub_C theorem irreducible_X : irreducible (X : polynomial R) := irreducible_of_prime prime_X lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1) (hm : monic p) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm) end integral_domain end polynomial namespace is_integral_domain variables {R : Type*} [comm_ring R] /-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/ lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) := @integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _)) end is_integral_domain
439d25f8bf1a5cf7306379a547badf0112833d58
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/probability/kernel/basic.lean
26f606148e1c5fba097e056c124eefd14199b449
[ "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
26,723
lean
/- Copyright (c) 2022 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rémy Degenne -/ import measure_theory.integral.bochner import measure_theory.constructions.prod.basic /-! # Markov Kernels > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A kernel from a measurable space `α` to another measurable space `β` is a measurable map `α → measure β`, where the measurable space instance on `measure β` is the one defined in `measure_theory.measure.measurable_space`. That is, a kernel `κ` verifies that for all measurable sets `s` of `β`, `a ↦ κ a s` is measurable. ## Main definitions Classes of kernels: * `probability_theory.kernel α β`: kernels from `α` to `β`, defined as the `add_submonoid` of the measurable functions in `α → measure β`. * `probability_theory.is_markov_kernel κ`: a kernel from `α` to `β` is said to be a Markov kernel if for all `a : α`, `k a` is a probability measure. * `probability_theory.is_finite_kernel κ`: a kernel from `α` to `β` is said to be finite if there exists `C : ℝ≥0∞` such that `C < ∞` and for all `a : α`, `κ a univ ≤ C`. This implies in particular that all measures in the image of `κ` are finite, but is stronger since it requires an uniform bound. This stronger condition is necessary to ensure that the composition of two finite kernels is finite. * `probability_theory.is_s_finite_kernel κ`: a kernel is called s-finite if it is a countable sum of finite kernels. Particular kernels: * `probability_theory.kernel.deterministic (f : α → β) (hf : measurable f)`: kernel `a ↦ measure.dirac (f a)`. * `probability_theory.kernel.const α (μβ : measure β)`: constant kernel `a ↦ μβ`. * `probability_theory.kernel.restrict κ (hs : measurable_set s)`: kernel for which the image of `a : α` is `(κ a).restrict s`. Integral: `∫⁻ b, f b ∂(kernel.restrict κ hs a) = ∫⁻ b in s, f b ∂(κ a)` ## Main statements * `probability_theory.kernel.ext_fun`: if `∫⁻ b, f b ∂(κ a) = ∫⁻ b, f b ∂(η a)` for all measurable functions `f` and all `a`, then the two kernels `κ` and `η` are equal. -/ open measure_theory open_locale measure_theory ennreal nnreal big_operators namespace probability_theory /-- A kernel from a measurable space `α` to another measurable space `β` is a measurable function `κ : α → measure β`. The measurable space structure on `measure β` is given by `measure_theory.measure.measurable_space`. A map `κ : α → measure β` is measurable iff `∀ s : set β, measurable_set s → measurable (λ a, κ a s)`. -/ def kernel (α β : Type*) [measurable_space α] [measurable_space β] : add_submonoid (α → measure β) := { carrier := measurable, zero_mem' := measurable_zero, add_mem' := λ f g hf hg, measurable.add hf hg, } instance {α β : Type*} [measurable_space α] [measurable_space β] : has_coe_to_fun (kernel α β) (λ _, α → measure β) := ⟨λ κ, κ.val⟩ variables {α β ι : Type*} {mα : measurable_space α} {mβ : measurable_space β} include mα mβ namespace kernel @[simp] lemma coe_fn_zero : ⇑(0 : kernel α β) = 0 := rfl @[simp] lemma coe_fn_add (κ η : kernel α β) : ⇑(κ + η) = κ + η := rfl omit mα mβ /-- Coercion to a function as an additive monoid homomorphism. -/ def coe_add_hom (α β : Type*) [measurable_space α] [measurable_space β] : kernel α β →+ (α → measure β) := ⟨coe_fn, coe_fn_zero, coe_fn_add⟩ include mα mβ @[simp] lemma zero_apply (a : α) : (0 : kernel α β) a = 0 := rfl @[simp] lemma coe_finset_sum (I : finset ι) (κ : ι → kernel α β) : ⇑(∑ i in I, κ i) = ∑ i in I, κ i := (coe_add_hom α β).map_sum _ _ lemma finset_sum_apply (I : finset ι) (κ : ι → kernel α β) (a : α) : (∑ i in I, κ i) a = ∑ i in I, κ i a := by rw [coe_finset_sum, finset.sum_apply] lemma finset_sum_apply' (I : finset ι) (κ : ι → kernel α β) (a : α) (s : set β) : (∑ i in I, κ i) a s = ∑ i in I, κ i a s := by rw [finset_sum_apply, measure.finset_sum_apply] end kernel /-- A kernel is a Markov kernel if every measure in its image is a probability measure. -/ class is_markov_kernel (κ : kernel α β) : Prop := (is_probability_measure : ∀ a, is_probability_measure (κ a)) /-- A kernel is finite if every measure in its image is finite, with a uniform bound. -/ class is_finite_kernel (κ : kernel α β) : Prop := (exists_univ_le : ∃ C : ℝ≥0∞, C < ∞ ∧ ∀ a, κ a set.univ ≤ C) /-- A constant `C : ℝ≥0∞` such that `C < ∞` (`is_finite_kernel.bound_lt_top κ`) and for all `a : α` and `s : set β`, `κ a s ≤ C` (`measure_le_bound κ a s`). -/ noncomputable def is_finite_kernel.bound (κ : kernel α β) [h : is_finite_kernel κ] : ℝ≥0∞ := h.exists_univ_le.some lemma is_finite_kernel.bound_lt_top (κ : kernel α β) [h : is_finite_kernel κ] : is_finite_kernel.bound κ < ∞ := h.exists_univ_le.some_spec.1 lemma is_finite_kernel.bound_ne_top (κ : kernel α β) [h : is_finite_kernel κ] : is_finite_kernel.bound κ ≠ ∞ := (is_finite_kernel.bound_lt_top κ).ne lemma kernel.measure_le_bound (κ : kernel α β) [h : is_finite_kernel κ] (a : α) (s : set β) : κ a s ≤ is_finite_kernel.bound κ := (measure_mono (set.subset_univ s)).trans (h.exists_univ_le.some_spec.2 a) instance is_finite_kernel_zero (α β : Type*) {mα : measurable_space α} {mβ : measurable_space β} : is_finite_kernel (0 : kernel α β) := ⟨⟨0, ennreal.coe_lt_top, λ a, by simp only [kernel.zero_apply, measure.coe_zero, pi.zero_apply, le_zero_iff]⟩⟩ instance is_finite_kernel.add (κ η : kernel α β) [is_finite_kernel κ] [is_finite_kernel η] : is_finite_kernel (κ + η) := begin refine ⟨⟨is_finite_kernel.bound κ + is_finite_kernel.bound η, ennreal.add_lt_top.mpr ⟨is_finite_kernel.bound_lt_top κ, is_finite_kernel.bound_lt_top η⟩, λ a, _⟩⟩, simp_rw [kernel.coe_fn_add, pi.add_apply, measure.coe_add, pi.add_apply], exact add_le_add (kernel.measure_le_bound _ _ _) (kernel.measure_le_bound _ _ _), end variables {κ : kernel α β} instance is_markov_kernel.is_probability_measure' [h : is_markov_kernel κ] (a : α) : is_probability_measure (κ a) := is_markov_kernel.is_probability_measure a instance is_finite_kernel.is_finite_measure [h : is_finite_kernel κ] (a : α) : is_finite_measure (κ a) := ⟨(kernel.measure_le_bound κ a set.univ).trans_lt (is_finite_kernel.bound_lt_top κ)⟩ @[priority 100] instance is_markov_kernel.is_finite_kernel [h : is_markov_kernel κ] : is_finite_kernel κ := ⟨⟨1, ennreal.one_lt_top, λ a, prob_le_one⟩⟩ namespace kernel @[ext] lemma ext {η : kernel α β} (h : ∀ a, κ a = η a) : κ = η := by { ext1, ext1 a, exact h a, } lemma ext_iff {η : kernel α β} : κ = η ↔ ∀ a, κ a = η a := ⟨λ h a, by rw h, ext⟩ lemma ext_iff' {η : kernel α β} : κ = η ↔ ∀ a (s : set β) (hs : measurable_set s), κ a s = η a s := by simp_rw [ext_iff, measure.ext_iff] lemma ext_fun {η : kernel α β} (h : ∀ a f, measurable f → ∫⁻ b, f b ∂(κ a) = ∫⁻ b, f b ∂(η a)) : κ = η := begin ext a s hs, specialize h a (s.indicator (λ _, 1)) (measurable.indicator measurable_const hs), simp_rw [lintegral_indicator_const hs, one_mul] at h, rw h, end lemma ext_fun_iff {η : kernel α β} : κ = η ↔ ∀ a f, measurable f → ∫⁻ b, f b ∂(κ a) = ∫⁻ b, f b ∂(η a) := ⟨λ h a f hf, by rw h, ext_fun⟩ protected lemma measurable (κ : kernel α β) : measurable κ := κ.prop protected lemma measurable_coe (κ : kernel α β) {s : set β} (hs : measurable_set s) : measurable (λ a, κ a s) := (measure.measurable_coe hs).comp (kernel.measurable κ) section sum /-- Sum of an indexed family of kernels. -/ protected noncomputable def sum [countable ι] (κ : ι → kernel α β) : kernel α β := { val := λ a, measure.sum (λ n, κ n a), property := begin refine measure.measurable_of_measurable_coe _ (λ s hs, _), simp_rw measure.sum_apply _ hs, exact measurable.ennreal_tsum (λ n, kernel.measurable_coe (κ n) hs), end, } lemma sum_apply [countable ι] (κ : ι → kernel α β) (a : α) : kernel.sum κ a = measure.sum (λ n, κ n a) := rfl lemma sum_apply' [countable ι] (κ : ι → kernel α β) (a : α) {s : set β} (hs : measurable_set s) : kernel.sum κ a s = ∑' n, κ n a s := by rw [sum_apply κ a, measure.sum_apply _ hs] @[simp] lemma sum_zero [countable ι] : kernel.sum (λ (i : ι), (0 : kernel α β)) = 0 := begin ext a s hs : 2, rw [sum_apply' _ a hs], simp only [zero_apply, measure.coe_zero, pi.zero_apply, tsum_zero], end lemma sum_comm [countable ι] (κ : ι → ι → kernel α β) : kernel.sum (λ n, kernel.sum (κ n)) = kernel.sum (λ m, kernel.sum (λ n, κ n m)) := by { ext a s hs, simp_rw [sum_apply], rw measure.sum_comm, } @[simp] lemma sum_fintype [fintype ι] (κ : ι → kernel α β) : kernel.sum κ = ∑ i, κ i := by { ext a s hs, simp only [sum_apply' κ a hs, finset_sum_apply' _ κ a s, tsum_fintype], } lemma sum_add [countable ι] (κ η : ι → kernel α β) : kernel.sum (λ n, κ n + η n) = kernel.sum κ + kernel.sum η := begin ext a s hs, simp only [coe_fn_add, pi.add_apply, sum_apply, measure.sum_apply _ hs, pi.add_apply, measure.coe_add, tsum_add ennreal.summable ennreal.summable], end end sum section s_finite /-- A kernel is s-finite if it can be written as the sum of countably many finite kernels. -/ class _root_.probability_theory.is_s_finite_kernel (κ : kernel α β) : Prop := (tsum_finite : ∃ κs : ℕ → kernel α β, (∀ n, is_finite_kernel (κs n)) ∧ κ = kernel.sum κs) @[priority 100] instance is_finite_kernel.is_s_finite_kernel [h : is_finite_kernel κ] : is_s_finite_kernel κ := ⟨⟨λ n, if n = 0 then κ else 0, λ n, by { split_ifs, exact h, apply_instance, }, begin ext a s hs, rw kernel.sum_apply' _ _ hs, have : (λ i, ((ite (i = 0) κ 0) a) s) = λ i, ite (i = 0) (κ a s) 0, { ext1 i, split_ifs; refl, }, rw [this, tsum_ite_eq], end⟩⟩ /-- A sequence of finite kernels such that `κ = kernel.sum (seq κ)`. See `is_finite_kernel_seq` and `kernel_sum_seq`. -/ noncomputable def seq (κ : kernel α β) [h : is_s_finite_kernel κ] : ℕ → kernel α β := h.tsum_finite.some lemma kernel_sum_seq (κ : kernel α β) [h : is_s_finite_kernel κ] : kernel.sum (seq κ) = κ := h.tsum_finite.some_spec.2.symm lemma measure_sum_seq (κ : kernel α β) [h : is_s_finite_kernel κ] (a : α) : measure.sum (λ n, seq κ n a) = κ a := by rw [← kernel.sum_apply, kernel_sum_seq κ] instance is_finite_kernel_seq (κ : kernel α β) [h : is_s_finite_kernel κ] (n : ℕ) : is_finite_kernel (kernel.seq κ n) := h.tsum_finite.some_spec.1 n instance is_s_finite_kernel.add (κ η : kernel α β) [is_s_finite_kernel κ] [is_s_finite_kernel η] : is_s_finite_kernel (κ + η) := begin refine ⟨⟨λ n, seq κ n + seq η n, λ n, infer_instance, _⟩⟩, rw [sum_add, kernel_sum_seq κ, kernel_sum_seq η], end lemma is_s_finite_kernel.finset_sum {κs : ι → kernel α β} (I : finset ι) (h : ∀ i ∈ I, is_s_finite_kernel (κs i)) : is_s_finite_kernel (∑ i in I, κs i) := begin classical, unfreezingI { induction I using finset.induction with i I hi_nmem_I h_ind h, { rw [finset.sum_empty], apply_instance, }, { rw finset.sum_insert hi_nmem_I, haveI : is_s_finite_kernel (κs i) := h i (finset.mem_insert_self _ _), haveI : is_s_finite_kernel (∑ (x : ι) in I, κs x), from h_ind (λ i hiI, h i (finset.mem_insert_of_mem hiI)), exact is_s_finite_kernel.add _ _, }, }, end lemma is_s_finite_kernel_sum_of_denumerable [denumerable ι] {κs : ι → kernel α β} (hκs : ∀ n, is_s_finite_kernel (κs n)) : is_s_finite_kernel (kernel.sum κs) := begin let e : ℕ ≃ (ι × ℕ) := denumerable.equiv₂ ℕ (ι × ℕ), refine ⟨⟨λ n, seq (κs (e n).1) (e n).2, infer_instance, _⟩⟩, have hκ_eq : kernel.sum κs = kernel.sum (λ n, kernel.sum (seq (κs n))), { simp_rw kernel_sum_seq, }, ext a s hs : 2, rw hκ_eq, simp_rw kernel.sum_apply' _ _ hs, change ∑' i m, seq (κs i) m a s = ∑' n, (λ im : ι × ℕ, seq (κs im.fst) im.snd a s) (e n), rw e.tsum_eq, { rw tsum_prod' ennreal.summable (λ _, ennreal.summable), }, { apply_instance, }, end lemma is_s_finite_kernel_sum [countable ι] {κs : ι → kernel α β} (hκs : ∀ n, is_s_finite_kernel (κs n)) : is_s_finite_kernel (kernel.sum κs) := begin casesI fintype_or_infinite ι, { rw sum_fintype, exact is_s_finite_kernel.finset_sum finset.univ (λ i _, hκs i), }, haveI : encodable ι := encodable.of_countable ι, haveI : denumerable ι := denumerable.of_encodable_of_infinite ι, exact is_s_finite_kernel_sum_of_denumerable hκs, end end s_finite section deterministic /-- Kernel which to `a` associates the dirac measure at `f a`. This is a Markov kernel. -/ noncomputable def deterministic (f : α → β) (hf : measurable f) : kernel α β := { val := λ a, measure.dirac (f a), property := begin refine measure.measurable_of_measurable_coe _ (λ s hs, _), simp_rw measure.dirac_apply' _ hs, exact measurable_one.indicator (hf hs), end, } lemma deterministic_apply {f : α → β} (hf : measurable f) (a : α) : deterministic f hf a = measure.dirac (f a) := rfl lemma deterministic_apply' {f : α → β} (hf : measurable f) (a : α) {s : set β} (hs : measurable_set s) : deterministic f hf a s = s.indicator (λ _, 1) (f a) := begin rw [deterministic], change measure.dirac (f a) s = s.indicator 1 (f a), simp_rw measure.dirac_apply' _ hs, end instance is_markov_kernel_deterministic {f : α → β} (hf : measurable f) : is_markov_kernel (deterministic f hf) := ⟨λ a, by { rw deterministic_apply hf, apply_instance, }⟩ lemma lintegral_deterministic' {f : β → ℝ≥0∞} {g : α → β} {a : α} (hg : measurable g) (hf : measurable f) : ∫⁻ x, f x ∂(kernel.deterministic g hg a) = f (g a) := by rw [kernel.deterministic_apply, lintegral_dirac' _ hf] @[simp] lemma lintegral_deterministic {f : β → ℝ≥0∞} {g : α → β} {a : α} (hg : measurable g) [measurable_singleton_class β] : ∫⁻ x, f x ∂(kernel.deterministic g hg a) = f (g a) := by rw [kernel.deterministic_apply, lintegral_dirac (g a) f] lemma set_lintegral_deterministic' {f : β → ℝ≥0∞} {g : α → β} {a : α} (hg : measurable g) (hf : measurable f) {s : set β} (hs : measurable_set s) [decidable (g a ∈ s)] : ∫⁻ x in s, f x ∂(kernel.deterministic g hg a) = if g a ∈ s then f (g a) else 0 := by rw [kernel.deterministic_apply, set_lintegral_dirac' hf hs] @[simp] lemma set_lintegral_deterministic {f : β → ℝ≥0∞} {g : α → β} {a : α} (hg : measurable g) [measurable_singleton_class β] (s : set β) [decidable (g a ∈ s)] : ∫⁻ x in s, f x ∂(kernel.deterministic g hg a) = if g a ∈ s then f (g a) else 0 := by rw [kernel.deterministic_apply, set_lintegral_dirac f s] lemma integral_deterministic' {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {g : α → β} {a : α} (hg : measurable g) (hf : strongly_measurable f) : ∫ x, f x ∂(kernel.deterministic g hg a) = f (g a) := by rw [kernel.deterministic_apply, integral_dirac' _ _ hf] @[simp] lemma integral_deterministic {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {g : α → β} {a : α} (hg : measurable g) [measurable_singleton_class β] : ∫ x, f x ∂(kernel.deterministic g hg a) = f (g a) := by rw [kernel.deterministic_apply, integral_dirac _ (g a)] lemma set_integral_deterministic' {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {g : α → β} {a : α} (hg : measurable g) (hf : strongly_measurable f) {s : set β} (hs : measurable_set s) [decidable (g a ∈ s)] : ∫ x in s, f x ∂(kernel.deterministic g hg a) = if g a ∈ s then f (g a) else 0 := by rw [kernel.deterministic_apply, set_integral_dirac' hf _ hs] @[simp] lemma set_integral_deterministic {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {g : α → β} {a : α} (hg : measurable g) [measurable_singleton_class β] (s : set β) [decidable (g a ∈ s)] : ∫ x in s, f x ∂(kernel.deterministic g hg a) = if g a ∈ s then f (g a) else 0 := by rw [kernel.deterministic_apply, set_integral_dirac f _ s] end deterministic section const omit mα mβ /-- Constant kernel, which always returns the same measure. -/ def const (α : Type*) {β : Type*} [measurable_space α] {mβ : measurable_space β} (μβ : measure β) : kernel α β := { val := λ _, μβ, property := measure.measurable_of_measurable_coe _ (λ s hs, measurable_const), } include mα mβ lemma const_apply (μβ : measure β) (a : α) : const α μβ a = μβ := rfl instance is_finite_kernel_const {μβ : measure β} [hμβ : is_finite_measure μβ] : is_finite_kernel (const α μβ) := ⟨⟨μβ set.univ, measure_lt_top _ _, λ a, le_rfl⟩⟩ instance is_markov_kernel_const {μβ : measure β} [hμβ : is_probability_measure μβ] : is_markov_kernel (const α μβ) := ⟨λ a, hμβ⟩ @[simp] lemma lintegral_const {f : β → ℝ≥0∞} {μ : measure β} {a : α} : ∫⁻ x, f x ∂(kernel.const α μ a) = ∫⁻ x, f x ∂μ := by rw kernel.const_apply @[simp] lemma set_lintegral_const {f : β → ℝ≥0∞} {μ : measure β} {a : α} {s : set β} : ∫⁻ x in s, f x ∂(kernel.const α μ a) = ∫⁻ x in s, f x ∂μ := by rw kernel.const_apply @[simp] lemma integral_const {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {μ : measure β} {a : α} : ∫ x, f x ∂(kernel.const α μ a) = ∫ x, f x ∂μ := by rw kernel.const_apply @[simp] lemma set_integral_const {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {μ : measure β} {a : α} {s : set β} : ∫ x in s, f x ∂(kernel.const α μ a) = ∫ x in s, f x ∂μ := by rw kernel.const_apply end const omit mα /-- In a countable space with measurable singletons, every function `α → measure β` defines a kernel. -/ def of_fun_of_countable [measurable_space α] {mβ : measurable_space β} [countable α] [measurable_singleton_class α] (f : α → measure β) : kernel α β := { val := f, property := measurable_of_countable f } include mα section restrict variables {s t : set β} /-- Kernel given by the restriction of the measures in the image of a kernel to a set. -/ protected noncomputable def restrict (κ : kernel α β) (hs : measurable_set s) : kernel α β := { val := λ a, (κ a).restrict s, property := begin refine measure.measurable_of_measurable_coe _ (λ t ht, _), simp_rw measure.restrict_apply ht, exact kernel.measurable_coe κ (ht.inter hs), end, } lemma restrict_apply (κ : kernel α β) (hs : measurable_set s) (a : α) : kernel.restrict κ hs a = (κ a).restrict s := rfl lemma restrict_apply' (κ : kernel α β) (hs : measurable_set s) (a : α) (ht : measurable_set t) : kernel.restrict κ hs a t = (κ a) (t ∩ s) := by rw [restrict_apply κ hs a, measure.restrict_apply ht] @[simp] lemma restrict_univ : kernel.restrict κ measurable_set.univ = κ := by { ext1 a, rw [kernel.restrict_apply, measure.restrict_univ], } @[simp] lemma lintegral_restrict (κ : kernel α β) (hs : measurable_set s) (a : α) (f : β → ℝ≥0∞) : ∫⁻ b, f b ∂(kernel.restrict κ hs a) = ∫⁻ b in s, f b ∂(κ a) := by rw restrict_apply @[simp] lemma set_lintegral_restrict (κ : kernel α β) (hs : measurable_set s) (a : α) (f : β → ℝ≥0∞) (t : set β) : ∫⁻ b in t, f b ∂(kernel.restrict κ hs a) = ∫⁻ b in (t ∩ s), f b ∂(κ a) := by rw [restrict_apply, measure.restrict_restrict' hs] @[simp] lemma set_integral_restrict {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] {f : β → E} {a : α} (hs : measurable_set s) (t : set β) : ∫ x in t, f x ∂(kernel.restrict κ hs a) = ∫ x in (t ∩ s), f x ∂(κ a) := by rw [restrict_apply, measure.restrict_restrict' hs] instance is_finite_kernel.restrict (κ : kernel α β) [is_finite_kernel κ] (hs : measurable_set s) : is_finite_kernel (kernel.restrict κ hs) := begin refine ⟨⟨is_finite_kernel.bound κ, is_finite_kernel.bound_lt_top κ, λ a, _⟩⟩, rw restrict_apply' κ hs a measurable_set.univ, exact measure_le_bound κ a _, end instance is_s_finite_kernel.restrict (κ : kernel α β) [is_s_finite_kernel κ] (hs : measurable_set s) : is_s_finite_kernel (kernel.restrict κ hs) := begin refine ⟨⟨λ n, kernel.restrict (seq κ n) hs, infer_instance, _⟩⟩, ext1 a, simp_rw [sum_apply, restrict_apply, ← measure.restrict_sum _ hs, ← sum_apply, kernel_sum_seq], end end restrict section comap_right variables {γ : Type*} {mγ : measurable_space γ} {f : γ → β} include mγ /-- Kernel with value `(κ a).comap f`, for a measurable embedding `f`. That is, for a measurable set `t : set β`, `comap_right κ hf a t = κ a (f '' t)`. -/ noncomputable def comap_right (κ : kernel α β) (hf : measurable_embedding f) : kernel α γ := { val := λ a, (κ a).comap f, property := begin refine measure.measurable_measure.mpr (λ t ht, _), have : (λ a, measure.comap f (κ a) t) = λ a, κ a (f '' t), { ext1 a, rw measure.comap_apply _ hf.injective (λ s' hs', _) _ ht, exact hf.measurable_set_image.mpr hs', }, rw this, exact kernel.measurable_coe _ (hf.measurable_set_image.mpr ht), end } lemma comap_right_apply (κ : kernel α β) (hf : measurable_embedding f) (a : α) : comap_right κ hf a = measure.comap f (κ a) := rfl lemma comap_right_apply' (κ : kernel α β) (hf : measurable_embedding f) (a : α) {t : set γ} (ht : measurable_set t) : comap_right κ hf a t = κ a (f '' t) := by rw [comap_right_apply, measure.comap_apply _ hf.injective (λ s, hf.measurable_set_image.mpr) _ ht] lemma is_markov_kernel.comap_right (κ : kernel α β) (hf : measurable_embedding f) (hκ : ∀ a, κ a (set.range f) = 1) : is_markov_kernel (comap_right κ hf) := begin refine ⟨λ a, ⟨_⟩⟩, rw comap_right_apply' κ hf a measurable_set.univ, simp only [set.image_univ, subtype.range_coe_subtype, set.set_of_mem_eq], exact hκ a, end instance is_finite_kernel.comap_right (κ : kernel α β) [is_finite_kernel κ] (hf : measurable_embedding f) : is_finite_kernel (comap_right κ hf) := begin refine ⟨⟨is_finite_kernel.bound κ, is_finite_kernel.bound_lt_top κ, λ a, _⟩⟩, rw comap_right_apply' κ hf a measurable_set.univ, exact measure_le_bound κ a _, end instance is_s_finite_kernel.comap_right (κ : kernel α β) [is_s_finite_kernel κ] (hf : measurable_embedding f) : is_s_finite_kernel (comap_right κ hf) := begin refine ⟨⟨λ n, comap_right (seq κ n) hf, infer_instance, _⟩⟩, ext1 a, rw sum_apply, simp_rw comap_right_apply _ hf, have : measure.sum (λ n, measure.comap f (seq κ n a)) = measure.comap f (measure.sum (λ n, seq κ n a)), { ext1 t ht, rw [measure.comap_apply _ hf.injective (λ s', hf.measurable_set_image.mpr) _ ht, measure.sum_apply _ ht, measure.sum_apply _ (hf.measurable_set_image.mpr ht)], congr' with n : 1, rw measure.comap_apply _ hf.injective (λ s', hf.measurable_set_image.mpr) _ ht, }, rw [this, measure_sum_seq], end end comap_right section piecewise variables {η : kernel α β} {s : set α} {hs : measurable_set s} [decidable_pred (∈ s)] /-- `piecewise hs κ η` is the kernel equal to `κ` on the measurable set `s` and to `η` on its complement. -/ def piecewise (hs : measurable_set s) (κ η : kernel α β) : kernel α β := { val := λ a, if a ∈ s then κ a else η a, property := measurable.piecewise hs (kernel.measurable _) (kernel.measurable _) } lemma piecewise_apply (a : α) : piecewise hs κ η a = if a ∈ s then κ a else η a := rfl lemma piecewise_apply' (a : α) (t : set β) : piecewise hs κ η a t = if a ∈ s then κ a t else η a t := by { rw piecewise_apply, split_ifs; refl, } instance is_markov_kernel.piecewise [is_markov_kernel κ] [is_markov_kernel η] : is_markov_kernel (piecewise hs κ η) := by { refine ⟨λ a, ⟨_⟩⟩, rw [piecewise_apply', measure_univ, measure_univ, if_t_t], } instance is_finite_kernel.piecewise [is_finite_kernel κ] [is_finite_kernel η] : is_finite_kernel (piecewise hs κ η) := begin refine ⟨⟨max (is_finite_kernel.bound κ) (is_finite_kernel.bound η), _, λ a, _⟩⟩, { exact max_lt (is_finite_kernel.bound_lt_top κ) (is_finite_kernel.bound_lt_top η), }, rw [piecewise_apply'], exact (ite_le_sup _ _ _).trans (sup_le_sup (measure_le_bound _ _ _) (measure_le_bound _ _ _)), end instance is_s_finite_kernel.piecewise [is_s_finite_kernel κ] [is_s_finite_kernel η] : is_s_finite_kernel (piecewise hs κ η) := begin refine ⟨⟨λ n, piecewise hs (seq κ n) (seq η n), infer_instance, _⟩⟩, ext1 a, simp_rw [sum_apply, kernel.piecewise_apply], split_ifs; exact (measure_sum_seq _ a).symm, end lemma lintegral_piecewise (a : α) (g : β → ℝ≥0∞) : ∫⁻ b, g b ∂(piecewise hs κ η a) = if a ∈ s then ∫⁻ b, g b ∂(κ a) else ∫⁻ b, g b ∂(η a) := by { simp_rw piecewise_apply, split_ifs; refl, } lemma set_lintegral_piecewise (a : α) (g : β → ℝ≥0∞) (t : set β) : ∫⁻ b in t, g b ∂(piecewise hs κ η a) = if a ∈ s then ∫⁻ b in t, g b ∂(κ a) else ∫⁻ b in t, g b ∂(η a) := by { simp_rw piecewise_apply, split_ifs; refl, } lemma integral_piecewise {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] (a : α) (g : β → E) : ∫ b, g b ∂(piecewise hs κ η a) = if a ∈ s then ∫ b, g b ∂(κ a) else ∫ b, g b ∂(η a) := by { simp_rw piecewise_apply, split_ifs; refl, } lemma set_integral_piecewise {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [complete_space E] (a : α) (g : β → E) (t : set β) : ∫ b in t, g b ∂(piecewise hs κ η a) = if a ∈ s then ∫ b in t, g b ∂(κ a) else ∫ b in t, g b ∂(η a) := by { simp_rw piecewise_apply, split_ifs; refl, } end piecewise end kernel end probability_theory
f110dc892dd4fd04f7b6147fda46a9901dbbfbfc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/ideal/over.lean
457edaa29fcdbf54d6b6b4b666c946aff8e859d2
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
8,994
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Anne Baanen -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.algebraic import Mathlib.ring_theory.localization import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Ideals over/under ideals This file concerns ideals lying over other ideals. Let `f : R →+* S` be a ring homomorphism (typically a ring extension), `I` an ideal of `R` and `J` an ideal of `S`. We say `J` lies over `I` (and `I` under `J`) if `I` is the `f`-preimage of `J`. This is expressed here by writing `I = J.comap f`. ## Implementation notes The proofs of the `comap_ne_bot` and `comap_lt_comap` families use an approach specific for their situation: we construct an element in `I.comap f` from the coefficients of a minimal polynomial. Once mathlib has more material on the localization at a prime ideal, the results can be proven using more general going-up/going-down theory. -/ namespace ideal theorem coeff_zero_mem_comap_of_root_mem_of_eval_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] {f : R →+* S} {I : ideal S} {r : S} (hr : r ∈ I) {p : polynomial R} (hp : polynomial.eval₂ f r p ∈ I) : polynomial.coeff p 0 ∈ comap f I := sorry theorem coeff_zero_mem_comap_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] {f : R →+* S} {I : ideal S} {r : S} (hr : r ∈ I) {p : polynomial R} (hp : polynomial.eval₂ f r p = 0) : polynomial.coeff p 0 ∈ comap f I := coeff_zero_mem_comap_of_root_mem_of_eval_mem hr (Eq.symm hp ▸ ideal.zero_mem I) theorem exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] {f : R →+* S} {I : ideal S} {r : S} (r_non_zero_divisor : ∀ {x : S}, x * r = 0 → x = 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) : ∃ (i : ℕ), polynomial.coeff p i ≠ 0 ∧ polynomial.coeff p i ∈ comap f I := sorry theorem exists_coeff_ne_zero_mem_comap_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {f : R →+* S} {I : ideal S} {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) : ∃ (i : ℕ), polynomial.coeff p i ≠ 0 ∧ polynomial.coeff p i ∈ comap f I := exists_coeff_ne_zero_mem_comap_of_non_zero_divisor_root_mem (fun (_x : S) (h : _x * r = 0) => or.resolve_right (iff.mp mul_eq_zero h) r_ne_zero) hr theorem exists_coeff_mem_comap_sdiff_comap_of_root_mem_sdiff {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {f : R →+* S} {I : ideal S} {J : ideal S} [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ ↑J \ ↑I) {p : polynomial R} (p_ne_zero : polynomial.map (quotient.mk (comap f I)) p ≠ 0) (hpI : polynomial.eval₂ f r p ∈ I) : ∃ (i : ℕ), polynomial.coeff p i ∈ ↑(comap f J) \ ↑(comap f I) := sorry theorem comap_ne_bot_of_root_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {f : R →+* S} {I : ideal S} {r : S} (r_ne_zero : r ≠ 0) (hr : r ∈ I) {p : polynomial R} (p_ne_zero : p ≠ 0) (hp : polynomial.eval₂ f r p = 0) : comap f I ≠ ⊥ := sorry theorem comap_lt_comap_of_root_mem_sdiff {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {f : R →+* S} {I : ideal S} {J : ideal S} [is_prime I] (hIJ : I ≤ J) {r : S} (hr : r ∈ ↑J \ ↑I) {p : polynomial R} (p_ne_zero : polynomial.map (quotient.mk (comap f I)) p ≠ 0) (hp : polynomial.eval₂ f r p ∈ I) : comap f I < comap f J := sorry theorem comap_ne_bot_of_algebraic_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {I : ideal S} [algebra R S] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_algebraic R x) : comap (algebra_map R S) I ≠ ⊥ := sorry theorem comap_ne_bot_of_integral_mem {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {I : ideal S} [algebra R S] [nontrivial R] {x : S} (x_ne_zero : x ≠ 0) (x_mem : x ∈ I) (hx : is_integral R x) : comap (algebra_map R S) I ≠ ⊥ := comap_ne_bot_of_algebraic_mem x_ne_zero x_mem (is_integral.is_algebraic R hx) theorem eq_bot_of_comap_eq_bot {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {I : ideal S} [algebra R S] [nontrivial R] (hRS : algebra.is_integral R S) (hI : comap (algebra_map R S) I = ⊥) : I = ⊥ := sorry theorem mem_of_one_mem {S : Type u_2} [integral_domain S] {I : ideal S} (h : 1 ∈ I) (x : S) : x ∈ I := Eq.symm (iff.mpr (eq_top_iff_one I) h) ▸ submodule.mem_top theorem comap_lt_comap_of_integral_mem_sdiff {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] {I : ideal S} {J : ideal S} [algebra R S] [hI : is_prime I] (hIJ : I ≤ J) {x : S} (mem : x ∈ ↑J \ ↑I) (integral : is_integral R x) : comap (algebra_map R S) I < comap (algebra_map R S) J := sorry theorem is_maximal_of_is_integral_of_is_maximal_comap {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [is_prime I] (hI : is_maximal (comap (algebra_map R S) I)) : is_maximal I := sorry theorem is_maximal_of_is_integral_of_is_maximal_comap' {R : Type u_1} {S : Type u_2} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : ring_hom.is_integral f) (I : ideal S) [hI' : is_prime I] (hI : is_maximal (comap f I)) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap hf I hI theorem is_maximal_comap_of_is_integral_of_is_maximal {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (hRS : algebra.is_integral R S) (I : ideal S) [hI : is_maximal I] : is_maximal (comap (algebra_map R S) I) := sorry theorem is_maximal_comap_of_is_integral_of_is_maximal' {R : Type u_1} {S : Type u_2} [comm_ring R] [integral_domain S] (f : R →+* S) (hf : ring_hom.is_integral f) (I : ideal S) (hI : is_maximal I) : is_maximal (comap f I) := is_maximal_comap_of_is_integral_of_is_maximal hf I theorem integral_closure.comap_ne_bot {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] [nontrivial R] {I : ideal ↥(integral_closure R S)} (I_ne_bot : I ≠ ⊥) : comap (algebra_map R ↥(integral_closure R S)) I ≠ ⊥ := sorry theorem integral_closure.eq_bot_of_comap_eq_bot {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] [nontrivial R] {I : ideal ↥(integral_closure R S)} : comap (algebra_map R ↥(integral_closure R S)) I = ⊥ → I = ⊥ := imp_of_not_imp_not (comap (algebra_map R ↥(integral_closure R S)) I = ⊥) (I = ⊥) integral_closure.comap_ne_bot theorem integral_closure.comap_lt_comap {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] {I : ideal ↥(integral_closure R S)} {J : ideal ↥(integral_closure R S)} [is_prime I] (I_lt_J : I < J) : comap (algebra_map R ↥(integral_closure R S)) I < comap (algebra_map R ↥(integral_closure R S)) J := sorry theorem integral_closure.is_maximal_of_is_maximal_comap {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (I : ideal ↥(integral_closure R S)) [is_prime I] (hI : is_maximal (comap (algebra_map R ↥(integral_closure R S)) I)) : is_maximal I := is_maximal_of_is_integral_of_is_maximal_comap (fun (x : ↥(integral_closure R S)) => integral_closure.is_integral x) I hI /-- `comap (algebra_map R S)` is a surjection from the prime spec of `R` to prime spec of `S`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ theorem exists_ideal_over_prime_of_is_integral' {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (hP : ring_hom.ker (algebra_map R S) ≤ P) : ∃ (Q : ideal S), is_prime Q ∧ comap (algebra_map R S) Q = P := sorry /-- More general going-up theorem than `exists_ideal_over_prime_of_is_integral'`. TODO: Version of going-up theorem with arbitrary length chains (by induction on this)? Not sure how best to write an ascending chain in Lean -/ theorem exists_ideal_over_prime_of_is_integral {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R) [is_prime P] (I : ideal S) [is_prime I] (hIP : comap (algebra_map R S) I ≤ P) : ∃ (Q : ideal S), ∃ (H : Q ≥ I), is_prime Q ∧ comap (algebra_map R S) Q = P := sorry /-- `comap (algebra_map R S)` is a surjection from the max spec of `S` to max spec of `R`. `hP : (algebra_map R S).ker ≤ P` is a slight generalization of the extension being injective -/ theorem exists_ideal_over_maximal_of_is_integral {R : Type u_1} [comm_ring R] {S : Type u_2} [integral_domain S] [algebra R S] (H : algebra.is_integral R S) (P : ideal R) [P_max : is_maximal P] (hP : ring_hom.ker (algebra_map R S) ≤ P) : ∃ (Q : ideal S), is_maximal Q ∧ comap (algebra_map R S) Q = P := sorry
90fc8547e60f0265b55e00c0ec490f8a95042831
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/field_theory/is_alg_closed/algebraic_closure.lean
5aa7ca14f72f62f4b35a4c5605a02ade06b29b0c
[ "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
11,018
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.direct_limit import algebra.char_p.algebra import field_theory.is_alg_closed.basic import field_theory.splitting_field.construction /-! # Algebraic Closure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we construct the algebraic closure of a field ## Main Definitions - `algebraic_closure k` is an algebraic closure of `k` (in the same universe). It is constructed by taking the polynomial ring generated by indeterminates `x_f` corresponding to monic irreducible polynomials `f` with coefficients in `k`, and quotienting out by a maximal ideal containing every `f(x_f)`, and then repeating this step countably many times. See Exercise 1.13 in Atiyah--Macdonald. ## Tags algebraic closure, algebraically closed -/ universes u v w noncomputable theory open_locale classical big_operators polynomial open polynomial variables (k : Type u) [field k] namespace algebraic_closure open mv_polynomial /-- The subtype of monic irreducible polynomials -/ @[reducible] def monic_irreducible : Type u := { f : k[X] // monic f ∧ irreducible f } /-- Sends a monic irreducible polynomial `f` to `f(x_f)` where `x_f` is a formal indeterminate. -/ def eval_X_self (f : monic_irreducible k) : mv_polynomial (monic_irreducible k) k := polynomial.eval₂ mv_polynomial.C (X f) f /-- The span of `f(x_f)` across monic irreducible polynomials `f` where `x_f` is an indeterminate. -/ def span_eval : ideal (mv_polynomial (monic_irreducible k) k) := ideal.span $ set.range $ eval_X_self k /-- Given a finset of monic irreducible polynomials, construct an algebra homomorphism to the splitting field of the product of the polynomials sending each indeterminate `x_f` represented by the polynomial `f` in the finset to a root of `f`. -/ def to_splitting_field (s : finset (monic_irreducible k)) : mv_polynomial (monic_irreducible k) k →ₐ[k] splitting_field (∏ x in s, x : k[X]) := mv_polynomial.aeval $ λ f, if hf : f ∈ s then root_of_splits _ ((splits_prod_iff _ $ λ (j : monic_irreducible k) _, j.2.2.ne_zero).1 (splitting_field.splits _) f hf) (mt is_unit_iff_degree_eq_zero.2 f.2.2.not_unit) else 37 theorem to_splitting_field_eval_X_self {s : finset (monic_irreducible k)} {f} (hf : f ∈ s) : to_splitting_field k s (eval_X_self k f) = 0 := by { rw [to_splitting_field, eval_X_self, ← alg_hom.coe_to_ring_hom, hom_eval₂, alg_hom.coe_to_ring_hom, mv_polynomial.aeval_X, dif_pos hf, ← algebra_map_eq, alg_hom.comp_algebra_map], exact map_root_of_splits _ _ _ } theorem span_eval_ne_top : span_eval k ≠ ⊤ := begin rw [ideal.ne_top_iff_one, span_eval, ideal.span, ← set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨v, _, hv⟩, replace hv := congr_arg (to_splitting_field k v.support) hv, rw [alg_hom.map_one, finsupp.total_apply, finsupp.sum, alg_hom.map_sum, finset.sum_eq_zero] at hv, { exact zero_ne_one hv }, intros j hj, rw [smul_eq_mul, alg_hom.map_mul, to_splitting_field_eval_X_self k hj, mul_zero] end /-- A random maximal ideal that contains `span_eval k` -/ def max_ideal : ideal (mv_polynomial (monic_irreducible k) k) := classical.some $ ideal.exists_le_maximal _ $ span_eval_ne_top k instance max_ideal.is_maximal : (max_ideal k).is_maximal := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).1 theorem le_max_ideal : span_eval k ≤ max_ideal k := (classical.some_spec $ ideal.exists_le_maximal _ $ span_eval_ne_top k).2 /-- The first step of constructing `algebraic_closure`: adjoin a root of all monic polynomials -/ def adjoin_monic : Type u := mv_polynomial (monic_irreducible k) k ⧸ max_ideal k instance adjoin_monic.field : field (adjoin_monic k) := ideal.quotient.field _ instance adjoin_monic.inhabited : inhabited (adjoin_monic k) := ⟨37⟩ /-- The canonical ring homomorphism to `adjoin_monic k`. -/ def to_adjoin_monic : k →+* adjoin_monic k := (ideal.quotient.mk _).comp C instance adjoin_monic.algebra : algebra k (adjoin_monic k) := (to_adjoin_monic k).to_algebra theorem adjoin_monic.algebra_map : algebra_map k (adjoin_monic k) = (ideal.quotient.mk _).comp C := rfl theorem adjoin_monic.is_integral (z : adjoin_monic k) : is_integral k z := let ⟨p, hp⟩ := ideal.quotient.mk_surjective z in hp ▸ mv_polynomial.induction_on p (λ x, is_integral_algebra_map) (λ p q, is_integral_add) (λ p f ih, @is_integral_mul _ _ _ _ _ _ (ideal.quotient.mk _ _) ih ⟨f, f.2.1, by { erw [adjoin_monic.algebra_map, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span ⟨f, rfl⟩) }⟩) theorem adjoin_monic.exists_root {f : k[X]} (hfm : f.monic) (hfi : irreducible f) : ∃ x : adjoin_monic k, f.eval₂ (to_adjoin_monic k) x = 0 := ⟨ideal.quotient.mk _ $ X (⟨f, hfm, hfi⟩ : monic_irreducible k), by { rw [to_adjoin_monic, ← hom_eval₂, ideal.quotient.eq_zero_iff_mem], exact le_max_ideal k (ideal.subset_span $ ⟨_, rfl⟩) }⟩ /-- The `n`th step of constructing `algebraic_closure`, together with its `field` instance. -/ def step_aux (n : ℕ) : Σ α : Type u, field α := nat.rec_on n ⟨k, infer_instance⟩ $ λ n ih, ⟨@adjoin_monic ih.1 ih.2, @adjoin_monic.field ih.1 ih.2⟩ /-- The `n`th step of constructing `algebraic_closure`. -/ def step (n : ℕ) : Type u := (step_aux k n).1 instance step.field (n : ℕ) : field (step k n) := (step_aux k n).2 instance step.inhabited (n) : inhabited (step k n) := ⟨37⟩ /-- The canonical inclusion to the `0`th step. -/ def to_step_zero : k →+* step k 0 := ring_hom.id k /-- The canonical ring homomorphism to the next step. -/ def to_step_succ (n : ℕ) : step k n →+* step k (n + 1) := @to_adjoin_monic (step k n) (step.field k n) instance step.algebra_succ (n) : algebra (step k n) (step k (n + 1)) := (to_step_succ k n).to_algebra theorem to_step_succ.exists_root {n} {f : polynomial (step k n)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : step k (n + 1), f.eval₂ (to_step_succ k n) x = 0 := @adjoin_monic.exists_root _ (step.field k n) _ hfm hfi /-- The canonical ring homomorphism to a step with a greater index. -/ def to_step_of_le (m n : ℕ) (h : m ≤ n) : step k m →+* step k n := { to_fun := nat.le_rec_on h (λ n, to_step_succ k n), map_one' := begin induction h with n h ih, { exact nat.le_rec_on_self 1 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_one] end, map_mul' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_mul] end, map_zero' := begin induction h with n h ih, { exact nat.le_rec_on_self 0 }, rw [nat.le_rec_on_succ h, ih, ring_hom.map_zero] end, map_add' := λ x y, begin induction h with n h ih, { simp_rw nat.le_rec_on_self }, simp_rw [nat.le_rec_on_succ h, ih, ring_hom.map_add] end } @[simp] lemma coe_to_step_of_le (m n : ℕ) (h : m ≤ n) : (to_step_of_le k m n h : step k m → step k n) = nat.le_rec_on h (λ n, to_step_succ k n) := rfl instance step.algebra (n) : algebra k (step k n) := (to_step_of_le k 0 n n.zero_le).to_algebra instance step.scalar_tower (n) : is_scalar_tower k (step k n) (step k (n + 1)) := is_scalar_tower.of_algebra_map_eq $ λ z, @nat.le_rec_on_succ (step k) 0 n n.zero_le (n + 1).zero_le (λ n, to_step_succ k n) z theorem step.is_integral (n) : ∀ z : step k n, is_integral k z := nat.rec_on n (λ z, is_integral_algebra_map) $ λ n ih z, is_integral_trans ih _ (adjoin_monic.is_integral (step k n) z : _) instance to_step_of_le.directed_system : directed_system (step k) (λ i j h, to_step_of_le k i j h) := ⟨λ i x h, nat.le_rec_on_self x, λ i₁ i₂ i₃ h₁₂ h₂₃ x, (nat.le_rec_on_trans h₁₂ h₂₃ x).symm⟩ end algebraic_closure /-- The canonical algebraic closure of a field, the direct limit of adding roots to the field for each polynomial over the field. -/ def algebraic_closure : Type u := ring.direct_limit (algebraic_closure.step k) (λ i j h, algebraic_closure.to_step_of_le k i j h) namespace algebraic_closure instance : field (algebraic_closure k) := field.direct_limit.field _ _ instance : inhabited (algebraic_closure k) := ⟨37⟩ /-- The canonical ring embedding from the `n`th step to the algebraic closure. -/ def of_step (n : ℕ) : step k n →+* algebraic_closure k := ring.direct_limit.of _ _ _ instance algebra_of_step (n) : algebra (step k n) (algebraic_closure k) := (of_step k n).to_algebra theorem of_step_succ (n : ℕ) : (of_step k (n + 1)).comp (to_step_succ k n) = of_step k n := ring_hom.ext $ λ x, show ring.direct_limit.of (step k) (λ i j h, to_step_of_le k i j h) _ _ = _, by { convert ring.direct_limit.of_f n.le_succ x, ext x, exact (nat.le_rec_on_succ' x).symm } theorem exists_of_step (z : algebraic_closure k) : ∃ n x, of_step k n x = z := ring.direct_limit.exists_of z -- slow theorem exists_root {f : polynomial (algebraic_closure k)} (hfm : f.monic) (hfi : irreducible f) : ∃ x : algebraic_closure k, f.eval x = 0 := begin have : ∃ n p, polynomial.map (of_step k n) p = f, { convert ring.direct_limit.polynomial.exists_of f }, unfreezingI { obtain ⟨n, p, rfl⟩ := this }, rw monic_map_iff at hfm, have := hfm.irreducible_of_irreducible_map (of_step k n) p hfi, obtain ⟨x, hx⟩ := to_step_succ.exists_root k hfm this, refine ⟨of_step k (n + 1) x, _⟩, rw [← of_step_succ k n, eval_map, ← hom_eval₂, hx, ring_hom.map_zero] end instance : is_alg_closed (algebraic_closure k) := is_alg_closed.of_exists_root _ $ λ f, exists_root k instance {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra R (algebraic_closure k) := ((of_step k 0).comp (@algebra_map _ _ _ _ alg)).to_algebra lemma algebra_map_def {R : Type*} [comm_semiring R] [alg : algebra R k] : algebra_map R (algebraic_closure k) = ((of_step k 0 : k →+* _).comp (@algebra_map _ _ _ _ alg)) := rfl instance {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S] [algebra S k] [algebra R k] [is_scalar_tower R S k] : is_scalar_tower R S (algebraic_closure k) := is_scalar_tower.of_algebra_map_eq (λ x, ring_hom.congr_arg _ (is_scalar_tower.algebra_map_apply R S k x : _)) /-- Canonical algebra embedding from the `n`th step to the algebraic closure. -/ def of_step_hom (n) : step k n →ₐ[k] algebraic_closure k := { commutes' := λ x, ring.direct_limit.of_f n.zero_le x, .. of_step k n } theorem is_algebraic : algebra.is_algebraic k (algebraic_closure k) := λ z, is_algebraic_iff_is_integral.2 $ let ⟨n, x, hx⟩ := exists_of_step k z in hx ▸ map_is_integral (of_step_hom k n) (step.is_integral k n x) instance : is_alg_closure k (algebraic_closure k) := ⟨algebraic_closure.is_alg_closed k, is_algebraic k⟩ end algebraic_closure
83b11ae05ed96636c75ed5a7a60998ef6a7dbcea
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/int/modeq.lean
abe3cd79c7a75c12e5dba91e4f0269251cfb7217
[ "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
3,306
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.int.basic data.nat.modeq namespace int def modeq (n a b : ℤ) := a % n = b % n notation a ` ≡ `:50 b ` [ZMOD `:50 n `]`:0 := modeq n a b namespace modeq variables {n m a b c d : ℤ} @[refl] protected theorem refl (a : ℤ) : a ≡ a [ZMOD n] := @rfl _ _ @[symm] protected theorem symm : a ≡ b [ZMOD n] → b ≡ a [ZMOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [ZMOD n] → b ≡ c [ZMOD n] → a ≡ c [ZMOD n] := eq.trans lemma coe_nat_modeq_iff {a b n : ℕ} : a ≡ b [ZMOD n] ↔ a ≡ b [MOD n] := by unfold modeq nat.modeq; rw ← int.coe_nat_eq_coe_nat_iff; simp [int.coe_nat_mod] instance : decidable (a ≡ b [ZMOD n]) := by unfold modeq; apply_instance theorem modeq_zero_iff : a ≡ 0 [ZMOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] theorem modeq_iff_dvd : a ≡ b [ZMOD n] ↔ (n:ℤ) ∣ b - a := by rw [modeq, eq_comm]; simp [int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero] theorem modeq_of_dvd_of_modeq (d : m ∣ n) (h : a ≡ b [ZMOD n]) : a ≡ b [ZMOD m] := modeq_iff_dvd.2 $ dvd_trans d (modeq_iff_dvd.1 h) theorem modeq_mul_left' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD (c * n)] := or.cases_on (lt_or_eq_of_le hc) (λ hc, by unfold modeq; simp [mul_mod_mul_of_pos _ _ hc, (show _ = _, from h)] ) (λ hc, by simp [hc.symm]) theorem modeq_mul_right' (hc : 0 ≤ c) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact modeq_mul_left' hc h theorem modeq_add (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a + c ≡ b + d [ZMOD n] := modeq_iff_dvd.2 $ by simpa using dvd_add (modeq_iff_dvd.1 h₁) (modeq_iff_dvd.1 h₂) theorem modeq_add_cancel_left (h₁ : a ≡ b [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : c ≡ d [ZMOD n] := have (n:ℤ) ∣ a + (-a + (d + -c)), by simpa using dvd_sub (modeq_iff_dvd.1 h₂) (modeq_iff_dvd.1 h₁), modeq_iff_dvd.2 $ by rwa add_neg_cancel_left at this theorem modeq_add_cancel_right (h₁ : c ≡ d [ZMOD n]) (h₂ : a + c ≡ b + d [ZMOD n]) : a ≡ b [ZMOD n] := by rw [add_comm a, add_comm b] at h₂; exact modeq_add_cancel_left h₁ h₂ theorem modeq_neg (h : a ≡ b [ZMOD n]) : -a ≡ -b [ZMOD n] := modeq_add_cancel_left h (by simp) theorem modeq_sub (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a - c ≡ b - d [ZMOD n] := by rw [sub_eq_add_neg, sub_eq_add_neg]; exact modeq_add h₁ (modeq_neg h₂) theorem modeq_mul_left (c : ℤ) (h : a ≡ b [ZMOD n]) : c * a ≡ c * b [ZMOD n] := or.cases_on (le_total 0 c) (λ hc, modeq_of_dvd_of_modeq (dvd_mul_left _ _) (modeq_mul_left' hc h)) (λ hc, by rw [← neg_neg c, ← neg_mul_eq_neg_mul, ← neg_mul_eq_neg_mul _ b]; exact modeq_neg (modeq_of_dvd_of_modeq (dvd_mul_left _ _) (modeq_mul_left' (neg_nonneg.2 hc) h))) theorem modeq_mul_right (c : ℤ) (h : a ≡ b [ZMOD n]) : a * c ≡ b * c [ZMOD n] := by rw [mul_comm a, mul_comm b]; exact modeq_mul_left c h theorem modeq_mul (h₁ : a ≡ b [ZMOD n]) (h₂ : c ≡ d [ZMOD n]) : a * c ≡ b * d [ZMOD n] := (modeq_mul_left _ h₂).trans (modeq_mul_right _ h₁) end modeq end int
6ddd0fb4f611b110c28f6ef6e7030d8d81d422b4
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/data/nat/gcd.lean
547dd8ae1dab6e8b4736a857bd2b21823f451c2c
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
1,639
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, Mario Carneiro Definitions and properties of gcd, lcm, and coprime. -/ prelude import init.data.nat.lemmas init.meta.well_founded_tactics open well_founded namespace nat /- gcd -/ def gcd : nat → nat → nat | 0 y := y | (succ x) y := have y % succ x < succ x, from mod_lt _ $ succ_pos _, gcd (y % succ x) (succ x) @[simp] theorem gcd_zero_left (x : nat) : gcd 0 x = x := by simp [gcd] @[simp] theorem gcd_succ (x y : nat) : gcd (succ x) y = gcd (y % succ x) (succ x) := by simp [gcd] @[simp] theorem gcd_one_left (n : ℕ) : gcd 1 n = 1 := by simp [gcd] theorem gcd_def (x y : ℕ) : gcd x y = if x = 0 then y else gcd (y % x) x := by cases x; simp [gcd, succ_ne_zero] @[simp] theorem gcd_self (n : ℕ) : gcd n n = n := by cases n; simp [gcd, mod_self] @[simp] theorem gcd_zero_right (n : ℕ) : gcd n 0 = n := by cases n; simp [gcd] theorem gcd_rec (m n : ℕ) : gcd m n = gcd (n % m) m := by cases m; simp [gcd] @[elab_as_eliminator] theorem gcd.induction {P : ℕ → ℕ → Prop} (m n : ℕ) (H0 : ∀n, P 0 n) (H1 : ∀m n, 0 < m → P (n % m) m → P m n) : P m n := @induction _ _ lt_wf (λm, ∀n, P m n) m (λk IH, by {induction k with k ih, exact H0, exact λn, H1 _ _ (succ_pos _) (IH _ (mod_lt _ (succ_pos _)) _)}) n def lcm (m n : ℕ) : ℕ := m * n / (gcd m n) @[reducible] def coprime (m n : ℕ) : Prop := gcd m n = 1 end nat
b3b33b8d7fc5375db30d4d36c000b80bdedf211f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/combinatorics/simple_graph/basic.lean
44e03497d6e9ea1f15fa3ec04d341ceeee0f5692
[ "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
19,597
lean
/- Copyright (c) 2020 Aaron Anderson, Jalex Stark, Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson, Jalex Stark, Kyle Miller, Alena Gusakov -/ import data.fintype.basic import data.sym2 import data.set.finite /-! # Simple graphs This module defines simple graphs on a vertex type `V` as an irreflexive symmetric relation. There is a basic API for locally finite graphs and for graphs with finitely many vertices. ## Main definitions * `simple_graph` is a structure for symmetric, irreflexive relations * `neighbor_set` is the `set` of vertices adjacent to a given vertex * `common_neighbors` is the intersection of the neighbor sets of two given vertices * `neighbor_finset` is the `finset` of vertices adjacent to a given vertex, if `neighbor_set` is finite * `incidence_set` is the `set` of edges containing a given vertex * `incidence_finset` is the `finset` of edges containing a given vertex, if `incidence_set` is finite ## Implementation notes * A locally finite graph is one with instances `∀ v, fintype (G.neighbor_set v)`. * Given instances `decidable_rel G.adj` and `fintype V`, then the graph is locally finite, too. ## Naming Conventions * If the vertex type of a graph is finite, we refer to its cardinality as `card_verts`. TODO: This is the simplest notion of an unoriented graph. This should eventually fit into a more complete combinatorics hierarchy which includes multigraphs and directed graphs. We begin with simple graphs in order to start learning what the combinatorics hierarchy should look like. TODO: Part of this would include defining, for example, subgraphs of a simple graph. -/ open finset universe u /-- A simple graph is an irreflexive symmetric relation `adj` on a vertex type `V`. The relation describes which pairs of vertices are adjacent. There is exactly one edge for every pair of adjacent edges; see `simple_graph.edge_set` for the corresponding edge set. -/ @[ext] structure simple_graph (V : Type u) := (adj : V → V → Prop) (sym : symmetric adj . obviously) (loopless : irreflexive adj . obviously) /-- Construct the simple graph induced by the given relation. It symmetrizes the relation and makes it irreflexive. -/ def simple_graph.from_rel {V : Type u} (r : V → V → Prop) : simple_graph V := { adj := λ a b, (a ≠ b) ∧ (r a b ∨ r b a), sym := λ a b ⟨hn, hr⟩, ⟨hn.symm, hr.symm⟩, loopless := λ a ⟨hn, _⟩, hn rfl } noncomputable instance {V : Type u} [fintype V] : fintype (simple_graph V) := by { classical, exact fintype.of_injective simple_graph.adj simple_graph.ext } @[simp] lemma simple_graph.from_rel_adj {V : Type u} (r : V → V → Prop) (v w : V) : (simple_graph.from_rel r).adj v w ↔ v ≠ w ∧ (r v w ∨ r w v) := iff.rfl /-- The complete graph on a type `V` is the simple graph with all pairs of distinct vertices adjacent. -/ def complete_graph (V : Type u) : simple_graph V := { adj := ne } instance (V : Type u) : inhabited (simple_graph V) := ⟨complete_graph V⟩ instance complete_graph_adj_decidable (V : Type u) [decidable_eq V] : decidable_rel (complete_graph V).adj := λ v w, not.decidable namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- `G.neighbor_set v` is the set of vertices adjacent to `v` in `G`. -/ def neighbor_set (v : V) : set V := set_of (G.adj v) instance neighbor_set.mem_decidable (v : V) [decidable_rel G.adj] : decidable_pred (G.neighbor_set v) := by { unfold neighbor_set, apply_instance } lemma ne_of_adj {a b : V} (hab : G.adj a b) : a ≠ b := by { rintro rfl, exact G.loopless a hab } /-- The edges of G consist of the unordered pairs of vertices related by `G.adj`. -/ def edge_set : set (sym2 V) := sym2.from_rel G.sym /-- The `incidence_set` is the set of edges incident to a given vertex. -/ def incidence_set (v : V) : set (sym2 V) := {e ∈ G.edge_set | v ∈ e} lemma incidence_set_subset (v : V) : G.incidence_set v ⊆ G.edge_set := λ _ h, h.1 @[simp] lemma mem_edge_set {v w : V} : ⟦(v, w)⟧ ∈ G.edge_set ↔ G.adj v w := by refl /-- Two vertices are adjacent iff there is an edge between them. The condition `v ≠ w` ensures they are different endpoints of the edge, which is necessary since when `v = w` the existential `∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e` is satisfied by every edge incident to `v`. -/ lemma adj_iff_exists_edge {v w : V} : G.adj v w ↔ v ≠ w ∧ ∃ (e ∈ G.edge_set), v ∈ e ∧ w ∈ e := begin refine ⟨λ _, ⟨G.ne_of_adj ‹_›, ⟦(v,w)⟧, _⟩, _⟩, { simpa }, { rintro ⟨hne, e, he, hv⟩, rw sym2.elems_iff_eq hne at hv, subst e, rwa mem_edge_set at he } end lemma edge_other_ne {e : sym2 V} (he : e ∈ G.edge_set) {v : V} (h : v ∈ e) : h.other ≠ v := begin erw [← sym2.mem_other_spec h, sym2.eq_swap] at he, exact G.ne_of_adj he, end instance edge_set_decidable_pred [decidable_rel G.adj] : decidable_pred G.edge_set := sym2.from_rel.decidable_pred _ instance edges_fintype [decidable_eq V] [fintype V] [decidable_rel G.adj] : fintype G.edge_set := subtype.fintype _ instance incidence_set_decidable_pred [decidable_eq V] [decidable_rel G.adj] (v : V) : decidable_pred (G.incidence_set v) := λ e, and.decidable /-- The `edge_set` of the graph as a `finset`. -/ def edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] : finset (sym2 V) := set.to_finset G.edge_set @[simp] lemma mem_edge_finset [decidable_eq V] [fintype V] [decidable_rel G.adj] (e : sym2 V) : e ∈ G.edge_finset ↔ e ∈ G.edge_set := set.mem_to_finset @[simp] lemma edge_set_univ_card [decidable_eq V] [fintype V] [decidable_rel G.adj] : (univ : finset G.edge_set).card = G.edge_finset.card := fintype.card_of_subtype G.edge_finset (mem_edge_finset _) @[simp] lemma irrefl {v : V} : ¬G.adj v v := G.loopless v lemma edge_symm (u v : V) : G.adj u v ↔ G.adj v u := ⟨λ x, G.sym x, λ x, G.sym x⟩ @[symm] lemma edge_symm' {u v : V} (h : G.adj u v) : G.adj v u := G.sym h @[simp] lemma mem_neighbor_set (v w : V) : w ∈ G.neighbor_set v ↔ G.adj v w := iff.rfl @[simp] lemma mem_incidence_set (v w : V) : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ G.adj v w := by simp [incidence_set] lemma mem_incidence_iff_neighbor {v w : V} : ⟦(v, w)⟧ ∈ G.incidence_set v ↔ w ∈ G.neighbor_set v := by simp only [mem_incidence_set, mem_neighbor_set] lemma adj_incidence_set_inter {v : V} {e : sym2 V} (he : e ∈ G.edge_set) (h : v ∈ e) : G.incidence_set v ∩ G.incidence_set h.other = {e} := begin ext e', simp only [incidence_set, set.mem_sep_eq, set.mem_inter_eq, set.mem_singleton_iff], split, { intro h', rw ←sym2.mem_other_spec h, exact (sym2.elems_iff_eq (edge_other_ne G he h).symm).mp ⟨h'.1.2, h'.2.2⟩, }, { rintro rfl, use [he, h, he], apply sym2.mem_other_mem, }, end /-- The set of common neighbors between two vertices `v` and `w` in a graph `G` is the intersection of the neighbor sets of `v` and `w`. -/ def common_neighbors (v w : V) : set V := G.neighbor_set v ∩ G.neighbor_set w lemma common_neighbors_eq (v w : V) : G.common_neighbors v w = G.neighbor_set v ∩ G.neighbor_set w := rfl lemma mem_common_neighbors {u v w : V} : u ∈ G.common_neighbors v w ↔ G.adj v u ∧ G.adj w u := by simp [common_neighbors] lemma common_neighbors_symm (v w : V) : G.common_neighbors v w = G.common_neighbors w v := by { rw [common_neighbors, set.inter_comm], refl } lemma not_mem_common_neighbors_left (v w : V) : v ∉ G.common_neighbors v w := λ h, ne_of_adj G h.1 rfl lemma not_mem_common_neighbors_right (v w : V) : w ∉ G.common_neighbors v w := λ h, ne_of_adj G h.2 rfl lemma common_neighbors_subset_neighbor_set (v w : V) : G.common_neighbors v w ⊆ G.neighbor_set v := by simp [common_neighbors] instance [decidable_rel G.adj] (v w : V) : decidable_pred (G.common_neighbors v w) := λ a, and.decidable section incidence variable [decidable_eq V] /-- Given an edge incident to a particular vertex, get the other vertex on the edge. -/ def other_vertex_of_incident {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : V := h.2.other' lemma edge_mem_other_incident_set {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : e ∈ G.incidence_set (G.other_vertex_of_incident h) := by { use h.1, simp [other_vertex_of_incident, sym2.mem_other_mem'] } lemma incidence_other_prop {v : V} {e : sym2 V} (h : e ∈ G.incidence_set v) : G.other_vertex_of_incident h ∈ G.neighbor_set v := by { cases h with he hv, rwa [←sym2.mem_other_spec' hv, mem_edge_set] at he } @[simp] lemma incidence_other_neighbor_edge {v w : V} (h : w ∈ G.neighbor_set v) : G.other_vertex_of_incident (G.mem_incidence_iff_neighbor.mpr h) = w := sym2.congr_right.mp (sym2.mem_other_spec' (G.mem_incidence_iff_neighbor.mpr h).right) /-- There is an equivalence between the set of edges incident to a given vertex and the set of vertices adjacent to the vertex. -/ @[simps] def incidence_set_equiv_neighbor_set (v : V) : G.incidence_set v ≃ G.neighbor_set v := { to_fun := λ e, ⟨G.other_vertex_of_incident e.2, G.incidence_other_prop e.2⟩, inv_fun := λ w, ⟨⟦(v, w.1)⟧, G.mem_incidence_iff_neighbor.mpr w.2⟩, left_inv := λ x, by simp [other_vertex_of_incident], right_inv := λ ⟨w, hw⟩, by simp } end incidence section finite_at /-! ## Finiteness at a vertex This section contains definitions and lemmas concerning vertices that have finitely many adjacent vertices. We denote this condition by `fintype (G.neighbor_set v)`. We define `G.neighbor_finset v` to be the `finset` version of `G.neighbor_set v`. Use `neighbor_finset_eq_filter` to rewrite this definition as a `filter`. -/ variables (v : V) [fintype (G.neighbor_set v)] /-- `G.neighbors v` is the `finset` version of `G.adj v` in case `G` is locally finite at `v`. -/ def neighbor_finset : finset V := (G.neighbor_set v).to_finset @[simp] lemma mem_neighbor_finset (w : V) : w ∈ G.neighbor_finset v ↔ G.adj v w := set.mem_to_finset /-- `G.degree v` is the number of vertices adjacent to `v`. -/ def degree : ℕ := (G.neighbor_finset v).card @[simp] lemma card_neighbor_set_eq_degree : fintype.card (G.neighbor_set v) = G.degree v := (set.to_finset_card _).symm lemma degree_pos_iff_exists_adj : 0 < G.degree v ↔ ∃ w, G.adj v w := by simp only [degree, card_pos, finset.nonempty, mem_neighbor_finset] instance incidence_set_fintype [decidable_eq V] : fintype (G.incidence_set v) := fintype.of_equiv (G.neighbor_set v) (G.incidence_set_equiv_neighbor_set v).symm /-- This is the `finset` version of `incidence_set`. -/ def incidence_finset [decidable_eq V] : finset (sym2 V) := (G.incidence_set v).to_finset @[simp] lemma card_incidence_set_eq_degree [decidable_eq V] : fintype.card (G.incidence_set v) = G.degree v := by { rw fintype.card_congr (G.incidence_set_equiv_neighbor_set v), simp } @[simp] lemma mem_incidence_finset [decidable_eq V] (e : sym2 V) : e ∈ G.incidence_finset v ↔ e ∈ G.incidence_set v := set.mem_to_finset end finite_at section locally_finite /-- A graph is locally finite if every vertex has a finite neighbor set. -/ @[reducible] def locally_finite := Π (v : V), fintype (G.neighbor_set v) variable [locally_finite G] /-- A locally finite simple graph is regular of degree `d` if every vertex has degree `d`. -/ def is_regular_of_degree (d : ℕ) : Prop := ∀ (v : V), G.degree v = d lemma is_regular_of_degree_eq {d : ℕ} (h : G.is_regular_of_degree d) (v : V) : G.degree v = d := h v end locally_finite section finite variables [fintype V] instance neighbor_set_fintype [decidable_rel G.adj] (v : V) : fintype (G.neighbor_set v) := @subtype.fintype _ _ (by { simp_rw mem_neighbor_set, apply_instance }) _ lemma neighbor_finset_eq_filter {v : V} [decidable_rel G.adj] : G.neighbor_finset v = finset.univ.filter (G.adj v) := by { ext, simp } @[simp] lemma complete_graph_degree [decidable_eq V] (v : V) : (complete_graph V).degree v = fintype.card V - 1 := begin convert univ.card.pred_eq_sub_one, erw [degree, neighbor_finset_eq_filter, filter_ne, card_erase_of_mem (mem_univ v)], end lemma complete_graph_is_regular [decidable_eq V] : (complete_graph V).is_regular_of_degree (fintype.card V - 1) := by { intro v, simp } /-- The minimum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_minimal_degree_vertex`, `min_degree_le_degree` and `le_min_degree_of_forall_le_degree`. -/ def min_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).min 0 /-- There exists a vertex of minimal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_minimal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.min_degree = G.degree v := begin obtain ⟨t, ht : _ = _⟩ := min_of_nonempty (univ_nonempty.image (λ v, G.degree v)), obtain ⟨v, _, rfl⟩ := mem_image.mp (mem_of_min ht), refine ⟨v, by simp [min_degree, ht]⟩, end /-- The minimum degree in the graph is at most the degree of any particular vertex. -/ lemma min_degree_le_degree [decidable_rel G.adj] (v : V) : G.min_degree ≤ G.degree v := begin obtain ⟨t, ht⟩ := finset.min_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.min_le_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rw option.mem_def at ht, rwa [min_degree, ht, option.get_or_else_some], end /-- In a nonempty graph, if `k` is at most the degree of every vertex, it is at most the minimum degree. Note the assumption that the graph is nonempty is necessary as long as `G.min_degree` is defined to be a natural. -/ lemma le_min_degree_of_forall_le_degree [decidable_rel G.adj] [nonempty V] (k : ℕ) (h : ∀ v, k ≤ G.degree v) : k ≤ G.min_degree := begin rcases G.exists_minimal_degree_vertex with ⟨v, hv⟩, rw hv, apply h end /-- The maximum degree of all vertices (and `0` if there are no vertices). The key properties of this are given in `exists_maximal_degree_vertex`, `degree_le_max_degree` and `max_degree_le_of_forall_degree_le`. -/ def max_degree [decidable_rel G.adj] : ℕ := option.get_or_else (univ.image (λ v, G.degree v)).max 0 /-- There exists a vertex of maximal degree. Note the assumption of being nonempty is necessary, as the lemma implies there exists a vertex. -/ lemma exists_maximal_degree_vertex [decidable_rel G.adj] [nonempty V] : ∃ v, G.max_degree = G.degree v := begin obtain ⟨t, ht⟩ := max_of_nonempty (univ_nonempty.image (λ v, G.degree v)), have ht₂ := mem_of_max ht, simp only [mem_image, mem_univ, exists_prop_of_true] at ht₂, rcases ht₂ with ⟨v, rfl⟩, rw option.mem_def at ht, refine ⟨v, _⟩, rw [max_degree, ht], refl end /-- The maximum degree in the graph is at least the degree of any particular vertex. -/ lemma degree_le_max_degree [decidable_rel G.adj] (v : V) : G.degree v ≤ G.max_degree := begin obtain ⟨t, ht : _ = _⟩ := finset.max_of_mem (mem_image_of_mem (λ v, G.degree v) (mem_univ v)), have := finset.le_max_of_mem (mem_image_of_mem _ (mem_univ v)) ht, rwa [max_degree, ht, option.get_or_else_some], end /-- In a graph, if `k` is at least the degree of every vertex, then it is at least the maximum degree. -/ lemma max_degree_le_of_forall_degree_le [decidable_rel G.adj] (k : ℕ) (h : ∀ v, G.degree v ≤ k) : G.max_degree ≤ k := begin by_cases hV : (univ : finset V).nonempty, { haveI : nonempty V := univ_nonempty_iff.mp hV, obtain ⟨v, hv⟩ := G.exists_maximal_degree_vertex, rw hv, apply h }, { rw not_nonempty_iff_eq_empty at hV, rw [max_degree, hV, image_empty], exact zero_le k }, end lemma degree_lt_card_verts [decidable_rel G.adj] (v : V) : G.degree v < fintype.card V := begin classical, apply finset.card_lt_card, rw finset.ssubset_iff, exact ⟨v, by simp, finset.subset_univ _⟩, end /-- The maximum degree of a nonempty graph is less than the number of vertices. Note that the assumption that `V` is nonempty is necessary, as otherwise this would assert the existence of a natural less than zero. -/ lemma max_degree_lt_card_verts [decidable_rel G.adj] [nonempty V] : G.max_degree < fintype.card V := begin cases G.exists_maximal_degree_vertex with v hv, rw hv, apply G.degree_lt_card_verts v, end lemma card_common_neighbors_le_degree_left [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree v := begin rw [←card_neighbor_set_eq_degree], exact set.card_le_of_subset (set.inter_subset_left _ _), end lemma card_common_neighbors_le_degree_right [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) ≤ G.degree w := begin convert G.card_common_neighbors_le_degree_left w v using 3, apply common_neighbors_symm, end lemma card_common_neighbors_lt_card_verts [decidable_rel G.adj] (v w : V) : fintype.card (G.common_neighbors v w) < fintype.card V := nat.lt_of_le_of_lt (G.card_common_neighbors_le_degree_left _ _) (G.degree_lt_card_verts v) /-- If the condition `G.adj v w` fails, then `card_common_neighbors_le_degree` is the best we can do in general. -/ lemma adj.card_common_neighbors_lt_degree {G : simple_graph V} [decidable_rel G.adj] {v w : V} (h : G.adj v w) : fintype.card (G.common_neighbors v w) < G.degree v := begin classical, erw [←set.to_finset_card], apply finset.card_lt_card, rw finset.ssubset_iff, use w, split, { rw set.mem_to_finset, apply not_mem_common_neighbors_right }, { rw finset.insert_subset, split, { simpa, }, { rw [neighbor_finset, ← set.subset_iff_to_finset_subset], apply common_neighbors_subset_neighbor_set } }, end end finite section complement /-! ## Complement of a simple graph This section contains definitions and lemmas concerning the complement of a simple graph. -/ /-- We define `compl G` to be the `simple_graph V` such that no two adjacent vertices in `G` are adjacent in the complement, and every nonadjacent pair of vertices is adjacent (still ensuring that vertices are not adjacent to themselves.) -/ def compl (G : simple_graph V) : simple_graph V := { adj := λ v w, v ≠ w ∧ ¬G.adj v w, sym := λ v w ⟨hne, _⟩, ⟨hne.symm, by rwa edge_symm⟩, loopless := λ v ⟨hne, _⟩, false.elim (hne rfl) } instance has_compl : has_compl (simple_graph V) := { compl := compl } @[simp] lemma compl_adj (G : simple_graph V) (v w : V) : Gᶜ.adj v w ↔ v ≠ w ∧ ¬G.adj v w := iff.rfl instance compl_adj_decidable (V : Type u) [decidable_eq V] (G : simple_graph V) [decidable_rel G.adj] : decidable_rel Gᶜ.adj := λ v w, and.decidable @[simp] lemma compl_compl (G : simple_graph V) : Gᶜᶜ = G := begin ext v w, split; simp only [compl_adj, not_and, not_not], { exact λ ⟨hne, h⟩, h hne }, { intro h, simpa [G.ne_of_adj h], }, end @[simp] lemma compl_involutive : function.involutive (@compl V) := compl_compl lemma compl_neighbor_set_disjoint (G : simple_graph V) (v : V) : disjoint (G.neighbor_set v) (Gᶜ.neighbor_set v) := begin rw set.disjoint_iff, rintro w ⟨h, h'⟩, rw [mem_neighbor_set, compl_adj] at h', exact h'.2 h, end lemma neighbor_set_union_compl_neighbor_set_eq (G : simple_graph V) (v : V) : G.neighbor_set v ∪ Gᶜ.neighbor_set v = {v}ᶜ := begin ext w, have h := @ne_of_adj _ G, simp_rw [set.mem_union, mem_neighbor_set, compl_adj, set.mem_compl_eq, set.mem_singleton_iff], tauto, end end complement end simple_graph
d4e2ae5812cacd24a004a3f86926129970e01b77
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/special_functions/sqrt.lean
3288842d449ea3a235420529f0dca8683ad3f7d6
[ "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
6,256
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.calculus.cont_diff /-! # Smoothness of `real.sqrt` In this file we prove that `real.sqrt` is infinitely smooth at all points `x ≠ 0` and provide some dot-notation lemmas. ## Tags sqrt, differentiable -/ open set open_locale topology namespace real /-- Local homeomorph between `(0, +∞)` and `(0, +∞)` with `to_fun = λ x, x ^ 2` and `inv_fun = sqrt`. -/ noncomputable def sq_local_homeomorph : local_homeomorph ℝ ℝ := { to_fun := λ x, x ^ 2, inv_fun := sqrt, source := Ioi 0, target := Ioi 0, map_source' := λ x hx, mem_Ioi.2 (pow_pos hx _), map_target' := λ x hx, mem_Ioi.2 (sqrt_pos.2 hx), left_inv' := λ x hx, sqrt_sq (le_of_lt hx), right_inv' := λ x hx, sq_sqrt (le_of_lt hx), open_source := is_open_Ioi, open_target := is_open_Ioi, continuous_to_fun := (continuous_pow 2).continuous_on, continuous_inv_fun := continuous_on_id.sqrt } lemma deriv_sqrt_aux {x : ℝ} (hx : x ≠ 0) : has_strict_deriv_at sqrt (1 / (2 * sqrt x)) x ∧ ∀ n, cont_diff_at ℝ n sqrt x := begin cases hx.lt_or_lt with hx hx, { rw [sqrt_eq_zero_of_nonpos hx.le, mul_zero, div_zero], have : sqrt =ᶠ[𝓝 x] (λ _, 0) := (gt_mem_nhds hx).mono (λ x hx, sqrt_eq_zero_of_nonpos hx.le), exact ⟨(has_strict_deriv_at_const x (0 : ℝ)).congr_of_eventually_eq this.symm, λ n, cont_diff_at_const.congr_of_eventually_eq this⟩ }, { have : ↑2 * sqrt x ^ (2 - 1) ≠ 0, by simp [(sqrt_pos.2 hx).ne', @two_ne_zero ℝ], split, { simpa using sq_local_homeomorph.has_strict_deriv_at_symm hx this (has_strict_deriv_at_pow 2 _) }, { exact λ n, sq_local_homeomorph.cont_diff_at_symm_deriv this hx (has_deriv_at_pow 2 (sqrt x)) (cont_diff_at_id.pow 2) } } end lemma has_strict_deriv_at_sqrt {x : ℝ} (hx : x ≠ 0) : has_strict_deriv_at sqrt (1 / (2 * sqrt x)) x := (deriv_sqrt_aux hx).1 lemma cont_diff_at_sqrt {x : ℝ} {n : ℕ∞} (hx : x ≠ 0) : cont_diff_at ℝ n sqrt x := (deriv_sqrt_aux hx).2 n lemma has_deriv_at_sqrt {x : ℝ} (hx : x ≠ 0) : has_deriv_at sqrt (1 / (2 * sqrt x)) x := (has_strict_deriv_at_sqrt hx).has_deriv_at end real open real section deriv variables {f : ℝ → ℝ} {s : set ℝ} {f' x : ℝ} lemma has_deriv_within_at.sqrt (hf : has_deriv_within_at f f' s x) (hx : f x ≠ 0) : has_deriv_within_at (λ y, sqrt (f y)) (f' / (2 * sqrt (f x))) s x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_deriv_at_sqrt hx).comp_has_deriv_within_at x hf lemma has_deriv_at.sqrt (hf : has_deriv_at f f' x) (hx : f x ≠ 0) : has_deriv_at (λ y, sqrt (f y)) (f' / (2 * sqrt(f x))) x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_deriv_at_sqrt hx).comp x hf lemma has_strict_deriv_at.sqrt (hf : has_strict_deriv_at f f' x) (hx : f x ≠ 0) : has_strict_deriv_at (λ t, sqrt (f t)) (f' / (2 * sqrt (f x))) x := by simpa only [(∘), div_eq_inv_mul, mul_one] using (has_strict_deriv_at_sqrt hx).comp x hf lemma deriv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : deriv_within (λx, sqrt (f x)) s x = (deriv_within f s x) / (2 * sqrt (f x)) := (hf.has_deriv_within_at.sqrt hx).deriv_within hxs @[simp] lemma deriv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : deriv (λx, sqrt (f x)) x = (deriv f x) / (2 * sqrt (f x)) := (hf.has_deriv_at.sqrt hx).deriv end deriv section fderiv variables {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] {f : E → ℝ} {n : ℕ∞} {s : set E} {x : E} {f' : E →L[ℝ] ℝ} lemma has_fderiv_at.sqrt (hf : has_fderiv_at f f' x) (hx : f x ≠ 0) : has_fderiv_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') x := (has_deriv_at_sqrt hx).comp_has_fderiv_at x hf lemma has_strict_fderiv_at.sqrt (hf : has_strict_fderiv_at f f' x) (hx : f x ≠ 0) : has_strict_fderiv_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') x := (has_strict_deriv_at_sqrt hx).comp_has_strict_fderiv_at x hf lemma has_fderiv_within_at.sqrt (hf : has_fderiv_within_at f f' s x) (hx : f x ≠ 0) : has_fderiv_within_at (λ y, sqrt (f y)) ((1 / (2 * sqrt (f x))) • f') s x := (has_deriv_at_sqrt hx).comp_has_fderiv_within_at x hf lemma differentiable_within_at.sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) : differentiable_within_at ℝ (λ y, sqrt (f y)) s x := (hf.has_fderiv_within_at.sqrt hx).differentiable_within_at lemma differentiable_at.sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : differentiable_at ℝ (λ y, sqrt (f y)) x := (hf.has_fderiv_at.sqrt hx).differentiable_at lemma differentiable_on.sqrt (hf : differentiable_on ℝ f s) (hs : ∀ x ∈ s, f x ≠ 0) : differentiable_on ℝ (λ y, sqrt (f y)) s := λ x hx, (hf x hx).sqrt (hs x hx) lemma differentiable.sqrt (hf : differentiable ℝ f) (hs : ∀ x, f x ≠ 0) : differentiable ℝ (λ y, sqrt (f y)) := λ x, (hf x).sqrt (hs x) lemma fderiv_within_sqrt (hf : differentiable_within_at ℝ f s x) (hx : f x ≠ 0) (hxs : unique_diff_within_at ℝ s x) : fderiv_within ℝ (λx, sqrt (f x)) s x = (1 / (2 * sqrt (f x))) • fderiv_within ℝ f s x := (hf.has_fderiv_within_at.sqrt hx).fderiv_within hxs @[simp] lemma fderiv_sqrt (hf : differentiable_at ℝ f x) (hx : f x ≠ 0) : fderiv ℝ (λx, sqrt (f x)) x = (1 / (2 * sqrt (f x))) • fderiv ℝ f x := (hf.has_fderiv_at.sqrt hx).fderiv lemma cont_diff_at.sqrt (hf : cont_diff_at ℝ n f x) (hx : f x ≠ 0) : cont_diff_at ℝ n (λ y, sqrt (f y)) x := (cont_diff_at_sqrt hx).comp x hf lemma cont_diff_within_at.sqrt (hf : cont_diff_within_at ℝ n f s x) (hx : f x ≠ 0) : cont_diff_within_at ℝ n (λ y, sqrt (f y)) s x := (cont_diff_at_sqrt hx).comp_cont_diff_within_at x hf lemma cont_diff_on.sqrt (hf : cont_diff_on ℝ n f s) (hs : ∀ x ∈ s, f x ≠ 0) : cont_diff_on ℝ n (λ y, sqrt (f y)) s := λ x hx, (hf x hx).sqrt (hs x hx) lemma cont_diff.sqrt (hf : cont_diff ℝ n f) (h : ∀ x, f x ≠ 0) : cont_diff ℝ n (λ y, sqrt (f y)) := cont_diff_iff_cont_diff_at.2 $ λ x, (hf.cont_diff_at.sqrt (h x)) end fderiv
49294e92c3aacdeb2374f97a90950018f2f15253
94e33a31faa76775069b071adea97e86e218a8ee
/src/group_theory/subsemigroup/operations.lean
c975e1cb6002fb7033efbb1d3558221a5fbc9bcb
[ "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
28,695
lean
/- Copyright (c) 2022 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov, Yakov Pechersky, Jireh Loreaux -/ import group_theory.subsemigroup.basic /-! # Operations on `subsemigroup`s In this file we define various operations on `subsemigroup`s and `mul_hom`s. ## Main definitions ### Conversion between multiplicative and additive definitions * `subsemigroup.to_add_subsemigroup`, `subsemigroup.to_add_subsemigroup'`, `add_subsemigroup.to_subsemigroup`, `add_subsemigroup.to_subsemigroup'`: convert between multiplicative and additive subsemigroups of `M`, `multiplicative M`, and `additive M`. These are stated as `order_iso`s. ### (Commutative) semigroup structure on a subsemigroup * `subsemigroup.to_semigroup`, `subsemigroup.to_comm_semigroup`: a subsemigroup inherits a (commutative) semigroup structure. ### Operations on subsemigroups * `subsemigroup.comap`: preimage of a subsemigroup under a semigroup homomorphism as a subsemigroup of the domain; * `subsemigroup.map`: image of a subsemigroup under a semigroup homomorphism as a subsemigroup of the codomain; * `subsemigroup.prod`: product of two subsemigroups `s : subsemigroup M` and `t : subsemigroup N` as a subsemigroup of `M × N`; ### Semigroup homomorphisms between subsemigroups * `subsemigroup.subtype`: embedding of a subsemigroup into the ambient semigroup. * `subsemigroup.inclusion`: given two subsemigroups `S`, `T` such that `S ≤ T`, `S.inclusion T` is the inclusion of `S` into `T` as a semigroup homomorphism; * `mul_equiv.subsemigroup_congr`: converts a proof of `S = T` into a semigroup isomorphism between `S` and `T`. * `subsemigroup.prod_equiv`: semigroup isomorphism between `s.prod t` and `s × t`; ### Operations on `mul_hom`s * `mul_hom.srange`: range of a semigroup homomorphism as a subsemigroup of the codomain; * `mul_hom.restrict`: restrict a semigroup homomorphism to a subsemigroup; * `mul_hom.cod_restrict`: restrict the codomain of a semigroup homomorphism to a subsemigroup; * `mul_hom.srange_restrict`: restrict a semigroup homomorphism to its range; ### Implementation notes This file follows closely `group_theory/submonoid/operations.lean`, omitting only that which is necessary. ## Tags subsemigroup, range, product, map, comap -/ variables {M N P σ : Type*} /-! ### Conversion to/from `additive`/`multiplicative` -/ section variables [has_mul M] /-- Subsemigroups of semigroup `M` are isomorphic to additive subsemigroups of `additive M`. -/ @[simps] def subsemigroup.to_add_subsemigroup : subsemigroup M ≃o add_subsemigroup (additive M) := { to_fun := λ S, { carrier := additive.to_mul ⁻¹' S, add_mem' := S.mul_mem' }, inv_fun := λ S, { carrier := additive.of_mul ⁻¹' S, mul_mem' := S.add_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Additive subsemigroups of an additive semigroup `additive M` are isomorphic to subsemigroups of `M`. -/ abbreviation add_subsemigroup.to_subsemigroup' : add_subsemigroup (additive M) ≃o subsemigroup M := subsemigroup.to_add_subsemigroup.symm lemma subsemigroup.to_add_subsemigroup_closure (S : set M) : (subsemigroup.closure S).to_add_subsemigroup = add_subsemigroup.closure (additive.to_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup.le_symm_apply.1 $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) lemma add_subsemigroup.to_subsemigroup'_closure (S : set (additive M)) : (add_subsemigroup.closure S).to_subsemigroup' = subsemigroup.closure (multiplicative.of_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup'.le_symm_apply.1 $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) end section variables {A : Type*} [has_add A] /-- Additive subsemigroups of an additive semigroup `A` are isomorphic to multiplicative subsemigroups of `multiplicative A`. -/ @[simps] def add_subsemigroup.to_subsemigroup : add_subsemigroup A ≃o subsemigroup (multiplicative A) := { to_fun := λ S, { carrier := multiplicative.to_add ⁻¹' S, mul_mem' := S.add_mem' }, inv_fun := λ S, { carrier := multiplicative.of_add ⁻¹' S, add_mem' := S.mul_mem' }, left_inv := λ x, by cases x; refl, right_inv := λ x, by cases x; refl, map_rel_iff' := λ a b, iff.rfl, } /-- Subsemigroups of a semigroup `multiplicative A` are isomorphic to additive subsemigroups of `A`. -/ abbreviation subsemigroup.to_add_subsemigroup' : subsemigroup (multiplicative A) ≃o add_subsemigroup A := add_subsemigroup.to_subsemigroup.symm lemma add_subsemigroup.to_subsemigroup_closure (S : set A) : (add_subsemigroup.closure S).to_subsemigroup = subsemigroup.closure (multiplicative.to_add ⁻¹' S) := le_antisymm (add_subsemigroup.to_subsemigroup.to_galois_connection.l_le $ add_subsemigroup.closure_le.2 subsemigroup.subset_closure) (subsemigroup.closure_le.2 add_subsemigroup.subset_closure) lemma subsemigroup.to_add_subsemigroup'_closure (S : set (multiplicative A)) : (subsemigroup.closure S).to_add_subsemigroup' = add_subsemigroup.closure (additive.of_mul ⁻¹' S) := le_antisymm (subsemigroup.to_add_subsemigroup'.to_galois_connection.l_le $ subsemigroup.closure_le.2 add_subsemigroup.subset_closure) (add_subsemigroup.closure_le.2 subsemigroup.subset_closure) end namespace subsemigroup open set /-! ### `comap` and `map` -/ variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The preimage of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The preimage of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def comap (f : M →ₙ* N) (S : subsemigroup N) : subsemigroup M := { carrier := (f ⁻¹' S), mul_mem' := λ a b ha hb, show f (a * b) ∈ S, by rw map_mul; exact mul_mem ha hb } @[simp, to_additive] lemma coe_comap (S : subsemigroup N) (f : M →ₙ* N) : (S.comap f : set M) = f ⁻¹' S := rfl @[simp, to_additive] lemma mem_comap {S : subsemigroup N} {f : M →ₙ* N} {x : M} : x ∈ S.comap f ↔ f x ∈ S := iff.rfl @[to_additive] lemma comap_comap (S : subsemigroup P) (g : N →ₙ* P) (f : M →ₙ* N) : (S.comap g).comap f = S.comap (g.comp f) := rfl @[simp, to_additive] lemma comap_id (S : subsemigroup P) : S.comap (mul_hom.id _) = S := ext (by simp) /-- The image of a subsemigroup along a semigroup homomorphism is a subsemigroup. -/ @[to_additive "The image of an `add_subsemigroup` along an `add_semigroup` homomorphism is an `add_subsemigroup`."] def map (f : M →ₙ* N) (S : subsemigroup M) : subsemigroup N := { carrier := (f '' S), mul_mem' := begin rintros _ _ ⟨x, hx, rfl⟩ ⟨y, hy, rfl⟩, exact ⟨x * y, @mul_mem (subsemigroup M) M _ _ _ _ _ _ hx hy, by rw map_mul; refl⟩ end } @[simp, to_additive] lemma coe_map (f : M →ₙ* N) (S : subsemigroup M) : (S.map f : set N) = f '' S := rfl @[simp, to_additive] lemma mem_map {f : M →ₙ* N} {S : subsemigroup M} {y : N} : y ∈ S.map f ↔ ∃ x ∈ S, f x = y := mem_image_iff_bex @[to_additive] lemma mem_map_of_mem (f : M →ₙ* N) {S : subsemigroup M} {x : M} (hx : x ∈ S) : f x ∈ S.map f := mem_image_of_mem f hx @[to_additive] lemma apply_coe_mem_map (f : M →ₙ* N) (S : subsemigroup M) (x : S) : f x ∈ S.map f := mem_map_of_mem f x.prop @[to_additive] lemma map_map (g : N →ₙ* P) (f : M →ₙ* N) : (S.map f).map g = S.map (g.comp f) := set_like.coe_injective $ image_image _ _ _ @[to_additive] lemma mem_map_iff_mem {f : M →ₙ* N} (hf : function.injective f) {S : subsemigroup M} {x : M} : f x ∈ S.map f ↔ x ∈ S := hf.mem_set_image @[to_additive] lemma map_le_iff_le_comap {f : M →ₙ* N} {S : subsemigroup M} {T : subsemigroup N} : S.map f ≤ T ↔ S ≤ T.comap f := image_subset_iff @[to_additive] lemma gc_map_comap (f : M →ₙ* N) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap @[to_additive] lemma map_le_of_le_comap {T : subsemigroup N} {f : M →ₙ* N} : S ≤ T.comap f → S.map f ≤ T := (gc_map_comap f).l_le @[to_additive] lemma le_comap_of_map_le {T : subsemigroup N} {f : M →ₙ* N} : S.map f ≤ T → S ≤ T.comap f := (gc_map_comap f).le_u @[to_additive] lemma le_comap_map {f : M →ₙ* N} : S ≤ (S.map f).comap f := (gc_map_comap f).le_u_l _ @[to_additive] lemma map_comap_le {S : subsemigroup N} {f : M →ₙ* N} : (S.comap f).map f ≤ S := (gc_map_comap f).l_u_le _ @[to_additive] lemma monotone_map {f : M →ₙ* N} : monotone (map f) := (gc_map_comap f).monotone_l @[to_additive] lemma monotone_comap {f : M →ₙ* N} : monotone (comap f) := (gc_map_comap f).monotone_u @[simp, to_additive] lemma map_comap_map {f : M →ₙ* N} : ((S.map f).comap f).map f = S.map f := (gc_map_comap f).l_u_l_eq_l _ @[simp, to_additive] lemma comap_map_comap {S : subsemigroup N} {f : M →ₙ* N} : ((S.comap f).map f).comap f = S.comap f := (gc_map_comap f).u_l_u_eq_u _ @[to_additive] lemma map_sup (S T : subsemigroup M) (f : M →ₙ* N) : (S ⊔ T).map f = S.map f ⊔ T.map f := (gc_map_comap f).l_sup @[to_additive] lemma map_supr {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup M) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr @[to_additive] lemma comap_inf (S T : subsemigroup N) (f : M →ₙ* N) : (S ⊓ T).comap f = S.comap f ⊓ T.comap f := (gc_map_comap f).u_inf @[to_additive] lemma comap_infi {ι : Sort*} (f : M →ₙ* N) (s : ι → subsemigroup N) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp, to_additive] lemma map_bot (f : M →ₙ* N) : (⊥ : subsemigroup M).map f = ⊥ := (gc_map_comap f).l_bot @[simp, to_additive] lemma comap_top (f : M →ₙ* N) : (⊤ : subsemigroup N).comap f = ⊤ := (gc_map_comap f).u_top @[simp, to_additive] lemma map_id (S : subsemigroup M) : S.map (mul_hom.id M) = S := ext (λ x, ⟨λ ⟨_, h, rfl⟩, h, λ h, ⟨_, h, rfl⟩⟩) section galois_coinsertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. "-/] def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) @[to_additive] lemma comap_map_eq_of_injective (S : subsemigroup M) : (S.map f).comap f = S := (gci_map_comap hf).u_l_eq _ @[to_additive] lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective @[to_additive] lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective @[to_additive] lemma comap_inf_map_of_injective (S T : subsemigroup M) : (S.map f ⊓ T.map f).comap f = S ⊓ T := (gci_map_comap hf).u_inf_l _ _ @[to_additive] lemma comap_infi_map_of_injective (S : ι → subsemigroup M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ @[to_additive] lemma comap_sup_map_of_injective (S T : subsemigroup M) : (S.map f ⊔ T.map f).comap f = S ⊔ T := (gci_map_comap hf).u_sup_l _ _ @[to_additive] lemma comap_supr_map_of_injective (S : ι → subsemigroup M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ @[to_additive] lemma map_le_map_iff_of_injective {S T : subsemigroup M} : S.map f ≤ T.map f ↔ S ≤ T := (gci_map_comap hf).l_le_l_iff @[to_additive] lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion section galois_insertion variables {ι : Type*} {f : M →ₙ* N} (hf : function.surjective f) include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ @[to_additive /-" `map f` and `comap f` form a `galois_insertion` when `f` is surjective. "-/] def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x h, let ⟨y, hy⟩ := hf x in mem_map.2 ⟨y, by simp [hy, h]⟩) @[to_additive] lemma map_comap_eq_of_surjective (S : subsemigroup N) : (S.comap f).map f = S := (gi_map_comap hf).l_u_eq _ @[to_additive] lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective @[to_additive] lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective @[to_additive] lemma map_inf_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊓ T.comap f).map f = S ⊓ T := (gi_map_comap hf).l_inf_u _ _ @[to_additive] lemma map_infi_comap_of_surjective (S : ι → subsemigroup N) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ @[to_additive] lemma map_sup_comap_of_surjective (S T : subsemigroup N) : (S.comap f ⊔ T.comap f).map f = S ⊔ T := (gi_map_comap hf).l_sup_u _ _ @[to_additive] lemma map_supr_comap_of_surjective (S : ι → subsemigroup N) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ @[to_additive] lemma comap_le_comap_iff_of_surjective {S T : subsemigroup N} : S.comap f ≤ T.comap f ↔ S ≤ T := (gi_map_comap hf).u_le_u_iff @[to_additive] lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion end subsemigroup namespace mul_mem_class variables {A : Type*} [has_mul M] [set_like A M] [hA : mul_mem_class A M] (S' : A) include hA /-- A submagma of a magma inherits a multiplication. -/ @[to_additive "An additive submagma of an additive magma inherits an addition.", priority 900] -- lower priority so other instances are found first instance has_mul : has_mul S' := ⟨λ a b, ⟨a.1 * b.1, mul_mem a.2 b.2⟩⟩ @[simp, norm_cast, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma coe_mul (x y : S') : (↑(x * y) : M) = ↑x * ↑y := rfl @[simp, to_additive, priority 900] -- lower priority so later simp lemmas are used first; to appease simp_nf lemma mk_mul_mk (x y : M) (hx : x ∈ S') (hy : y ∈ S') : (⟨x, hx⟩ : S') * ⟨y, hy⟩ = ⟨x * y, mul_mem hx hy⟩ := rfl @[to_additive] lemma mul_def (x y : S') : x * y = ⟨x * y, mul_mem x.2 y.2⟩ := rfl omit hA /-- A subsemigroup of a semigroup inherits a semigroup structure. -/ @[to_additive "An `add_subsemigroup` of an `add_semigroup` inherits an `add_semigroup` structure."] instance to_semigroup {M : Type*} [semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : semigroup S := subtype.coe_injective.semigroup coe (λ _ _, rfl) /-- A subsemigroup of a `comm_semigroup` is a `comm_semigroup`. -/ @[to_additive "An `add_subsemigroup` of an `add_comm_semigroup` is an `add_comm_semigroup`."] instance to_comm_semigroup {M} [comm_semigroup M] {A : Type*} [set_like A M] [mul_mem_class A M] (S : A) : comm_semigroup S := subtype.coe_injective.comm_semigroup coe (λ _ _, rfl) include hA /-- The natural semigroup hom from a subsemigroup of semigroup `M` to `M`. -/ @[to_additive "The natural semigroup hom from an `add_subsemigroup` of `add_semigroup` `M` to `M`."] def subtype : S' →ₙ* M := ⟨coe, λ _ _, rfl⟩ @[simp, to_additive] theorem coe_subtype : (mul_mem_class.subtype S' : S' → M) = coe := rfl end mul_mem_class namespace subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The top subsemigroup is isomorphic to the semigroup. -/ @[to_additive "The top additive subsemigroup is isomorphic to the additive semigroup.", simps] def top_equiv : (⊤ : subsemigroup M) ≃* M := { to_fun := λ x, x, inv_fun := λ x, ⟨x, mem_top x⟩, left_inv := λ x, x.eta _, right_inv := λ _, rfl, map_mul' := λ _ _, rfl } @[simp, to_additive] lemma top_equiv_to_mul_hom : (top_equiv : _ ≃* M).to_mul_hom = mul_mem_class.subtype (⊤ : subsemigroup M) := rfl /-- A subsemigroup is isomorphic to its image under an injective function -/ @[to_additive "An additive subsemigroup is isomorphic to its image under an injective function"] noncomputable def equiv_map_of_injective (f : M →ₙ* N) (hf : function.injective f) : S ≃* S.map f := { map_mul' := λ _ _, subtype.ext (map_mul f _ _), ..equiv.set.image f S hf } @[simp, to_additive] lemma coe_equiv_map_of_injective_apply (f : M →ₙ* N) (hf : function.injective f) (x : S) : (equiv_map_of_injective S f hf x : N) = f x := rfl @[simp, to_additive] lemma closure_closure_coe_preimage {s : set M} : closure ((coe : closure s → M) ⁻¹' s) = ⊤ := eq_top_iff.2 $ λ x, subtype.rec_on x $ λ x hx _, begin refine closure_induction' _ (λ g hg, _) (λ g₁ g₂ hg₁ hg₂, _) hx, { exact subset_closure hg }, { exact subsemigroup.mul_mem _ }, end /-- Given `subsemigroup`s `s`, `t` of semigroups `M`, `N` respectively, `s × t` as a subsemigroup of `M × N`. -/ @[to_additive prod "Given `add_subsemigroup`s `s`, `t` of `add_semigroup`s `A`, `B` respectively, `s × t` as an `add_subsemigroup` of `A × B`."] def prod (s : subsemigroup M) (t : subsemigroup N) : subsemigroup (M × N) := { carrier := (s : set M) ×ˢ (t : set N), mul_mem' := λ p q hp hq, ⟨s.mul_mem hp.1 hq.1, t.mul_mem hp.2 hq.2⟩ } @[to_additive coe_prod] lemma coe_prod (s : subsemigroup M) (t : subsemigroup N) : (s.prod t : set (M × N)) = (s : set M) ×ˢ (t : set N) := rfl @[to_additive mem_prod] lemma mem_prod {s : subsemigroup M} {t : subsemigroup N} {p : M × N} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[to_additive prod_mono] lemma prod_mono {s₁ s₂ : subsemigroup M} {t₁ t₂ : subsemigroup N} (hs : s₁ ≤ s₂) (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht @[to_additive prod_top] lemma prod_top (s : subsemigroup M) : s.prod (⊤ : subsemigroup N) = s.comap (mul_hom.fst M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_fst] @[to_additive top_prod] lemma top_prod (s : subsemigroup N) : (⊤ : subsemigroup M).prod s = s.comap (mul_hom.snd M N) := ext $ λ x, by simp [mem_prod, mul_hom.coe_snd] @[simp, to_additive top_prod_top] lemma top_prod_top : (⊤ : subsemigroup M).prod (⊤ : subsemigroup N) = ⊤ := (top_prod _).trans $ comap_top _ @[to_additive] lemma bot_prod_bot : (⊥ : subsemigroup M).prod (⊥ : subsemigroup N) = ⊥ := set_like.coe_injective $ by simp [coe_prod, prod.one_eq_mk] /-- The product of subsemigroups is isomorphic to their product as semigroups. -/ @[to_additive prod_equiv "The product of additive subsemigroups is isomorphic to their product as additive semigroups"] def prod_equiv (s : subsemigroup M) (t : subsemigroup N) : s.prod t ≃* s × t := { map_mul' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } open mul_hom @[to_additive] lemma mem_map_equiv {f : M ≃* N} {K : subsemigroup M} {x : N} : x ∈ K.map f.to_mul_hom ↔ f.symm x ∈ K := @set.mem_image_equiv _ _ ↑K f.to_equiv x @[to_additive] lemma map_equiv_eq_comap_symm (f : M ≃* N) (K : subsemigroup M) : K.map f.to_mul_hom = K.comap f.symm.to_mul_hom := set_like.coe_injective (f.to_equiv.image_eq_preimage K) @[to_additive] lemma comap_equiv_eq_map_symm (f : N ≃* M) (K : subsemigroup M) : K.comap f.to_mul_hom = K.map f.symm.to_mul_hom := (map_equiv_eq_comap_symm f.symm K).symm @[simp, to_additive] lemma map_equiv_top (f : M ≃* N) : (⊤ : subsemigroup M).map f.to_mul_hom = ⊤ := set_like.coe_injective $ set.image_univ.trans f.surjective.range_eq @[to_additive le_prod_iff] lemma le_prod_iff {s : subsemigroup M} {t : subsemigroup N} {u : subsemigroup (M × N)} : u ≤ s.prod t ↔ u.map (fst M N) ≤ s ∧ u.map (snd M N) ≤ t := begin split, { intros h, split, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).1 }, { rintros x ⟨⟨y1,y2⟩, ⟨hy1,rfl⟩⟩, exact (h hy1).2 }, }, { rintros ⟨hH, hK⟩ ⟨x1, x2⟩ h, exact ⟨hH ⟨_ , h, rfl⟩, hK ⟨ _, h, rfl⟩⟩, } end end subsemigroup namespace mul_hom open subsemigroup variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) /-- The range of a semigroup homomorphism is a subsemigroup. See Note [range copy pattern]. -/ @[to_additive "The range of an `add_hom` is an `add_subsemigroup`."] def srange (f : M →ₙ* N) : subsemigroup N := ((⊤ : subsemigroup M).map f).copy (set.range f) set.image_univ.symm @[simp, to_additive] lemma coe_srange (f : M →ₙ* N) : (f.srange : set N) = set.range f := rfl @[simp, to_additive] lemma mem_srange {f : M →ₙ* N} {y : N} : y ∈ f.srange ↔ ∃ x, f x = y := iff.rfl @[to_additive] lemma srange_eq_map (f : M →ₙ* N) : f.srange = (⊤ : subsemigroup M).map f := copy_eq _ @[to_additive] lemma map_srange (g : N →ₙ* P) (f : M →ₙ* N) : f.srange.map g = (g.comp f).srange := by simpa only [srange_eq_map] using (⊤ : subsemigroup M).map_map g f @[to_additive] lemma srange_top_iff_surjective {N} [has_mul N] {f : M →ₙ* N} : f.srange = (⊤ : subsemigroup N) ↔ 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 semigroup hom is the whole of the codomain. -/ @[to_additive "The range of a surjective `add_semigroup` hom is the whole of the codomain."] lemma srange_top_of_surjective {N} [has_mul N] (f : M →ₙ* N) (hf : function.surjective f) : f.srange = (⊤ : subsemigroup N) := srange_top_iff_surjective.2 hf @[to_additive] lemma mclosure_preimage_le (f : M →ₙ* N) (s : set N) : 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 semigroup hom of the subsemigroup generated by a set equals the subsemigroup generated by the image of the set. -/ @[to_additive "The image under an `add_semigroup` hom of the `add_subsemigroup` generated by a set equals the `add_subsemigroup` generated by the image of the set."] lemma map_mclosure (f : M →ₙ* N) (s : set M) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (mclosure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) /-- Restriction of a semigroup hom to a subsemigroup of the domain. -/ @[to_additive "Restriction of an add_semigroup hom to an `add_subsemigroup` of the domain."] def restrict {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) (S : σ) : S →ₙ* N := f.comp (mul_mem_class.subtype S) @[simp, to_additive] lemma restrict_apply {N : Type*} [has_mul N] [set_like σ M] [mul_mem_class σ M] (f : M →ₙ* N) {S : σ} (x : S) : f.restrict S x = f x := rfl /-- Restriction of a semigroup hom to a subsemigroup of the codomain. -/ @[to_additive "Restriction of an `add_semigroup` hom to an `add_subsemigroup` of the codomain.", simps] def cod_restrict [set_like σ N] [mul_mem_class σ N] (f : M →ₙ* N) (S : σ) (h : ∀ x, f x ∈ S) : M →ₙ* S := { to_fun := λ n, ⟨f n, h n⟩, map_mul' := λ x y, subtype.eq (map_mul f x y) } /-- Restriction of a semigroup hom to its range interpreted as a subsemigroup. -/ @[to_additive "Restriction of an `add_semigroup` hom to its range interpreted as a subsemigroup."] def srange_restrict {N} [has_mul N] (f : M →ₙ* N) : M →ₙ* f.srange := f.cod_restrict f.srange $ λ x, ⟨x, rfl⟩ @[simp, to_additive] lemma coe_srange_restrict {N} [has_mul N] (f : M →ₙ* N) (x : M) : (f.srange_restrict x : N) = f x := rfl @[to_additive] lemma srange_restrict_surjective (f : M →ₙ* N) : function.surjective f.srange_restrict := λ ⟨_, ⟨x, rfl⟩⟩, ⟨x, rfl⟩ @[to_additive] lemma prod_map_comap_prod' {M' : Type*} {N' : Type*} [has_mul M'] [has_mul N'] (f : M →ₙ* N) (g : M' →ₙ* N') (S : subsemigroup N) (S' : subsemigroup N') : (S.prod S').comap (prod_map f g) = (S.comap f).prod (S'.comap g) := set_like.coe_injective $ set.preimage_prod_map_prod f g _ _ /-- The `mul_hom` from the preimage of a subsemigroup to itself. -/ @[to_additive "the `add_hom` from the preimage of an additive subsemigroup to itself.", simps] def subsemigroup_comap (f : M →ₙ* N) (N' : subsemigroup N) : N'.comap f →ₙ* N' := { to_fun := λ x, ⟨f x, x.prop⟩, map_mul' := λ x y, subtype.eq (@map_mul M N _ _ _ _ f x y) } /-- The `mul_hom` from a subsemigroup to its image. See `mul_equiv.subsemigroup_map` for a variant for `mul_equiv`s. -/ @[to_additive "the `add_hom` from an additive subsemigroup to its image. See `add_equiv.add_subsemigroup_map` for a variant for `add_equiv`s.", simps] def subsemigroup_map (f : M →ₙ* N) (M' : subsemigroup M) : M' →ₙ* M'.map f := { to_fun := λ x, ⟨f x, ⟨x, x.prop, rfl⟩⟩, map_mul' := λ x y, subtype.eq $ @map_mul M N _ _ _ _ f x y } @[to_additive] lemma subsemigroup_map_surjective (f : M →ₙ* N) (M' : subsemigroup M) : function.surjective (f.subsemigroup_map M') := by { rintro ⟨_, x, hx, rfl⟩, exact ⟨⟨x, hx⟩, rfl⟩ } end mul_hom namespace subsemigroup open mul_hom variables [has_mul M] [has_mul N] [has_mul P] (S : subsemigroup M) @[simp, to_additive] lemma srange_fst [nonempty N] : (fst M N).srange = ⊤ := (fst M N).srange_top_of_surjective $ prod.fst_surjective @[simp, to_additive] lemma srange_snd [nonempty M] : (snd M N).srange = ⊤ := (snd M N).srange_top_of_surjective $ prod.snd_surjective @[to_additive] lemma prod_eq_top_iff [nonempty M] [nonempty N] {s : subsemigroup M} {t : subsemigroup N} : s.prod t = ⊤ ↔ s = ⊤ ∧ t = ⊤ := by simp only [eq_top_iff, le_prod_iff, ← (gc_map_comap _).le_iff_le, ← srange_eq_map, srange_fst, srange_snd] /-- The semigroup hom associated to an inclusion of subsemigroups. -/ @[to_additive "The `add_semigroup` hom associated to an inclusion of subsemigroups."] def inclusion {S T : subsemigroup M} (h : S ≤ T) : S →ₙ* T := (mul_mem_class.subtype S).cod_restrict _ (λ x, h x.2) @[simp, to_additive] lemma range_subtype (s : subsemigroup M) : (mul_mem_class.subtype s).srange = s := set_like.coe_injective $ (coe_srange _).trans $ subtype.range_coe @[to_additive] lemma eq_top_iff' : S = ⊤ ↔ ∀ x : M, x ∈ S := eq_top_iff.trans ⟨λ h m, h $ mem_top m, λ h m _, h m⟩ end subsemigroup namespace mul_equiv variables [has_mul M] [has_mul N] {S T : subsemigroup M} /-- Makes the identity isomorphism from a proof that two subsemigroups of a multiplicative semigroup are equal. -/ @[to_additive "Makes the identity additive isomorphism from a proof two subsemigroups of an additive semigroup are equal."] def subsemigroup_congr (h : S = T) : S ≃* T := { map_mul' := λ _ _, rfl, ..equiv.set_congr $ congr_arg _ h } -- this name is primed so that the version to `f.range` instead of `f.srange` can be unprimed. /-- A semigroup homomorphism `f : M →ₙ* N` with a left-inverse `g : N → M` defines a multiplicative equivalence between `M` and `f.srange`. This is a bidirectional version of `mul_hom.srange_restrict`. -/ @[to_additive /-" An additive semigroup homomorphism `f : M →+ N` with a left-inverse `g : N → M` defines an additive equivalence between `M` and `f.srange`. This is a bidirectional version of `add_hom.srange_restrict`. "-/, simps {simp_rhs := tt}] def of_left_inverse (f : M →ₙ* N) {g : N → M} (h : function.left_inverse g f) : M ≃* f.srange := { to_fun := f.srange_restrict, inv_fun := g ∘ (mul_mem_class.subtype f.srange), left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := mul_hom.mem_srange.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.srange_restrict } /-- A `mul_equiv` `φ` between two semigroups `M` and `N` induces a `mul_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `mul_hom.subsemigroup_map` for a variant for `mul_hom`s. -/ @[to_additive "An `add_equiv` `φ` between two additive semigroups `M` and `N` induces an `add_equiv` between a subsemigroup `S ≤ M` and the subsemigroup `φ(S) ≤ N`. See `add_hom.add_subsemigroup_map` for a variant for `add_hom`s.", simps] def subsemigroup_map (e : M ≃* N) (S : subsemigroup M) : S ≃* S.map e.to_mul_hom := { to_fun := λ x, ⟨e x, _⟩, inv_fun := λ x, ⟨e.symm x, _⟩, -- we restate this for `simps` to avoid `⇑e.symm.to_equiv x` ..e.to_mul_hom.subsemigroup_map S, ..e.to_equiv.image S } end mul_equiv
62249636595b83321754a2f7c36fe46bd425a0be
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/multiplicity.lean
f54f1afac1c5b2f3b6194a795502babc159f5b07
[ "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
11,995
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 algebra.big_operators.intervals import algebra.geom_sum import data.nat.bitwise import data.nat.log import data.nat.parity import data.nat.prime import ring_theory.multiplicity /-! # Natural number multiplicity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains lemmas about the multiplicity function (the maximum prime power dividing a number) when applied to naturals, in particular calculating it for factorials and binomial coefficients. ## Multiplicity calculations * `nat.multiplicity_factorial`: Legendre's Theorem. The multiplicity of `p` in `n!` is `n/p + ... + n/p^b` for any `b` such that `n/p^(b + 1) = 0`. * `nat.multiplicity_factorial_mul`: The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. * `nat.multiplicity_choose`: The multiplicity of `p` in `n.choose k` is the number of carries when `k` and`n - k` are added in base `p`. ## Other declarations * `nat.multiplicity_eq_card_pow_dvd`: The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. * `nat.multiplicity_two_factorial_lt`: The multiplicity of `2` in `n!` is strictly less than `n`. * `nat.prime.multiplicity_something`: Specialization of `multiplicity.something` to a prime in the naturals. Avoids having to provide `p ≠ 1` and other trivialities, along with translating between `prime` and `nat.prime`. ## Tags Legendre, p-adic -/ open finset nat multiplicity open_locale big_operators nat namespace nat /-- The multiplicity of `m` in `n` is the number of positive natural numbers `i` such that `m ^ i` divides `n`. This set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log m n`. -/ lemma multiplicity_eq_card_pow_dvd {m n b : ℕ} (hm : m ≠ 1) (hn : 0 < n) (hb : log m n < b): multiplicity m n = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card := calc multiplicity m n = ↑(Ico 1 $ ((multiplicity m n).get (finite_nat_iff.2 ⟨hm, hn⟩) + 1)).card : by simp ... = ↑((finset.Ico 1 b).filter (λ i, m ^ i ∣ n)).card : congr_arg coe $ congr_arg card $ finset.ext $ λ i, begin rw [mem_filter, mem_Ico, mem_Ico, lt_succ_iff, ←@part_enat.coe_le_coe i, part_enat.coe_get, ←pow_dvd_iff_le_multiplicity, and.right_comm], refine (and_iff_left_of_imp (λ h, lt_of_le_of_lt _ hb)).symm, cases m, { rw [zero_pow, zero_dvd_iff] at h, exacts [(hn.ne' h.2).elim, h.1] }, exact le_log_of_pow_le (one_lt_iff_ne_zero_and_ne_one.2 ⟨m.succ_ne_zero, hm⟩) (le_of_dvd hn h.2) end namespace prime lemma multiplicity_one {p : ℕ} (hp : p.prime) : multiplicity p 1 = 0 := multiplicity.one_right hp.prime.not_unit lemma multiplicity_mul {p m n : ℕ} (hp : p.prime) : multiplicity p (m * n) = multiplicity p m + multiplicity p n := multiplicity.mul hp.prime lemma multiplicity_pow {p m n : ℕ} (hp : p.prime) : multiplicity p (m ^ n) = n • (multiplicity p m) := multiplicity.pow hp.prime lemma multiplicity_self {p : ℕ} (hp : p.prime) : multiplicity p p = 1 := multiplicity_self hp.prime.not_unit hp.ne_zero lemma multiplicity_pow_self {p n : ℕ} (hp : p.prime) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.prime.not_unit n /-- **Legendre's Theorem** The multiplicity of a prime in `n!` is the sum of the quotients `n / p ^ i`. This sum is expressed over the finset `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_factorial {p : ℕ} (hp : p.prime) : ∀ {n b : ℕ}, log p n < b → multiplicity p n! = (∑ i in Ico 1 b, n / p ^ i : ℕ) | 0 b hb := by simp [Ico, hp.multiplicity_one] | (n+1) b hb := calc multiplicity p (n+1)! = multiplicity p n! + multiplicity p (n+1) : by rw [factorial_succ, hp.multiplicity_mul, add_comm] ... = (∑ i in Ico 1 b, n / p ^ i : ℕ) + ((finset.Ico 1 b).filter (λ i, p ^ i ∣ n+1)).card : by rw [multiplicity_factorial ((log_mono_right $ le_succ _).trans_lt hb), ← multiplicity_eq_card_pow_dvd hp.ne_one (succ_pos _) hb] ... = (∑ i in Ico 1 b, (n / p ^ i + if p^i ∣ n+1 then 1 else 0) : ℕ) : by { rw [sum_add_distrib, sum_boole], simp } ... = (∑ i in Ico 1 b, (n + 1) / p ^ i : ℕ) : congr_arg coe $ finset.sum_congr rfl $ λ _ _, (succ_div _ _).symm /-- The multiplicity of `p` in `(p * (n + 1))!` is one more than the sum of the multiplicities of `p` in `(p * n)!` and `n + 1`. -/ lemma multiplicity_factorial_mul_succ {n p : ℕ} (hp : p.prime) : multiplicity p (p * (n + 1))! = multiplicity p (p * n)! + multiplicity p (n + 1) + 1 := begin have hp' := hp.prime, have h0 : 2 ≤ p := hp.two_le, have h1 : 1 ≤ p * n + 1 := nat.le_add_left _ _, have h2 : p * n + 1 ≤ p * (n + 1), linarith, have h3 : p * n + 1 ≤ p * (n + 1) + 1, linarith, have hm : multiplicity p (p * n)! ≠ ⊤, { rw [ne.def, eq_top_iff_not_finite, not_not, finite_nat_iff], exact ⟨hp.ne_one, factorial_pos _⟩ }, revert hm, have h4 : ∀ m ∈ Ico (p * n + 1) (p * (n + 1)), multiplicity p m = 0, { intros m hm, rw [multiplicity_eq_zero, ← not_dvd_iff_between_consec_multiples _ hp.pos], rw [mem_Ico] at hm, exact ⟨n, lt_of_succ_le hm.1, hm.2⟩ }, simp_rw [← prod_Ico_id_eq_factorial, multiplicity.finset.prod hp', ← sum_Ico_consecutive _ h1 h3, add_assoc], intro h, rw [part_enat.add_left_cancel_iff h, sum_Ico_succ_top h2, multiplicity.mul hp', hp.multiplicity_self, sum_congr rfl h4, sum_const_zero, zero_add, add_comm (1 : part_enat)] end /-- The multiplicity of `p` in `(p * n)!` is `n` more than that of `n!`. -/ lemma multiplicity_factorial_mul {n p : ℕ} (hp : p.prime) : multiplicity p (p * n)! = multiplicity p n! + n := begin induction n with n ih, { simp }, { simp only [succ_eq_add_one, multiplicity.mul, hp, hp.prime, ih, multiplicity_factorial_mul_succ, ←add_assoc, nat.cast_one, nat.cast_add, factorial_succ], congr' 1, rw [add_comm, add_assoc] } end /-- A prime power divides `n!` iff it is at most the sum of the quotients `n / p ^ i`. This sum is expressed over the set `Ico 1 b` where `b` is any bound greater than `log p n` -/ lemma pow_dvd_factorial_iff {p : ℕ} {n r b : ℕ} (hp : p.prime) (hbn : log p n < b) : p ^ r ∣ n! ↔ r ≤ ∑ i in Ico 1 b, n / p ^ i := by rw [← part_enat.coe_le_coe, ← hp.multiplicity_factorial hbn, ← pow_dvd_iff_le_multiplicity] lemma multiplicity_factorial_le_div_pred {p : ℕ} (hp : p.prime) (n : ℕ) : multiplicity p n! ≤ (n/(p - 1) : ℕ) := begin rw [hp.multiplicity_factorial (lt_succ_self _), part_enat.coe_le_coe], exact nat.geom_sum_Ico_le hp.two_le _ _, end lemma multiplicity_choose_aux {p n b k : ℕ} (hp : p.prime) (hkn : k ≤ n) : ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, k / p ^ i + ∑ i in finset.Ico 1 b, (n - k) / p ^ i + ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := calc ∑ i in finset.Ico 1 b, n / p ^ i = ∑ i in finset.Ico 1 b, (k + (n - k)) / p ^ i : by simp only [add_tsub_cancel_of_le hkn] ... = ∑ i in finset.Ico 1 b, (k / p ^ i + (n - k) / p ^ i + if p ^ i ≤ k % p ^ i + (n - k) % p ^ i then 1 else 0) : by simp only [nat.add_div (pow_pos hp.pos _)] ... = _ : by simp [sum_add_distrib, sum_boole] /-- The multiplicity of `p` in `choose n k` is the number of carries when `k` and `n - k` are added in base `p`. The set is expressed by filtering `Ico 1 b` where `b` is any bound greater than `log p n`. -/ lemma multiplicity_choose {p n k b : ℕ} (hp : p.prime) (hkn : k ≤ n) (hnb : log p n < b) : multiplicity p (choose n k) = ((Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card := have h₁ : multiplicity p (choose n k) + multiplicity p (k! * (n - k)!) = ((finset.Ico 1 b).filter (λ i, p ^ i ≤ k % p ^ i + (n - k) % p ^ i)).card + multiplicity p (k! * (n - k)!), begin rw [← hp.multiplicity_mul, ← mul_assoc, choose_mul_factorial_mul_factorial hkn, hp.multiplicity_factorial hnb, hp.multiplicity_mul, hp.multiplicity_factorial ((log_mono_right hkn).trans_lt hnb), hp.multiplicity_factorial (lt_of_le_of_lt (log_mono_right tsub_le_self) hnb), multiplicity_choose_aux hp hkn], simp [add_comm], end, (part_enat.add_right_cancel_iff (part_enat.ne_top_iff_dom.2 $ by exact finite_nat_iff.2 ⟨ne_of_gt hp.one_lt, mul_pos (factorial_pos k) (factorial_pos (n - k))⟩)).1 h₁ /-- A lower bound on the multiplicity of `p` in `choose n k`. -/ lemma multiplicity_le_multiplicity_choose_add {p : ℕ} (hp : p.prime) : ∀ (n k : ℕ), multiplicity p n ≤ multiplicity p (choose n k) + multiplicity p k | _ 0 := by simp | 0 (_+1) := by simp | (n+1) (k+1) := begin rw ← hp.multiplicity_mul, refine multiplicity_le_multiplicity_of_dvd_right _, rw [← succ_mul_choose_eq], exact dvd_mul_right _ _ end variables {p n k : ℕ} lemma multiplicity_choose_prime_pow_add_multiplicity (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : k ≠ 0) : multiplicity p (choose (p ^ n) k) + multiplicity p k = n := le_antisymm (have hdisj : disjoint ((Ico 1 n.succ).filter (λ i, p ^ i ≤ k % p ^ i + (p ^ n - k) % p ^ i)) ((Ico 1 n.succ).filter (λ i, p ^ i ∣ k)), by simp [disjoint_right, *, dvd_iff_mod_eq_zero, nat.mod_lt _ (pow_pos hp.pos _)] {contextual := tt}, begin rw [multiplicity_choose hp hkn (lt_succ_self _), multiplicity_eq_card_pow_dvd (ne_of_gt hp.one_lt) hk0.bot_lt (lt_succ_of_le (log_mono_right hkn)), ← nat.cast_add, part_enat.coe_le_coe, log_pow hp.one_lt, ← card_disjoint_union hdisj, filter_union_right], have filter_le_Ico := (Ico 1 n.succ).card_filter_le _, rwa card_Ico 1 n.succ at filter_le_Ico, end) (by rw [← hp.multiplicity_pow_self]; exact multiplicity_le_multiplicity_choose_add hp _ _) lemma multiplicity_choose_prime_pow {p n k : ℕ} (hp : p.prime) (hkn : k ≤ p ^ n) (hk0 : k ≠ 0) : multiplicity p (choose (p ^ n) k) = ↑(n - (multiplicity p k).get (finite_nat_iff.2 ⟨hp.ne_one, hk0.bot_lt⟩)) := part_enat.eq_coe_sub_of_add_eq_coe $ multiplicity_choose_prime_pow_add_multiplicity hp hkn hk0 lemma dvd_choose_pow (hp : prime p) (hk : k ≠ 0) (hkp : k ≠ p ^ n) : p ∣ (p ^ n).choose k := begin obtain hkp | hkp := hkp.symm.lt_or_lt, { simp [choose_eq_zero_of_lt hkp] }, refine multiplicity_ne_zero.1 (λ h, hkp.not_le $ nat.le_of_dvd hk.bot_lt _), have H := hp.multiplicity_choose_prime_pow_add_multiplicity hkp.le hk, rw [h, zero_add, eq_coe_iff] at H, exact H.1, end lemma dvd_choose_pow_iff (hp : prime p) : p ∣ (p ^ n).choose k ↔ k ≠ 0 ∧ k ≠ p ^ n := by refine ⟨λ h, ⟨_, _⟩, λ h, dvd_choose_pow hp h.1 h.2⟩; rintro rfl; simpa [hp.ne_one] using h end prime lemma multiplicity_two_factorial_lt : ∀ {n : ℕ} (h : n ≠ 0), multiplicity 2 n! < n := begin have h2 := prime_two.prime, refine binary_rec _ _, { contradiction }, { intros b n ih h, by_cases hn : n = 0, { subst hn, simp at h, simp [h, one_right h2.not_unit] }, have : multiplicity 2 (2 * n)! < (2 * n : ℕ), { rw [prime_two.multiplicity_factorial_mul], refine (part_enat.add_lt_add_right (ih hn) (part_enat.coe_ne_top _)).trans_le _, rw [two_mul], norm_cast }, cases b, { simpa [bit0_eq_two_mul n] }, { suffices : multiplicity 2 (2 * n + 1) + multiplicity 2 (2 * n)! < ↑(2 * n) + 1, { simpa [succ_eq_add_one, multiplicity.mul, h2, prime_two, nat.bit1_eq_succ_bit0, bit0_eq_two_mul n] }, rw [multiplicity_eq_zero.2 (two_not_dvd_two_mul_add_one n), zero_add], refine this.trans _, exact_mod_cast lt_succ_self _ }} end end nat
0ecc56539ed0b1fe001cd34e5922ae49b9b5044f
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/typevec.lean
55224d6e7ef0b5d51e3a6d33ad4c9f7095c5c8cd
[ "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
24,599
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon -/ import data.fin.fin2 import logic.function.basic import tactic.basic /-! # Tuples of types, and their categorical structure. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Features * `typevec n` - n-tuples of types * `α ⟹ β` - n-tuples of maps * `f ⊚ g` - composition Also, support functions for operating with n-tuples of types, such as: * `append1 α β` - append type `β` to n-tuple `α` to obtain an (n+1)-tuple * `drop α` - drops the last element of an (n+1)-tuple * `last α` - returns the last element of an (n+1)-tuple * `append_fun f g` - appends a function g to an n-tuple of functions * `drop_fun f` - drops the last function from an n+1-tuple * `last_fun f` - returns the last function of a tuple. Since e.g. `append1 α.drop α.last` is propositionally equal to `α` but not definitionally equal to it, we need support functions and lemmas to mediate between constructions. -/ universes u v w /-- n-tuples of types, as a category -/ def typevec (n : ℕ) := fin2 n → Type* instance {n} : inhabited (typevec.{u} n) := ⟨ λ _, punit ⟩ namespace typevec variable {n : ℕ} /-- arrow in the category of `typevec` -/ def arrow (α β : typevec n) := Π i : fin2 n, α i → β i localized "infixl (name := typevec.arrow) ` ⟹ `:40 := typevec.arrow" in mvfunctor instance arrow.inhabited (α β : typevec n) [Π i, inhabited (β i)] : inhabited (α ⟹ β) := ⟨ λ _ _, default ⟩ /-- identity of arrow composition -/ def id {α : typevec n} : α ⟹ α := λ i x, x /-- arrow composition in the category of `typevec` -/ def comp {α β γ : typevec n} (g : β ⟹ γ) (f : α ⟹ β) : α ⟹ γ := λ i x, g i (f i x) localized "infixr (name := typevec.comp) ` ⊚ `:80 := typevec.comp" in mvfunctor -- type as \oo @[simp] theorem id_comp {α β : typevec n} (f : α ⟹ β) : id ⊚ f = f := rfl @[simp] theorem comp_id {α β : typevec n} (f : α ⟹ β) : f ⊚ id = f := rfl theorem comp_assoc {α β γ δ : typevec n} (h : γ ⟹ δ) (g : β ⟹ γ) (f : α ⟹ β) : (h ⊚ g) ⊚ f = h ⊚ g ⊚ f := rfl /-- Support for extending a typevec by one element. -/ def append1 (α : typevec n) (β : Type*) : typevec (n+1) | (fin2.fs i) := α i | fin2.fz := β infixl (name := typevec.append1) ` ::: `:67 := append1 /-- retain only a `n-length` prefix of the argument -/ def drop (α : typevec.{u} (n+1)) : typevec n := λ i, α i.fs /-- take the last value of a `(n+1)-length` vector -/ def last (α : typevec.{u} (n+1)) : Type* := α fin2.fz instance last.inhabited (α : typevec (n+1)) [inhabited (α fin2.fz)] : inhabited (last α) := ⟨show α fin2.fz, from default⟩ theorem drop_append1 {α : typevec n} {β : Type*} {i : fin2 n} : drop (append1 α β) i = α i := rfl theorem drop_append1' {α : typevec n} {β : Type*} : drop (append1 α β) = α := by ext; apply drop_append1 theorem last_append1 {α : typevec n} {β : Type*} : last (append1 α β) = β := rfl @[simp] theorem append1_drop_last (α : typevec (n+1)) : append1 (drop α) (last α) = α := funext $ λ i, by cases i; refl /-- cases on `(n+1)-length` vectors -/ @[elab_as_eliminator] def append1_cases {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (γ) : C γ := by rw [← @append1_drop_last _ γ]; apply H @[simp] theorem append1_cases_append1 {C : typevec (n+1) → Sort u} (H : ∀ α β, C (append1 α β)) (α β) : @append1_cases _ C H (append1 α β) = H α β := rfl /-- append an arrow and a function for arbitrary source and target type vectors -/ def split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : α ⟹ α' | (fin2.fs i) := f i | fin2.fz := g /-- append an arrow and a function as well as their respective source and target types / typevecs -/ def append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : append1 α β ⟹ append1 α' β' := split_fun f g infixl (name := typevec.append_fun) ` ::: ` := append_fun /-- split off the prefix of an arrow -/ def drop_fun {α β : typevec (n+1)} (f : α ⟹ β) : drop α ⟹ drop β := λ i, f i.fs /-- split off the last function of an arrow -/ def last_fun {α β : typevec (n+1)} (f : α ⟹ β) : last α → last β := f fin2.fz /-- arrow in the category of `0-length` vectors -/ def nil_fun {α : typevec 0} {β : typevec 0} : α ⟹ β := λ i, fin2.elim0 i theorem eq_of_drop_last_eq {α β : typevec (n+1)} {f g : α ⟹ β} (h₀ : drop_fun f = drop_fun g) (h₁ : last_fun f = last_fun g) : f = g := by replace h₀ := congr_fun h₀; ext1 ⟨⟩; apply_assumption @[simp] theorem drop_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : drop_fun (split_fun f g) = f := rfl /-- turn an equality into an arrow -/ def arrow.mp {α β : typevec n} (h : α = β) : α ⟹ β | i := eq.mp (congr_fun h _) /-- turn an equality into an arrow, with reverse direction -/ def arrow.mpr {α β : typevec n} (h : α = β) : β ⟹ α | i := eq.mpr (congr_fun h _) /-- decompose a vector into its prefix appended with its last element -/ def to_append1_drop_last {α : typevec (n+1)} : α ⟹ drop α ::: last α := arrow.mpr (append1_drop_last _) /-- stitch two bits of a vector back together -/ def from_append1_drop_last {α : typevec (n+1)} : drop α ::: last α ⟹ α := arrow.mp (append1_drop_last _) @[simp] theorem last_fun_split_fun {α α' : typevec (n+1)} (f : drop α ⟹ drop α') (g : last α → last α') : last_fun (split_fun f g) = g := rfl @[simp] theorem drop_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : drop_fun (f ::: g) = f := rfl @[simp] theorem last_fun_append_fun {α α' : typevec n} {β β' : Type*} (f : α ⟹ α') (g : β → β') : last_fun (f ::: g) = g := rfl theorem split_drop_fun_last_fun {α α' : typevec (n+1)} (f : α ⟹ α') : split_fun (drop_fun f) (last_fun f) = f := eq_of_drop_last_eq rfl rfl theorem split_fun_inj {α α' : typevec (n+1)} {f f' : drop α ⟹ drop α'} {g g' : last α → last α'} (H : split_fun f g = split_fun f' g') : f = f' ∧ g = g' := by rw [← drop_fun_split_fun f g, H, ← last_fun_split_fun f g, H]; simp theorem append_fun_inj {α α' : typevec n} {β β' : Type*} {f f' : α ⟹ α'} {g g' : β → β'} : f ::: g = f' ::: g' → f = f' ∧ g = g' := split_fun_inj theorem split_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : drop α₀ ⟹ drop α₁) (f₁ : drop α₁ ⟹ drop α₂) (g₀ : last α₀ → last α₁) (g₁ : last α₁ → last α₂) : split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) = split_fun f₁ g₁ ⊚ split_fun f₀ g₀ := eq_of_drop_last_eq rfl rfl theorem append_fun_comp_split_fun {α γ : typevec n} {β δ : Type*} {ε : typevec (n + 1)} (f₀ : drop ε ⟹ α) (f₁ : α ⟹ γ) (g₀ : last ε → β) (g₁ : β → δ) : append_fun f₁ g₁ ⊚ split_fun f₀ g₀ = split_fun (f₁ ⊚ f₀) (g₁ ∘ g₀) := (split_fun_comp _ _ _ _).symm lemma append_fun_comp {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : f₁ ⊚ f₀ ::: g₁ ∘ g₀ = (f₁ ::: g₁) ⊚ (f₀ ::: g₀) := eq_of_drop_last_eq rfl rfl lemma append_fun_comp' {α₀ α₁ α₂ : typevec n} {β₀ β₁ β₂ : Type*} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : (f₁ ::: g₁) ⊚ (f₀ ::: g₀) = f₁ ⊚ f₀ ::: g₁ ∘ g₀ := eq_of_drop_last_eq rfl rfl lemma nil_fun_comp {α₀ : typevec 0} (f₀ : α₀ ⟹ fin2.elim0) : nil_fun ⊚ f₀ = f₀ := funext $ λ x, fin2.elim0 x theorem append_fun_comp_id {α : typevec n} {β₀ β₁ β₂ : Type*} (g₀ : β₀ → β₁) (g₁ : β₁ → β₂) : @id _ α ::: g₁ ∘ g₀ = (id ::: g₁) ⊚ (id ::: g₀) := eq_of_drop_last_eq rfl rfl @[simp] theorem drop_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : drop_fun (f₁ ⊚ f₀) = drop_fun f₁ ⊚ drop_fun f₀ := rfl @[simp] theorem last_fun_comp {α₀ α₁ α₂ : typevec (n+1)} (f₀ : α₀ ⟹ α₁) (f₁ : α₁ ⟹ α₂) : last_fun (f₁ ⊚ f₀) = last_fun f₁ ∘ last_fun f₀ := rfl theorem append_fun_aux {α α' : typevec n} {β β' : Type*} (f : α ::: β ⟹ α' ::: β') : drop_fun f ::: last_fun f = f := eq_of_drop_last_eq rfl rfl theorem append_fun_id_id {α : typevec n} {β : Type*} : @typevec.id n α ::: @_root_.id β = typevec.id := eq_of_drop_last_eq rfl rfl instance subsingleton0 : subsingleton (typevec 0) := ⟨ λ a b, funext $ λ a, fin2.elim0 a ⟩ local prefix `♯`:0 := cast (by try { simp }; congr' 1; try { simp }) /-- cases distinction for 0-length type vector -/ protected def cases_nil {β : typevec 0 → Sort*} (f : β fin2.elim0) : Π v, β v := λ v, ♯ f /-- cases distinction for (n+1)-length type vector -/ protected def cases_cons (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) : Π v, β v := λ v : typevec (n+1), ♯ f v.last v.drop protected lemma cases_nil_append1 {β : typevec 0 → Sort*} (f : β fin2.elim0) : typevec.cases_nil f fin2.elim0 = f := rfl protected lemma cases_cons_append1 (n : ℕ) {β : typevec (n+1) → Sort*} (f : Π t (v : typevec n), β (v ::: t)) (v : typevec n) (α) : typevec.cases_cons n f (v ::: α) = f α v := rfl /-- cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₃ {β : Π v v' : typevec 0, v ⟹ v' → Sort*} (f : β fin2.elim0 fin2.elim0 nil_fun) : Π v v' fs, β v v' fs := λ v v' fs, begin refine cast _ f; congr' 1; ext; try { intros; casesm fin2 0 }, refl end /-- cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₃ (n : ℕ) {β : Π v v' : typevec (n+1), v ⟹ v' → Sort*} (F : Π t t' (f : t → t') (v v' : typevec n) (fs : v ⟹ v'), β (v ::: t) (v' ::: t') (fs ::: f)) : Π v v' fs, β v v' fs := begin intros v v', rw [←append1_drop_last v, ←append1_drop_last v'], intro fs, rw [←split_drop_fun_last_fun fs], apply F end /-- specialized cases distinction for an arrow in the category of 0-length type vectors -/ def typevec_cases_nil₂ {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : Π f, β f := begin intro g, have : g = nil_fun, ext ⟨ ⟩, rw this, exact f end /-- specialized cases distinction for an arrow in the category of (n+1)-length type vectors -/ def typevec_cases_cons₂ (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) : Π fs, β fs := begin intro fs, rw [←split_drop_fun_last_fun fs], apply F end lemma typevec_cases_nil₂_append_fun {β : fin2.elim0 ⟹ fin2.elim0 → Sort*} (f : β nil_fun) : typevec_cases_nil₂ f nil_fun = f := rfl lemma typevec_cases_cons₂_append_fun (n : ℕ) (t t' : Type*) (v v' : typevec (n)) {β : (v ::: t) ⟹ (v' ::: t') → Sort*} (F : Π (f : t → t') (fs : v ⟹ v'), β (fs ::: f)) (f fs) : typevec_cases_cons₂ n t t' v v' F (fs ::: f) = F f fs := rfl /- for lifting predicates and relations -/ /-- `pred_last α p x` predicates `p` of the last element of `x : α.append1 β`. -/ def pred_last (α : typevec n) {β : Type*} (p : β → Prop) : Π ⦃i⦄, (α.append1 β) i → Prop | (fin2.fs i) := λ x, true | fin2.fz := p /-- `rel_last α r x y` says that `p` the last elements of `x y : α.append1 β` are related by `r` and all the other elements are equal. -/ def rel_last (α : typevec n) {β γ : Type*} (r : β → γ → Prop) : Π ⦃i⦄, (α.append1 β) i → (α.append1 γ) i → Prop | (fin2.fs i) := eq | fin2.fz := r section liftp' open nat /-- `repeat n t` is a `n-length` type vector that contains `n` occurences of `t` -/ def repeat : Π (n : ℕ) (t : Sort*), typevec n | 0 t := fin2.elim0 | (nat.succ i) t := append1 (repeat i t) t /-- `prod α β` is the pointwise product of the components of `α` and `β` -/ def prod : Π {n} (α β : typevec.{u} n), typevec n | 0 α β := fin2.elim0 | (n+1) α β := prod (drop α) (drop β) ::: (last α × last β) localized "infix (name := typevec.prod) ` ⊗ `:45 := typevec.prod" in mvfunctor /-- `const x α` is an arrow that ignores its source and constructs a `typevec` that contains nothing but `x` -/ protected def const {β} (x : β) : Π {n} (α : typevec n), α ⟹ repeat _ β | (succ n) α (fin2.fs i) := const (drop α) _ | (succ n) α fin2.fz := λ _, x open function (uncurry) /-- vector of equality on a product of vectors -/ def repeat_eq : Π {n} (α : typevec n), α ⊗ α ⟹ repeat _ Prop | 0 α := nil_fun | (succ n) α := repeat_eq (drop α) ::: uncurry eq lemma const_append1 {β γ} (x : γ) {n} (α : typevec n) : typevec.const x (α ::: β) = append_fun (typevec.const x α) (λ _, x) := by ext i : 1; cases i; refl lemma eq_nil_fun {α β : typevec 0} (f : α ⟹ β) : f = nil_fun := by ext x; cases x lemma id_eq_nil_fun {α : typevec 0} : @id _ α = nil_fun := by ext x; cases x lemma const_nil {β} (x : β) (α : typevec 0) : typevec.const x α = nil_fun := by ext i : 1; cases i; refl @[typevec] lemma repeat_eq_append1 {β} {n} (α : typevec n) : repeat_eq (α ::: β) = split_fun (repeat_eq α) (uncurry eq) := by induction n; refl @[typevec] lemma repeat_eq_nil (α : typevec 0) : repeat_eq α = nil_fun := by ext i : 1; cases i; refl /-- predicate on a type vector to constrain only the last object -/ def pred_last' (α : typevec n) {β : Type*} (p : β → Prop) : α ::: β ⟹ repeat (n+1) Prop := split_fun (typevec.const true α) p /-- predicate on the product of two type vectors to constrain only their last object -/ def rel_last' (α : typevec n) {β : Type*} (p : β → β → Prop) : (α ::: β ⊗ α ::: β) ⟹ repeat (n+1) Prop := split_fun (repeat_eq α) (uncurry p) /-- given `F : typevec.{u} (n+1) → Type u`, `curry F : Type u → typevec.{u} → Type u`, i.e. its first argument can be fed in separately from the rest of the vector of arguments -/ def curry (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) : Type* := F (β ::: α) instance curry.inhabited (F : typevec.{u} (n+1) → Type*) (α : Type u) (β : typevec.{u} n) [I : inhabited (F $ β ::: α)]: inhabited (curry F α β) := I /-- arrow to remove one element of a `repeat` vector -/ def drop_repeat (α : Type*) : Π {n}, drop (repeat (succ n) α) ⟹ repeat n α | (succ n) (fin2.fs i) := drop_repeat i | (succ n) fin2.fz := _root_.id /-- projection for a repeat vector -/ def of_repeat {α : Sort*} : Π {n i}, repeat n α i → α | ._ fin2.fz := _root_.id | ._ (fin2.fs i) := @of_repeat _ i lemma const_iff_true {α : typevec n} {i x p} : of_repeat (typevec.const p α i x) ↔ p := by induction i; [refl, erw [typevec.const,@i_ih (drop α) x]] -- variables {F : typevec.{u} n → Type*} [mvfunctor F] variables {α β γ : typevec.{u} n} variables (p : α ⟹ repeat n Prop) (r : α ⊗ α ⟹ repeat n Prop) /-- left projection of a `prod` vector -/ def prod.fst : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ α | (succ n) α β (fin2.fs i) := @prod.fst _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.fst /-- right projection of a `prod` vector -/ def prod.snd : Π {n} {α β : typevec.{u} n}, α ⊗ β ⟹ β | (succ n) α β (fin2.fs i) := @prod.snd _ (drop α) (drop β) i | (succ n) α β fin2.fz := _root_.prod.snd /-- introduce a product where both components are the same -/ def prod.diag : Π {n} {α : typevec.{u} n}, α ⟹ α ⊗ α | (succ n) α (fin2.fs i) x := @prod.diag _ (drop α) _ x | (succ n) α fin2.fz x := (x,x) /-- constructor for `prod` -/ def prod.mk : Π {n} {α β : typevec.{u} n} (i : fin2 n), α i → β i → (α ⊗ β) i | (succ n) α β (fin2.fs i) := prod.mk i | (succ n) α β fin2.fz := _root_.prod.mk @[simp] lemma prod_fst_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.fst i (prod.mk i a b) = a := by induction i; simp [prod.fst, prod.mk, *] at * @[simp] lemma prod_snd_mk {α β : typevec n} (i : fin2 n) (a : α i) (b : β i) : typevec.prod.snd i (prod.mk i a b) = b := by induction i; simp [prod.snd, prod.mk, *] at * /-- `prod` is functorial -/ protected def prod.map : Π {n} {α α' β β' : typevec.{u} n}, (α ⟹ β) → (α' ⟹ β') → α ⊗ α' ⟹ β ⊗ β' | (succ n) α α' β β' x y (fin2.fs i) a := @prod.map _ (drop α) (drop α') (drop β) (drop β') (drop_fun x) (drop_fun y) _ a | (succ n) α α' β β' x y fin2.fz a := (x _ a.1,y _ a.2) localized "infix (name := typevec.prod.map) ` ⊗' `:45 := typevec.prod.map" in mvfunctor theorem fst_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.fst ⊚ (f ⊗' g) = f ⊚ typevec.prod.fst := by ext i; induction i; [refl, apply i_ih] theorem snd_prod_mk {α α' β β' : typevec n} (f : α ⟹ β) (g : α' ⟹ β') : typevec.prod.snd ⊚ (f ⊗' g) = g ⊚ typevec.prod.snd := by ext i; induction i; [refl, apply i_ih] theorem fst_diag {α : typevec n} : typevec.prod.fst ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] theorem snd_diag {α : typevec n} : typevec.prod.snd ⊚ (prod.diag : α ⟹ _) = id := by ext i; induction i; [refl, apply i_ih] lemma repeat_eq_iff_eq {α : typevec n} {i x y} : of_repeat (repeat_eq α i (prod.mk _ x y)) ↔ x = y := by induction i; [refl, erw [repeat_eq,@i_ih (drop α) x y]] /-- given a predicate vector `p` over vector `α`, `subtype_ p` is the type of vectors that contain an `α` that satisfies `p` -/ def subtype_ : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), typevec n | ._ α p fin2.fz := _root_.subtype (λ x, p fin2.fz x) | ._ α p (fin2.fs i) := subtype_ (drop_fun p) i /-- projection on `subtype_` -/ def subtype_val : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ α | (succ n) α p (fin2.fs i) := @subtype_val n _ _ i | (succ n) α p fin2.fz := _root_.subtype.val /-- arrow that rearranges the type of `subtype_` to turn a subtype of vector into a vector of subtypes -/ def to_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), (λ (i : fin2 n), { x // of_repeat $ p i x }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype (drop_fun p) i x | (succ n) α p fin2.fz x := x /-- arrow that rearranges the type of `subtype_` to turn a vector of subtypes into a subtype of vector -/ def of_subtype : Π {n} {α : typevec.{u} n} (p : α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x // of_repeat $ p i x }) | (succ n) α p (fin2.fs i) x := of_subtype _ i x | (succ n) α p fin2.fz x := x /-- similar to `to_subtype` adapted to relations (i.e. predicate on product) -/ def to_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) ⟹ subtype_ p | (succ n) α p (fin2.fs i) x := to_subtype' (drop_fun p) i x | (succ n) α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `of_subtype` adapted to relations (i.e. predicate on product) -/ def of_subtype' : Π {n} {α : typevec.{u} n} (p : α ⊗ α ⟹ repeat n Prop), subtype_ p ⟹ (λ (i : fin2 n), { x : α i × α i // of_repeat $ p i (prod.mk _ x.1 x.2) }) | ._ α p (fin2.fs i) x := of_subtype' _ i x | ._ α p fin2.fz x := ⟨x.val,cast (by congr; simp [prod.mk]) x.property⟩ /-- similar to `diag` but the target vector is a `subtype_` guaranteeing the equality of the components -/ def diag_sub : Π {n} {α : typevec.{u} n}, α ⟹ subtype_ (repeat_eq α) | (succ n) α (fin2.fs i) x := @diag_sub _ (drop α) _ x | (succ n) α fin2.fz x := ⟨(x,x), rfl⟩ lemma subtype_val_nil {α : typevec.{u} 0} (ps : α ⟹ repeat 0 Prop) : typevec.subtype_val ps = nil_fun := funext $ by rintro ⟨ ⟩; refl lemma diag_sub_val {n} {α : typevec.{u} n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by ext i; induction i; [refl, apply i_ih] lemma prod_id : Π {n} {α β : typevec.{u} n}, (id ⊗' id) = (id : α ⊗ β ⟹ _) := begin intros, ext i a, induction i, { cases a, refl }, { apply i_ih }, end lemma append_prod_append_fun {n} {α α' β β' : typevec.{u} n} {φ φ' ψ ψ' : Type u} {f₀ : α ⟹ α'} {g₀ : β ⟹ β'} {f₁ : φ → φ'} {g₁ : ψ → ψ'} : (f₀ ⊗' g₀) ::: _root_.prod.map f₁ g₁ = ((f₀ ::: f₁) ⊗' (g₀ ::: g₁)) := by ext i a; cases i; [cases a, skip]; refl end liftp' @[simp] lemma drop_fun_diag {α} : drop_fun (@prod.diag (n+1) α) = prod.diag := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma drop_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (subtype_val p) = subtype_val _ := rfl @[simp] lemma last_fun_subtype_val {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (subtype_val p) = subtype.val := rfl @[simp] lemma drop_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (to_subtype p) = to_subtype _ := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma last_fun_to_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (to_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma drop_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : drop_fun (of_subtype p) = of_subtype _ := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma last_fun_of_subtype {α} (p : α ⟹ repeat (n+1) Prop) : last_fun (of_subtype p) = _root_.id := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma drop_fun_rel_last {α : typevec n} {β} (R : β → β → Prop) : drop_fun (rel_last' α R) = repeat_eq α := rfl attribute [simp] drop_append1' open_locale mvfunctor @[simp] lemma drop_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : drop_fun (f ⊗' f') = (drop_fun f ⊗' drop_fun f') := by { ext i : 2, induction i; simp [drop_fun, *]; refl } @[simp] lemma last_fun_prod {α α' β β' : typevec (n+1)} (f : α ⟹ β) (f' : α' ⟹ β') : last_fun (f ⊗' f') = _root_.prod.map (last_fun f) (last_fun f') := by { ext i : 1, induction i; simp [last_fun, *]; refl } @[simp] lemma drop_fun_from_append1_drop_last {α : typevec (n+1)} : drop_fun (@from_append1_drop_last _ α) = id := rfl @[simp] lemma last_fun_from_append1_drop_last {α : typevec (n+1)} : last_fun (@from_append1_drop_last _ α) = _root_.id := rfl @[simp] lemma drop_fun_id {α : typevec (n+1)} : drop_fun (@typevec.id _ α) = id := rfl @[simp] lemma prod_map_id {α β : typevec n} : (@typevec.id _ α ⊗' @typevec.id _ β) = id := by { ext i : 2, induction i; simp only [typevec.prod.map, *, drop_fun_id], cases x, refl, refl } @[simp] lemma subtype_val_diag_sub {α : typevec n} : subtype_val (repeat_eq α) ⊚ diag_sub = prod.diag := by { clear_except, ext i, induction i; [refl, apply i_ih], } @[simp] lemma to_subtype_of_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : to_subtype p ⊚ of_subtype p = id := by ext i x; induction i; dsimp only [id, to_subtype, comp, of_subtype] at *; simp * @[simp] lemma subtype_val_to_subtype {α : typevec n} (p : α ⟹ repeat n Prop) : subtype_val p ⊚ to_subtype p = λ _, subtype.val := by ext i x; induction i; dsimp only [to_subtype, comp, subtype_val] at *; simp * @[simp] lemma to_subtype_of_subtype_assoc {α β : typevec n} (p : α ⟹ repeat n Prop) (f : β ⟹ subtype_ p) : @to_subtype n _ p ⊚ of_subtype _ ⊚ f = f := by rw [← comp_assoc,to_subtype_of_subtype]; simp @[simp] lemma to_subtype'_of_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : to_subtype' r ⊚ of_subtype' r = id := by ext i x; induction i; dsimp only [id, to_subtype', comp, of_subtype'] at *; simp [subtype.eta, *] lemma subtype_val_to_subtype' {α : typevec n} (r : α ⊗ α ⟹ repeat n Prop) : subtype_val r ⊚ to_subtype' r = λ i x, prod.mk i x.1.fst x.1.snd := by ext i x; induction i; dsimp only [id, to_subtype', comp, subtype_val, prod.mk] at *; simp * end typevec
64667e2ddab8ba2050d2b2d93192a30649ea9d4b
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/AIME_2021_I_5.lean
4969fe3b0ebab19a40425c6d4e9ef55e2141c688
[]
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
138
lean
import data.finset.basic theorem AIME_2021_I_5 (a b:ℕ)(h:(a-b)^2+a^2+(a+b)^2=a*b^2): (a=5∧ b=5)∨ (a=14∧b=7) := begin sorry end
f7836cd9615f64bc2265df5d4a328ed1a522912d
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/galois.lean
18a06e48dd8072a342e9fc9c2f9d6fae4e19ac75
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
12,774
lean
/- Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning and Patrick Lutz -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.field_theory.normal import Mathlib.field_theory.primitive_element import Mathlib.field_theory.fixed import Mathlib.ring_theory.power_basis import Mathlib.PostPort universes u_1 u_2 u_3 u_4 namespace Mathlib /-! # Galois Extensions In this file we define Galois extensions as extensions which are both separable and normal. ## Main definitions - `is_galois F E` where `E` is an extension of `F` - `fixed_field H` where `H : subgroup (E ≃ₐ[F] E)` - `fixing_subgroup K` where `K : intermediate_field F E` - `galois_correspondence` where `E/F` is finite dimensional and Galois ## Main results - `fixing_subgroup_of_fixed_field` : If `E/F` is finite dimensional (but not necessarily Galois) then `fixing_subgroup (fixed_field H) = H` - `fixed_field_of_fixing_subgroup`: If `E/F` is finite dimensional and Galois then `fixed_field (fixing_subgroup K) = K` Together, these two result prove the Galois correspondence - `is_galois.tfae` : Equivalent characterizations of a Galois extension of finite degree -/ /-- A field extension E/F is galois if it is both separable and normal -/ def is_galois (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] := is_separable F E ∧ normal F E namespace is_galois protected instance self (F : Type u_1) [field F] : is_galois F F := { left := Mathlib.is_separable_self F, right := Mathlib.normal_self F } protected instance to_is_separable (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [h : is_galois F E] : is_separable F E := and.left h protected instance to_normal (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [h : is_galois F E] : normal F E := and.right h theorem integral (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] [is_galois F E] (x : E) : is_integral F x := normal.is_integral F x theorem separable (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] [h : is_galois F E] (x : E) : polynomial.separable (minpoly F x) := and.right (and.left h x) -- TODO(Commelin, Browning): rename this to `splits` theorem normal (F : Type u_1) [field F] {E : Type u_2} [field E] [algebra F E] [is_galois F E] (x : E) : polynomial.splits (algebra_map F E) (minpoly F x) := normal.splits F x protected instance of_fixed_field (E : Type u_2) [field E] (G : Type u_1) [group G] [fintype G] [mul_semiring_action G E] : is_galois (↥(mul_action.fixed_points G E)) E := { left := fixed_points.separable G E, right := fixed_points.normal G E } theorem intermediate_field.adjoin_simple.card_aut_eq_findim (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [finite_dimensional F E] {α : E} (hα : is_integral F α) (h_sep : polynomial.separable (minpoly F α)) (h_splits : polynomial.splits (algebra_map F ↥(intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α))) (minpoly F α)) : fintype.card (alg_equiv F ↥(intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α)) ↥(intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α))) = finite_dimensional.findim F ↥(intermediate_field.adjoin F (intermediate_field.insert.insert ∅ α)) := sorry theorem card_aut_eq_findim (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [finite_dimensional F E] [h : is_galois F E] : fintype.card (alg_equiv F E E) = finite_dimensional.findim F E := sorry end is_galois theorem is_galois.tower_top_of_is_galois (F : Type u_1) (K : Type u_2) (E : Type u_3) [field F] [field K] [field E] [algebra F K] [algebra F E] [algebra K E] [is_scalar_tower F K E] [is_galois F E] : is_galois K E := { left := is_separable_tower_top_of_is_separable F K E, right := normal.tower_top_of_normal F K E } protected instance is_galois.tower_top_intermediate_field {F : Type u_1} {E : Type u_3} [field F] [field E] [algebra F E] (K : intermediate_field F E) [h : is_galois F E] : is_galois (↥K) E := is_galois.tower_top_of_is_galois F (↥K) E theorem is_galois_iff_is_galois_bot {F : Type u_1} {E : Type u_3} [field F] [field E] [algebra F E] : is_galois (↥⊥) E ↔ is_galois F E := { mp := fun (h : is_galois (↥⊥) E) => is_galois.tower_top_of_is_galois (↥⊥) F E, mpr := fun (h : is_galois F E) => is_galois.tower_top_intermediate_field ⊥ } theorem is_galois.of_alg_equiv {F : Type u_1} {E : Type u_3} [field F] [field E] {E' : Type u_4} [field E'] [algebra F E'] [algebra F E] [h : is_galois F E] (f : alg_equiv F E E') : is_galois F E' := { left := is_separable.of_alg_hom F E ↑(alg_equiv.symm f), right := normal.of_alg_equiv f } theorem alg_equiv.transfer_galois {F : Type u_1} {E : Type u_3} [field F] [field E] {E' : Type u_4} [field E'] [algebra F E'] [algebra F E] (f : alg_equiv F E E') : is_galois F E ↔ is_galois F E' := { mp := fun (h : is_galois F E) => is_galois.of_alg_equiv f, mpr := fun (h : is_galois F E') => is_galois.of_alg_equiv (alg_equiv.symm f) } theorem is_galois_iff_is_galois_top {F : Type u_1} {E : Type u_3} [field F] [field E] [algebra F E] : is_galois F ↥⊤ ↔ is_galois F E := alg_equiv.transfer_galois intermediate_field.top_equiv protected instance is_galois_bot {F : Type u_1} {E : Type u_3} [field F] [field E] [algebra F E] : is_galois F ↥⊥ := iff.mpr (alg_equiv.transfer_galois intermediate_field.bot_equiv) (is_galois.self F) namespace intermediate_field protected instance subgroup_action {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (H : subgroup (alg_equiv F E E)) : faithful_mul_semiring_action (↥H) E := faithful_mul_semiring_action.mk sorry /-- The intermediate_field fixed by a subgroup -/ def fixed_field {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (H : subgroup (alg_equiv F E E)) : intermediate_field F E := mk (mul_action.fixed_points (↥H) E) sorry sorry sorry sorry sorry sorry sorry theorem findim_fixed_field_eq_card {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (H : subgroup (alg_equiv F E E)) [finite_dimensional F E] : finite_dimensional.findim (↥(fixed_field H)) E = fintype.card ↥H := fixed_points.findim_eq_card (↥H) E /-- The subgroup fixing an intermediate_field -/ def fixing_subgroup {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : subgroup (alg_equiv F E E) := subgroup.mk (fun (ϕ : alg_equiv F E E) => ∀ (x : ↥K), coe_fn ϕ ↑x = ↑x) sorry sorry sorry theorem le_iff_le {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (H : subgroup (alg_equiv F E E)) (K : intermediate_field F E) : K ≤ fixed_field H ↔ H ≤ fixing_subgroup K := sorry /-- The fixing_subgroup of `K : intermediate_field F E` is isomorphic to `E ≃ₐ[K] E` -/ def fixing_subgroup_equiv {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : ↥(fixing_subgroup K) ≃* alg_equiv (↥K) E E := mul_equiv.mk (fun (ϕ : ↥(fixing_subgroup K)) => alg_equiv.of_bijective (alg_hom.mk ⇑ϕ sorry sorry sorry sorry sorry) sorry) (fun (ϕ : alg_equiv (↥K) E E) => { val := alg_equiv.of_bijective (alg_hom.mk ⇑ϕ sorry sorry sorry sorry sorry) sorry, property := sorry }) sorry sorry sorry theorem fixing_subgroup_fixed_field {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (H : subgroup (alg_equiv F E E)) [finite_dimensional F E] : fixing_subgroup (fixed_field H) = H := sorry protected instance fixed_field.algebra {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : algebra ↥K ↥(fixed_field (fixing_subgroup K)) := algebra.mk (ring_hom.mk (fun (x : ↥K) => { val := ↑x, property := sorry }) sorry sorry sorry sorry) sorry sorry protected instance fixed_field.is_scalar_tower {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) : is_scalar_tower (↥K) (↥(fixed_field (fixing_subgroup K))) E := is_scalar_tower.mk fun (_x : ↥K) (_x_1 : ↥(fixed_field (fixing_subgroup K))) (_x_2 : E) => mul_assoc (↑_x) (↑_x_1) _x_2 end intermediate_field namespace is_galois theorem fixed_field_fixing_subgroup {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) [finite_dimensional F E] [h : is_galois F E] : intermediate_field.fixed_field (intermediate_field.fixing_subgroup K) = K := sorry theorem card_fixing_subgroup_eq_findim {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] (K : intermediate_field F E) [finite_dimensional F E] [is_galois F E] : fintype.card ↥(intermediate_field.fixing_subgroup K) = finite_dimensional.findim (↥K) E := sorry /-- The Galois correspondence from intermediate fields to subgroups -/ def intermediate_field_equiv_subgroup {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] [is_galois F E] : intermediate_field F E ≃o order_dual (subgroup (alg_equiv F E E)) := rel_iso.mk (equiv.mk intermediate_field.fixing_subgroup intermediate_field.fixed_field sorry sorry) sorry /-- The Galois correspondence as a galois_insertion -/ def galois_insertion_intermediate_field_subgroup {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] : galois_insertion (⇑order_dual.to_dual ∘ intermediate_field.fixing_subgroup) (intermediate_field.fixed_field ∘ ⇑order_dual.to_dual) := galois_insertion.mk (fun (K : intermediate_field F E) (_x : function.comp intermediate_field.fixed_field (⇑order_dual.to_dual) (function.comp (⇑order_dual.to_dual) intermediate_field.fixing_subgroup K) ≤ K) => intermediate_field.fixing_subgroup K) sorry sorry sorry /-- The Galois correspondence as a galois_coinsertion -/ def galois_coinsertion_intermediate_field_subgroup {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] [is_galois F E] : galois_coinsertion (⇑order_dual.to_dual ∘ intermediate_field.fixing_subgroup) (intermediate_field.fixed_field ∘ ⇑order_dual.to_dual) := galois_coinsertion.mk (fun (H : order_dual (subgroup (alg_equiv F E E))) (_x : H ≤ function.comp (⇑order_dual.to_dual) intermediate_field.fixing_subgroup (function.comp intermediate_field.fixed_field (⇑order_dual.to_dual) H)) => intermediate_field.fixed_field H) sorry sorry sorry end is_galois namespace is_galois theorem is_separable_splitting_field (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [finite_dimensional F E] [h : is_galois F E] : ∃ (p : polynomial F), polynomial.separable p ∧ polynomial.is_splitting_field F E p := sorry theorem of_fixed_field_eq_bot (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [finite_dimensional F E] (h : intermediate_field.fixed_field ⊤ = ⊥) : is_galois F E := eq.mpr (id (Eq._oldrec (Eq.refl (is_galois F E)) (Eq.symm (propext is_galois_iff_is_galois_bot)))) (eq.mpr (id (Eq._oldrec (Eq.refl (is_galois (↥⊥) E)) (Eq.symm h))) (is_galois.of_fixed_field E ↥⊤)) theorem of_card_aut_eq_findim (F : Type u_1) [field F] (E : Type u_2) [field E] [algebra F E] [finite_dimensional F E] (h : fintype.card (alg_equiv F E E) = finite_dimensional.findim F E) : is_galois F E := sorry theorem of_separable_splitting_field_aux {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {p : polynomial F} [hFE : finite_dimensional F E] [sp : polynomial.is_splitting_field F E p] (hp : polynomial.separable p) (K : intermediate_field F E) {x : E} (hx : x ∈ polynomial.roots (polynomial.map (algebra_map F E) p)) : fintype.card (alg_hom F (↥↑(intermediate_field.adjoin (↥K) (intermediate_field.insert.insert ∅ x))) E) = fintype.card (alg_hom F (↥K) E) * finite_dimensional.findim ↥K ↥(intermediate_field.adjoin (↥K) (intermediate_field.insert.insert ∅ x)) := sorry theorem of_separable_splitting_field {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] {p : polynomial F} [sp : polynomial.is_splitting_field F E p] (hp : polynomial.separable p) : is_galois F E := sorry /--Equivalent characterizations of a Galois extension of finite degree-/ theorem tfae {F : Type u_1} [field F] {E : Type u_2} [field E] [algebra F E] [finite_dimensional F E] : tfae [is_galois F E, intermediate_field.fixed_field ⊤ = ⊥, fintype.card (alg_equiv F E E) = finite_dimensional.findim F E, ∃ (p : polynomial F), polynomial.separable p ∧ polynomial.is_splitting_field F E p] := sorry
3b018201d10c550c26eefc282af096839a5281c4
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/determinant.lean
832a3770de7ceaecc05223e5cbac107e147fb634
[ "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
25,692
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen -/ import linear_algebra.matrix.reindex import tactic.field_simp import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.basis /-! # Determinant of families of vectors This file defines the determinant of an endomorphism, and of a family of vectors with respect to some basis. For the determinant of a matrix, see the file `linear_algebra.matrix.determinant`. ## Main definitions In the list below, and in all this file, `R` is a commutative ring (semiring is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite types used for indexing. * `basis.det`: the determinant of a family of vectors with respect to a basis, as a multilinear map * `linear_map.det`: the determinant of an endomorphism `f : End R M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) * `linear_equiv.det`: the determinant of an isomorphism `f : M ≃ₗ[R] M` as a multiplicative homomorphism (if `M` does not have a finite `R`-basis, the result is `1` instead) ## Tags basis, det, determinant -/ noncomputable theory open_locale big_operators open_locale matrix open linear_map open submodule universes u v w open linear_map matrix set function variables {R : Type*} [comm_ring R] variables {M : Type*} [add_comm_group M] [module R M] variables {M' : Type*} [add_comm_group M'] [module R M'] variables {ι : Type*} [decidable_eq ι] [fintype ι] variables (e : basis ι R M) section conjugate variables {A : Type*} [comm_ring A] variables {m n : Type*} [fintype m] [fintype n] /-- If `R^m` and `R^n` are linearly equivalent, then `m` and `n` are also equivalent. -/ def equiv_of_pi_lequiv_pi {R : Type*} [comm_ring R] [nontrivial R] (e : (m → R) ≃ₗ[R] (n → R)) : m ≃ n := basis.index_equiv (basis.of_equiv_fun e.symm) (pi.basis_fun _ _) namespace matrix /-- If `M` and `M'` are each other's inverse matrices, they are square matrices up to equivalence of types. -/ def index_equiv_of_inv [nontrivial A] [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : m ≃ n := equiv_of_pi_lequiv_pi (to_lin'_of_inv hMM' hM'M) lemma det_comm [decidable_eq n] (M N : matrix n n A) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- If there exists a two-sided inverse `M'` for `M` (indexed differently), then `det (N ⬝ M) = det (M ⬝ N)`. -/ lemma det_comm' [decidable_eq m] [decidable_eq n] {M : matrix n m A} {N : matrix m n A} {M' : matrix m n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N) = det (N ⬝ M) := begin nontriviality A, -- Although `m` and `n` are different a priori, we will show they have the same cardinality. -- This turns the problem into one for square matrices, which is easy. let e := index_equiv_of_inv hMM' hM'M, rw [← det_submatrix_equiv_self e, ← submatrix_mul_equiv _ _ _ (equiv.refl n) _, det_comm, submatrix_mul_equiv, equiv.coe_refl, submatrix_id_id] end /-- If `M'` is a two-sided inverse for `M` (indexed differently), `det (M ⬝ N ⬝ M') = det N`. See `matrix.det_conj` and `matrix.det_conj'` for the case when `M' = M⁻¹` or vice versa. -/ lemma det_conj_of_mul_eq_one [decidable_eq m] [decidable_eq n] {M : matrix m n A} {M' : matrix n m A} {N : matrix n n A} (hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) : det (M ⬝ N ⬝ M') = det N := by rw [← det_comm' hM'M hMM', ← matrix.mul_assoc, hM'M, matrix.one_mul] end matrix end conjugate namespace linear_map /-! ### Determinant of a linear map -/ variables {A : Type*} [comm_ring A] [module A M] variables {κ : Type*} [fintype κ] /-- The determinant of `linear_map.to_matrix` does not depend on the choice of basis. -/ lemma det_to_matrix_eq_det_to_matrix [decidable_eq κ] (b : basis ι A M) (c : basis κ A M) (f : M →ₗ[A] M) : det (linear_map.to_matrix b b f) = det (linear_map.to_matrix c c f) := by rw [← linear_map_to_matrix_mul_basis_to_matrix c b c, ← basis_to_matrix_mul_linear_map_to_matrix b c b, matrix.det_conj_of_mul_eq_one]; rw [basis.to_matrix_mul_to_matrix, basis.to_matrix_self] /-- The determinant of an endomorphism given a basis. See `linear_map.det` for a version that populates the basis non-computably. Although the `trunc (basis ι A M)` parameter makes it slightly more convenient to switch bases, there is no good way to generalize over universe parameters, so we can't fully state in `det_aux`'s type that it does not depend on the choice of basis. Instead you can use the `det_aux_def'` lemma, or avoid mentioning a basis at all using `linear_map.det`. -/ def det_aux : trunc (basis ι A M) → (M →ₗ[A] M) →* A := trunc.lift (λ b : basis ι A M, (det_monoid_hom).comp (to_matrix_alg_equiv b : (M →ₗ[A] M) →* matrix ι ι A)) (λ b c, monoid_hom.ext $ det_to_matrix_eq_det_to_matrix b c) /-- Unfold lemma for `det_aux`. See also `det_aux_def'` which allows you to vary the basis. -/ lemma det_aux_def (b : basis ι A M) (f : M →ₗ[A] M) : linear_map.det_aux (trunc.mk b) f = matrix.det (linear_map.to_matrix b b f) := rfl -- Discourage the elaborator from unfolding `det_aux` and producing a huge term. attribute [irreducible] linear_map.det_aux lemma det_aux_def' {ι' : Type*} [fintype ι'] [decidable_eq ι'] (tb : trunc $ basis ι A M) (b' : basis ι' A M) (f : M →ₗ[A] M) : linear_map.det_aux tb f = matrix.det (linear_map.to_matrix b' b' f) := by { apply trunc.induction_on tb, intro b, rw [det_aux_def, det_to_matrix_eq_det_to_matrix b b'] } @[simp] lemma det_aux_id (b : trunc $ basis ι A M) : linear_map.det_aux b (linear_map.id) = 1 := (linear_map.det_aux b).map_one @[simp] lemma det_aux_comp (b : trunc $ basis ι A M) (f g : M →ₗ[A] M) : linear_map.det_aux b (f.comp g) = linear_map.det_aux b f * linear_map.det_aux b g := (linear_map.det_aux b).map_mul f g section open_locale classical -- Discourage the elaborator from unfolding `det` and producing a huge term by marking it -- as irreducible. /-- The determinant of an endomorphism independent of basis. If there is no finite basis on `M`, the result is `1` instead. -/ @[irreducible] protected def det : (M →ₗ[A] M) →* A := if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 lemma coe_det [decidable_eq M] : ⇑(linear_map.det : (M →ₗ[A] M) →* A) = if H : ∃ (s : finset M), nonempty (basis s A M) then linear_map.det_aux (trunc.mk H.some_spec.some) else 1 := by { ext, unfold linear_map.det, split_ifs, { congr }, -- use the correct `decidable_eq` instance refl } end -- Auxiliary lemma, the `simp` normal form goes in the other direction -- (using `linear_map.det_to_matrix`) lemma det_eq_det_to_matrix_of_finset [decidable_eq M] {s : finset M} (b : basis s A M) (f : M →ₗ[A] M) : f.det = matrix.det (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s A M), from ⟨s, ⟨b⟩⟩, by rw [linear_map.coe_det, dif_pos, det_aux_def' _ b]; assumption @[simp] lemma det_to_matrix (b : basis ι A M) (f : M →ₗ[A] M) : matrix.det (to_matrix b b f) = f.det := by { haveI := classical.dec_eq M, rw [det_eq_det_to_matrix_of_finset b.reindex_finset_range, det_to_matrix_eq_det_to_matrix b] } @[simp] lemma det_to_matrix' {ι : Type*} [fintype ι] [decidable_eq ι] (f : (ι → A) →ₗ[A] (ι → A)) : det f.to_matrix' = f.det := by simp [← to_matrix_eq_to_matrix'] @[simp] lemma det_to_lin (b : basis ι R M) (f : matrix ι ι R) : linear_map.det (matrix.to_lin b b f) = f.det := by rw [← linear_map.det_to_matrix b, linear_map.to_matrix_to_lin] /-- To show `P f.det` it suffices to consider `P (to_matrix _ _ f).det` and `P 1`. -/ @[elab_as_eliminator] lemma det_cases [decidable_eq M] {P : A → Prop} (f : M →ₗ[A] M) (hb : ∀ (s : finset M) (b : basis s A M), P (to_matrix b b f).det) (h1 : P 1) : P f.det := begin unfold linear_map.det, split_ifs with h, { convert hb _ h.some_spec.some, apply det_aux_def' }, { exact h1 } end @[simp] lemma det_comp (f g : M →ₗ[A] M) : (f.comp g).det = f.det * g.det := linear_map.det.map_mul f g @[simp] lemma det_id : (linear_map.id : M →ₗ[A] M).det = 1 := linear_map.det.map_one /-- Multiplying a map by a scalar `c` multiplies its determinant by `c ^ dim M`. -/ @[simp] lemma det_smul {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (c : 𝕜) (f : M →ₗ[𝕜] M) : linear_map.det (c • f) = c ^ (finite_dimensional.finrank 𝕜 M) * linear_map.det f := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { haveI : finite_dimensional 𝕜 M, { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_fintype_basis hs }, simp only [← det_to_matrix (finite_dimensional.fin_basis 𝕜 M), linear_equiv.map_smul, fintype.card_fin, det_smul] }, { classical, have : finite_dimensional.finrank 𝕜 M = 0 := finrank_eq_zero_of_not_exists_basis H, simp [coe_det, H, this] } end lemma det_zero' {ι : Type*} [finite ι] [nonempty ι] (b : basis ι A M) : linear_map.det (0 : M →ₗ[A] M) = 0 := by { haveI := classical.dec_eq ι, casesI nonempty_fintype ι, rwa [← det_to_matrix b, linear_equiv.map_zero, det_zero] } /-- In a finite-dimensional vector space, the zero map has determinant `1` in dimension `0`, and `0` otherwise. We give a formula that also works in infinite dimension, where we define the determinant to be `1`. -/ @[simp] lemma det_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] : linear_map.det (0 : M →ₗ[𝕜] M) = (0 : 𝕜) ^ (finite_dimensional.finrank 𝕜 M) := by simp only [← zero_smul 𝕜 (1 : M →ₗ[𝕜] M), det_smul, mul_one, monoid_hom.map_one] lemma det_eq_one_of_subsingleton [subsingleton M] (f : M →ₗ[R] M) : (f : M →ₗ[R] M).det = 1 := begin have b : basis (fin 0) R M := basis.empty M, rw ← f.det_to_matrix b, exact matrix.det_is_empty, end lemma det_eq_one_of_finrank_eq_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] (h : finite_dimensional.finrank 𝕜 M = 0) (f : M →ₗ[𝕜] M) : (f : M →ₗ[𝕜] M).det = 1 := begin classical, refine @linear_map.det_cases M _ 𝕜 _ _ _ (λ t, t = 1) f _ rfl, intros s b, haveI : is_empty s, { rw ← fintype.card_eq_zero_iff, exact (finite_dimensional.finrank_eq_card_basis b).symm.trans h }, exact matrix.det_is_empty end /-- Conjugating a linear map by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj {N : Type*} [add_comm_group N] [module A N] (f : M →ₗ[A] M) (e : M ≃ₗ[A] N) : linear_map.det ((e : M →ₗ[A] N) ∘ₗ (f ∘ₗ (e.symm : N →ₗ[A] M))) = linear_map.det f := begin classical, by_cases H : ∃ (s : finset M), nonempty (basis s A M), { rcases H with ⟨s, ⟨b⟩⟩, rw [← det_to_matrix b f, ← det_to_matrix (b.map e), to_matrix_comp (b.map e) b (b.map e), to_matrix_comp (b.map e) b b, ← matrix.mul_assoc, matrix.det_conj_of_mul_eq_one], { rw [← to_matrix_comp, linear_equiv.comp_coe, e.symm_trans_self, linear_equiv.refl_to_linear_map, to_matrix_id] }, { rw [← to_matrix_comp, linear_equiv.comp_coe, e.self_trans_symm, linear_equiv.refl_to_linear_map, to_matrix_id] } }, { have H' : ¬ (∃ (t : finset N), nonempty (basis t A N)), { contrapose! H, rcases H with ⟨s, ⟨b⟩⟩, exact ⟨_, ⟨(b.map e.symm).reindex_finset_range⟩⟩ }, simp only [coe_det, H, H', pi.one_apply, dif_neg, not_false_iff] } end /-- If a linear map is invertible, so is its determinant. -/ lemma is_unit_det {A : Type*} [comm_ring A] [module A M] (f : M →ₗ[A] M) (hf : is_unit f) : is_unit f.det := begin obtain ⟨g, hg⟩ : ∃ g, f.comp g = 1 := hf.exists_right_inv, have : linear_map.det f * linear_map.det g = 1, by simp only [← linear_map.det_comp, hg, monoid_hom.map_one], exact is_unit_of_mul_eq_one _ _ this, end /-- If a linear map has determinant different from `1`, then the space is finite-dimensional. -/ lemma finite_dimensional_of_det_ne_one {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M →ₗ[𝕜] M) (hf : f.det ≠ 1) : finite_dimensional 𝕜 M := begin by_cases H : ∃ (s : finset M), nonempty (basis s 𝕜 M), { rcases H with ⟨s, ⟨hs⟩⟩, exact finite_dimensional.of_fintype_basis hs }, { classical, simp [linear_map.coe_det, H] at hf, exact hf.elim } end /-- If the determinant of a map vanishes, then the map is not onto. -/ lemma range_lt_top_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : f.range < ⊤ := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [lt_top_iff_ne_top, not_not, ← is_unit_iff_range_eq_top] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end /-- If the determinant of a map vanishes, then the map is not injective. -/ lemma bot_lt_ker_of_det_eq_zero {𝕜 : Type*} [field 𝕜] [module 𝕜 M] {f : M →ₗ[𝕜] M} (hf : f.det = 0) : ⊥ < f.ker := begin haveI : finite_dimensional 𝕜 M, by simp [f.finite_dimensional_of_det_ne_one, hf], contrapose hf, simp only [bot_lt_iff_ne_bot, not_not, ← is_unit_iff_ker_eq_bot] at hf, exact is_unit_iff_ne_zero.1 (f.is_unit_det hf) end end linear_map namespace linear_equiv /-- On a `linear_equiv`, the domain of `linear_map.det` can be promoted to `Rˣ`. -/ protected def det : (M ≃ₗ[R] M) →* Rˣ := (units.map (linear_map.det : (M →ₗ[R] M) →* R)).comp (linear_map.general_linear_group.general_linear_equiv R M).symm.to_monoid_hom @[simp] lemma coe_det (f : M ≃ₗ[R] M) : ↑f.det = linear_map.det (f : M →ₗ[R] M) := rfl @[simp] lemma coe_inv_det (f : M ≃ₗ[R] M) : ↑(f.det⁻¹) = linear_map.det (f.symm : M →ₗ[R] M) := rfl @[simp] lemma det_refl : (linear_equiv.refl R M).det = 1 := units.ext $ linear_map.det_id @[simp] lemma det_trans (f g : M ≃ₗ[R] M) : (f.trans g).det = g.det * f.det := map_mul _ g f @[simp] lemma det_symm (f : M ≃ₗ[R] M) : f.symm.det = f.det⁻¹ := map_inv _ f /-- Conjugating a linear equiv by a linear equiv does not change its determinant. -/ @[simp] lemma det_conj (f : M ≃ₗ[R] M) (e : M ≃ₗ[R] M') : ((e.symm.trans f).trans e).det = f.det := by rw [←units.eq_iff, coe_det, coe_det, ←comp_coe, ←comp_coe, linear_map.det_conj] end linear_equiv /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_mul_det_symm {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f : M →ₗ[A] M).det * (f.symm : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] /-- The determinants of a `linear_equiv` and its inverse multiply to 1. -/ @[simp] lemma linear_equiv.det_symm_mul_det {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : (f.symm : M →ₗ[A] M).det * (f : M →ₗ[A] M).det = 1 := by simp [←linear_map.det_comp] -- Cannot be stated using `linear_map.det` because `f` is not an endomorphism. lemma linear_equiv.is_unit_det (f : M ≃ₗ[R] M') (v : basis ι R M) (v' : basis ι R M') : is_unit (linear_map.to_matrix v v' f).det := begin apply is_unit_det_of_left_inverse, simpa using (linear_map.to_matrix_comp v v' v f.symm f).symm end /-- Specialization of `linear_equiv.is_unit_det` -/ lemma linear_equiv.is_unit_det' {A : Type*} [comm_ring A] [module A M] (f : M ≃ₗ[A] M) : is_unit (linear_map.det (f : M →ₗ[A] M)) := is_unit_of_mul_eq_one _ _ f.det_mul_det_symm /-- The determinant of `f.symm` is the inverse of that of `f` when `f` is a linear equiv. -/ lemma linear_equiv.det_coe_symm {𝕜 : Type*} [field 𝕜] [module 𝕜 M] (f : M ≃ₗ[𝕜] M) : (f.symm : M →ₗ[𝕜] M).det = (f : M →ₗ[𝕜] M).det ⁻¹ := by field_simp [is_unit.ne_zero f.is_unit_det'] /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ @[simps] def linear_equiv.of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : M ≃ₗ[R] M' := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_smul, inv_fun := to_lin v' v (to_matrix v v' f)⁻¹, left_inv := λ x, calc to_lin v' v (to_matrix v v' f)⁻¹ (f x) = to_lin v v ((to_matrix v v' f)⁻¹ ⬝ to_matrix v v' f) x : by { rw [to_lin_mul v v' v, to_lin_to_matrix, linear_map.comp_apply] } ... = x : by simp [h], right_inv := λ x, calc f (to_lin v' v (to_matrix v v' f)⁻¹ x) = to_lin v' v' (to_matrix v v' f ⬝ (to_matrix v v' f)⁻¹) x : by { rw [to_lin_mul v' v v', linear_map.comp_apply, to_lin_to_matrix v v'] } ... = x : by simp [h] } @[simp] lemma linear_equiv.coe_of_is_unit_det {f : M →ₗ[R] M'} {v : basis ι R M} {v' : basis ι R M'} (h : is_unit (linear_map.to_matrix v v' f).det) : (linear_equiv.of_is_unit_det h : M →ₗ[R] M') = f := by { ext x, refl } /-- Builds a linear equivalence from a linear map on a finite-dimensional vector space whose determinant is nonzero. -/ @[reducible] def linear_map.equiv_of_det_ne_zero {𝕜 : Type*} [field 𝕜] {M : Type*} [add_comm_group M] [module 𝕜 M] [finite_dimensional 𝕜 M] (f : M →ₗ[𝕜] M) (hf : linear_map.det f ≠ 0) : M ≃ₗ[𝕜] M := have is_unit (linear_map.to_matrix (finite_dimensional.fin_basis 𝕜 M) (finite_dimensional.fin_basis 𝕜 M) f).det := by simp only [linear_map.det_to_matrix, is_unit_iff_ne_zero.2 hf], linear_equiv.of_is_unit_det this lemma linear_map.associated_det_of_eq_comp (e : M ≃ₗ[R] M) (f f' : M →ₗ[R] M) (h : ∀ x, f x = f' (e x)) : associated f.det f'.det := begin suffices : associated (f' ∘ₗ ↑e).det f'.det, { convert this using 2, ext x, exact h x }, rw [← mul_one f'.det, linear_map.det_comp], exact associated.mul_left _ (associated_one_iff_is_unit.mpr e.is_unit_det') end lemma linear_map.associated_det_comp_equiv {N : Type*} [add_comm_group N] [module R N] (f : N →ₗ[R] M) (e e' : M ≃ₗ[R] N) : associated (f ∘ₗ ↑e).det (f ∘ₗ ↑e').det := begin refine linear_map.associated_det_of_eq_comp (e.trans e'.symm) _ _ _, intro x, simp only [linear_map.comp_apply, linear_equiv.coe_coe, linear_equiv.trans_apply, linear_equiv.apply_symm_apply], end /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def basis.det : alternating_map R M R ι := { to_fun := λ v, det (e.to_matrix v), map_add' := begin intros v i x y, simp only [e.to_matrix_update, linear_equiv.map_add], apply det_update_column_add end, map_smul' := begin intros u i c x, simp only [e.to_matrix_update, algebra.id.smul_eq_mul, linear_equiv.map_smul], apply det_update_column_smul end, map_eq_zero_of_eq' := begin intros v i j h hij, rw [←function.update_eq_self i v, h, ←det_transpose, e.to_matrix_update, ←update_row_transpose, ←e.to_matrix_transpose_apply], apply det_zero_of_row_eq hij, rw [update_row_ne hij.symm, update_row_self], end } lemma basis.det_apply (v : ι → M) : e.det v = det (e.to_matrix v) := rfl lemma basis.det_self : e.det e = 1 := by simp [e.det_apply] @[simp] lemma basis.det_is_empty [is_empty ι] : e.det = alternating_map.const_of_is_empty R M 1 := begin ext v, exact matrix.det_is_empty, end /-- `basis.det` is not the zero map. -/ lemma basis.det_ne_zero [nontrivial R] : e.det ≠ 0 := λ h, by simpa [h] using e.det_self lemma is_basis_iff_det {v : ι → M} : linear_independent R v ∧ span R (set.range v) = ⊤ ↔ is_unit (e.det v) := begin split, { rintro ⟨hli, hspan⟩, set v' := basis.mk hli hspan.ge with v'_eq, rw e.det_apply, convert linear_equiv.is_unit_det (linear_equiv.refl _ _) v' e using 2, ext i j, simp }, { intro h, rw [basis.det_apply, basis.to_matrix_eq_to_matrix_constr] at h, set v' := basis.map e (linear_equiv.of_is_unit_det h) with v'_def, have : ⇑ v' = v, { ext i, rw [v'_def, basis.map_apply, linear_equiv.of_is_unit_det_apply, e.constr_basis] }, rw ← this, exact ⟨v'.linear_independent, v'.span_eq⟩ }, end lemma basis.is_unit_det (e' : basis ι R M) : is_unit (e.det e') := (is_basis_iff_det e).mp ⟨e'.linear_independent, e'.span_eq⟩ /-- Any alternating map to `R` where `ι` has the cardinality of a basis equals the determinant map with respect to that basis, multiplied by the value of that alternating map on that basis. -/ lemma alternating_map.eq_smul_basis_det (f : alternating_map R M R ι) : f = f e • e.det := begin refine basis.ext_alternating e (λ i h, _), let σ : equiv.perm ι := equiv.of_bijective i (finite.injective_iff_bijective.1 h), change f (e ∘ σ) = (f e • e.det) (e ∘ σ), simp [alternating_map.map_perm, basis.det_self] end @[simp] lemma alternating_map.map_basis_eq_zero_iff {ι : Type*} [decidable_eq ι] [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e = 0 ↔ f = 0 := ⟨λ h, by { casesI nonempty_fintype ι, simpa [h] using f.eq_smul_basis_det e }, λ h, h.symm ▸ alternating_map.zero_apply _⟩ lemma alternating_map.map_basis_ne_zero_iff {ι : Type*} [decidable_eq ι] [finite ι] (e : basis ι R M) (f : alternating_map R M R ι) : f e ≠ 0 ↔ f ≠ 0 := not_congr $ f.map_basis_eq_zero_iff e variables {A : Type*} [comm_ring A] [module A M] @[simp] lemma basis.det_comp (e : basis ι A M) (f : M →ₗ[A] M) (v : ι → M) : e.det (f ∘ v) = f.det * e.det v := by { rw [basis.det_apply, basis.det_apply, ← f.det_to_matrix e, ← matrix.det_mul, e.to_matrix_eq_to_matrix_constr (f ∘ v), e.to_matrix_eq_to_matrix_constr v, ← to_matrix_comp, e.constr_comp] } @[simp] lemma basis.det_comp_basis [module A M'] (b : basis ι A M) (b' : basis ι A M') (f : M →ₗ[A] M') : b'.det (f ∘ b) = linear_map.det (f ∘ₗ (b'.equiv b (equiv.refl ι) : M' →ₗ[A] M)) := begin rw [basis.det_apply, ← linear_map.det_to_matrix b', linear_map.to_matrix_comp _ b, matrix.det_mul, linear_map.to_matrix_basis_equiv, matrix.det_one, mul_one], congr' 1, ext i j, rw [basis.to_matrix_apply, linear_map.to_matrix_apply] end lemma basis.det_reindex {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).det v = b.det (v ∘ e) := by rw [basis.det_apply, basis.to_matrix_reindex', det_reindex_alg_equiv, basis.det_apply] lemma basis.det_reindex_symm {ι' : Type*} [fintype ι'] [decidable_eq ι'] (b : basis ι R M) (v : ι → M) (e : ι' ≃ ι) : (b.reindex e.symm).det (v ∘ e) = b.det v := by rw [basis.det_reindex, function.comp.assoc, e.self_comp_symm, function.comp.right_id] @[simp] lemma basis.det_map (b : basis ι R M) (f : M ≃ₗ[R] M') (v : ι → M') : (b.map f).det v = b.det (f.symm ∘ v) := by { rw [basis.det_apply, basis.to_matrix_map, basis.det_apply] } lemma basis.det_map' (b : basis ι R M) (f : M ≃ₗ[R] M') : (b.map f).det = b.det.comp_linear_map f.symm := alternating_map.ext $ b.det_map f @[simp] lemma pi.basis_fun_det : (pi.basis_fun R ι).det = matrix.det_row_alternating := begin ext M, rw [basis.det_apply, basis.coe_pi_basis_fun.to_matrix_eq_transpose, det_transpose], end /-- If we fix a background basis `e`, then for any other basis `v`, we can characterise the coordinates provided by `v` in terms of determinants relative to `e`. -/ lemma basis.det_smul_mk_coord_eq_det_update {v : ι → M} (hli : linear_independent R v) (hsp : ⊤ ≤ span R (range v)) (i : ι) : (e.det v) • (basis.mk hli hsp).coord i = e.det.to_multilinear_map.to_linear_map v i := begin apply (basis.mk hli hsp).ext, intros k, rcases eq_or_ne k i with rfl | hik; simp only [algebra.id.smul_eq_mul, basis.coe_mk, linear_map.smul_apply, linear_map.coe_mk, multilinear_map.to_linear_map_apply], { rw [basis.mk_coord_apply_eq, mul_one, update_eq_self], congr, }, { rw [basis.mk_coord_apply_ne hik, mul_zero, eq_comm], exact e.det.map_eq_zero_of_eq _ (by simp [hik, function.update_apply]) hik, }, end /-- If a basis is multiplied columnwise by scalars `w : ι → Rˣ`, then the determinant with respect to this basis is multiplied by the product of the inverse of these scalars. -/ lemma basis.det_units_smul (e : basis ι R M) (w : ι → Rˣ) : (e.units_smul w).det = (↑(∏ i, w i)⁻¹ : R) • e.det := begin ext f, change matrix.det (λ i j, (e.units_smul w).repr (f j) i) = (↑(∏ i, w i)⁻¹ : R) • matrix.det (λ i j, e.repr (f j) i), simp only [e.repr_units_smul], convert matrix.det_mul_column (λ i, (↑((w i)⁻¹) : R)) (λ i j, e.repr (f j) i), simp [← finset.prod_inv_distrib] end /-- The determinant of a basis constructed by `units_smul` is the product of the given units. -/ @[simp] lemma basis.det_units_smul_self (w : ι → Rˣ) : e.det (e.units_smul w) = ∏ i, w i := by simp [basis.det_apply] /-- The determinant of a basis constructed by `is_unit_smul` is the product of the given units. -/ @[simp] lemma basis.det_is_unit_smul {w : ι → R} (hw : ∀ i, is_unit (w i)) : e.det (e.is_unit_smul hw) = ∏ i, w i := e.det_units_smul_self _
4de804bc90802c36e248e40c0a37b1b1ad5c7308
9cba98daa30c0804090f963f9024147a50292fa0
/geom/geom3d.lean
42ccf73deb7ead1cfe530b7647c819574811bcc2
[]
no_license
kevinsullivan/phys
dcb192f7b3033797541b980f0b4a7e75d84cea1a
ebc2df3779d3605ff7a9b47eeda25c2a551e011f
refs/heads/master
1,637,490,575,500
1,629,899,064,000
1,629,899,064,000
168,012,884
0
3
null
1,629,644,436,000
1,548,699,832,000
Lean
UTF-8
Lean
false
false
32,340
lean
import .geom1d open_locale affine section fix_this_name universes u /- 3D Geometric Space with Std Coordinate System -/ noncomputable def std_3d_geom := (mk_prod_spc (mk_prod_spc geom1d_std_space geom1d_std_space) geom1d_std_space) abbreviation geom3d_frame := std_3d_geom.frame_type abbreviation geom3d_space (f : geom3d_frame) := spc real_scalar f noncomputable def geom3d_std_frame := std_3d_geom.frame noncomputable def geom3d_std_space : geom3d_space geom3d_std_frame := std_3d_geom /- Positions are points in this space. -/ -- public structure position3d {f : geom3d_frame} (s : geom3d_space f ) extends point s -- public, to enable certain proofs that clients might want to write @[ext] lemma position3d.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : position3d s), x.to_point = y.to_point → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_point := x} : position3d s).to_point = x := rfl, simp [h₁] at e, exact e end noncomputable def position3d.coords {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) := λi : fin 3, (p.to_point.coords i).coord /- User can use coordinates to build an object, but once this is done, the coordinates should disappear inside the object. From there, you should be able to ask the object to return its coordinates *in any given ACS (on the same physical dimension). noncomputable def position3d.coords_in_s' {f f': geom3d_frame} {s : geom3d_space f } (p :position3d s) (s' : geom3d_space f' ) := p.to_point.coords -- should get back (transform p) . coords. -/ /- def point.expressed_in {dim : ℕ} {id_vec : fin dim → ℕ} {f: fm K dim id_vec} {s : spc K f} {f2: fm K dim id_vec} {s2 : spc K f2} (p1 : point s) (s2 : spc K f2) : point s2 := (s.fm_tr s2).transform_point p1 def vectr.expressed_in {dim : ℕ} {id_vec : fin dim → ℕ} {f: fm K dim id_vec} {s : spc K f} {f2: fm K dim id_vec} {s2 : spc K f2} (v1 : vectr s) (s2 : spc K f2) : vectr s2 := (s.fm_tr s2).transform_vectr v1 -/ noncomputable def position3d.expressed_in {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) : Π {f' : geom3d_frame} (s' : geom3d_space f' ), position3d s' := λ f' s', ⟨(p.to_point.expressed_in s')⟩ noncomputable def position3d.coords_in {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) : Π {f' : geom3d_frame} (s' : geom3d_space f' ), fin 3 → scalar := λ f' s', λi, ((p.expressed_in s').to_point.coords i).coord noncomputable def position3d.x {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) : real_scalar := (p.to_point.coords 0).coord noncomputable def position3d.y {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) : real_scalar := (p.to_point.coords 1).coord noncomputable def position3d.z {f : geom3d_frame} {s : geom3d_space f } (p :position3d s) : real_scalar := (p.to_point.coords 2).coord noncomputable def mk_position3d {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : real_scalar) : position3d s := position3d.mk (mk_point s ⟨[k₁,k₂,k₃],rfl⟩) -- Private @[simp] def mk_position3d' {f : geom3d_frame} (s : geom3d_space f ) (p : point s) : position3d s := position3d.mk p -- Private @[simp] noncomputable def mk_position3d'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : position1d s1) (p2 : position1d s2) (p3 : position1d s3 ) : position3d (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_point_prod (mk_point_prod p1.to_point p2.to_point) p3.to_point⟩ /- Displacements are vectors in this affine coordinate space -/ -- Public structure displacement3d {f : geom3d_frame} (s : geom3d_space f ) extends vectr s @[ext] lemma displacement3d.ext : ∀ {f : geom3d_frame} {s : geom3d_space f } (x y : displacement3d s), x.to_vectr = y.to_vectr → x = y := begin intros f s x y e, cases x, cases y, simp *, have h₁ : ({to_vectr := x} : displacement3d s).to_vectr = x := rfl, simp [h₁] at e, exact e end -- Public def displacement3d.frame {f : geom3d_frame} {s : geom3d_space f } (d :displacement3d s) := f -- Public noncomputable def displacement3d.expressed_in {f : geom3d_frame} {s : geom3d_space f } (p : displacement3d s) : Π {f' : geom3d_frame} (s' : geom3d_space f' ), displacement3d s' := λ f' s', ⟨(p.to_vectr.expressed_in s')⟩ noncomputable def displacement3d.coords_in {f : geom3d_frame} {s : geom3d_space f } (p : displacement3d s) : Π {f' : geom3d_frame} (s' : geom3d_space f' ), fin 3 → scalar := λ f' s', λi, ((p.expressed_in s').to_vectr.coords i).coord noncomputable def displacement3d.coords {f : geom3d_frame} {s : geom3d_space f } (d :displacement3d s) := λi : fin 3, (d.to_vectr.coords i).coord noncomputable def displacement3d.x {f : geom3d_frame} {s : geom3d_space f } (p :displacement3d s) : real_scalar := (p.to_vectr.coords 0).coord noncomputable def displacement3d.y {f : geom3d_frame} {s : geom3d_space f } (p :displacement3d s) : real_scalar := (p.to_vectr.coords 1).coord noncomputable def displacement3d.z {f : geom3d_frame} {s : geom3d_space f } (p :displacement3d s) : real_scalar := (p.to_vectr.coords 2).coord -- Private @[simp] def mk_displacement3d' {f : geom3d_frame} (s : geom3d_space f ) (v : vectr s) : displacement3d s := displacement3d.mk v @[simp] noncomputable def mk_displacement3d {f : geom3d_frame} (s : geom3d_space f ) (k₁ k₂ k₃ : real_scalar) : displacement3d s := displacement3d.mk (mk_vectr s ⟨[k₁,k₂,k₃],rfl⟩) -- Private @[simp] noncomputable def mk_displacement3d'' {f1 f2 f3 : geom1d_frame } { s1 : geom1d_space f1} {s2 : geom1d_space f2} { s3 : geom1d_space f3} (p1 : displacement1d s1) (p2 : displacement1d s2) (p3 : displacement1d s3 ) : displacement3d (mk_prod_spc (mk_prod_spc s1 s2) s3) := ⟨mk_vectr_prod (mk_vectr_prod p1.to_vectr p2.to_vectr) p3.to_vectr⟩ -- Public @[simp] noncomputable def mk_geom3d_frame {parent : geom3d_frame} {s : spc real_scalar parent} (p : position3d s) (v0 : displacement3d s) (v1 : displacement3d s) (v2 : displacement3d s) : geom3d_frame := (mk_frame p.to_point ⟨(λi, if i = 0 then v0.to_vectr else if i = 1 then v1.to_vectr else v2.to_vectr),sorry,sorry⟩) -- Public @[simp] noncomputable def mk_geom3d_space (fr : geom3d_frame) : geom3d_space _ := mk_space fr end fix_this_name section fix_this_name_too /- Proof that geom3d is an affine coordinate space -/ namespace geom3d variables {f : geom3d_frame} {s : geom3d_space f } @[simp] noncomputable def add_displacement3d_displacement3d (v3 v2 : displacement3d s) : displacement3d s := mk_displacement3d' s (v3.to_vectr + v2.to_vectr) @[simp] noncomputable def smul_displacement3d (k : real_scalar) (v : displacement3d s) : displacement3d s := mk_displacement3d' s (k • v.to_vectr) @[simp] noncomputable def neg_displacement3d (v : displacement3d s) : displacement3d s := mk_displacement3d' s ((-1 : real_scalar) • v.to_vectr) @[simp] noncomputable def sub_displacement3d_displacement3d (v3 v2 : displacement3d s) : displacement3d s := -- v3-v2 add_displacement3d_displacement3d v3 (neg_displacement3d v2) noncomputable instance has_add_displacement3d : has_add (displacement3d s) := ⟨ add_displacement3d_displacement3d ⟩ lemma add_assoc_displacement3d : ∀ a b c : displacement3d s, a + b + c = a + (b + c) := begin intros, ext, dsimp only [has_add.add], dsimp only [add_displacement3d_displacement3d, has_add.add], dsimp only [add_vectr_vectr, has_add.add], dsimp only [add_vec_vec, mk_displacement3d', mk_vectr'], simp only [add_assoc], end noncomputable instance add_semigroup_displacement3d : add_semigroup (displacement3d s) := ⟨ add_displacement3d_displacement3d, add_assoc_displacement3d⟩ @[simp] noncomputable def displacement3d_zero := mk_displacement3d s 0 0 0 noncomputable instance : inhabited (displacement3d s) := ⟨displacement3d_zero⟩ noncomputable instance has_zero_displacement3d : has_zero (displacement3d s) := ⟨displacement3d_zero⟩ lemma zero_add_displacement3d : ∀ a : displacement3d s, 0 + a = a := begin intros, ext, dsimp only [has_zero.zero, has_add.add], dsimp only [add_displacement3d_displacement3d, displacement3d_zero, mk_displacement3d', mk_displacement3d, has_add.add], dsimp only [add_vectr_vectr, mk_vectr', mk_vectr, mk_vec_n, has_add.add], dsimp only [add_vec_vec, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, zero_add], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le, zero_add], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le, zero_add], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end lemma add_zero_displacement3d : ∀ a : displacement3d s, a + 0 = a := begin intros, ext, dsimp only [has_zero.zero, has_add.add], dsimp only [add_displacement3d_displacement3d, displacement3d_zero, mk_displacement3d', mk_displacement3d, has_add.add], dsimp only [add_vectr_vectr, mk_vectr', mk_vectr, mk_vec_n, has_add.add], dsimp only [add_vec_vec, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, add_zero], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le, add_zero], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le, add_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end @[simp] noncomputable def nsmul_displacement3d : ℕ → (displacement3d s) → (displacement3d s) | nat.zero v := displacement3d_zero --| 3 v := v | (nat.succ n) v := (add_displacement3d_displacement3d) v (nsmul_displacement3d n v) noncomputable instance add_monoid_displacement3d : add_monoid (displacement3d s) := ⟨ -- add_semigroup add_displacement3d_displacement3d, add_assoc_displacement3d, -- has_zero displacement3d_zero, -- new structure @zero_add_displacement3d f s, add_zero_displacement3d, nsmul_displacement3d, begin admit end, begin admit end ⟩ noncomputable instance has_neg_displacement3d : has_neg (displacement3d s) := ⟨neg_displacement3d⟩ noncomputable instance has_sub_displacement3d : has_sub (displacement3d s) := ⟨ sub_displacement3d_displacement3d⟩ lemma sub_eq_add_neg_displacement3d : ∀ a b : displacement3d s, a - b = a + -b := begin intros,ext, refl, end noncomputable instance sub_neg_monoid_displacement3d : sub_neg_monoid (displacement3d s) := { neg := neg_displacement3d , ..(show add_monoid (displacement3d s), by apply_instance) } lemma add_left_neg_displacement3d : ∀ a : displacement3d s, -a + a = 0 := begin intros, ext, dsimp only [has_zero.zero, has_add.add, has_neg.neg], dsimp only [neg_displacement3d, has_scalar.smul], dsimp only [add_displacement3d_displacement3d, smul_vectr, has_add.add, has_scalar.smul], dsimp only [add_vectr_vectr, smul_vec, mk_displacement3d', mk_vectr', has_add.add], dsimp only [add_vec_vec], simp only [neg_mul_eq_neg_mul_symm, one_mul, mk_vectr, displacement3d_zero, mk_displacement3d, add_left_neg], dsimp only [mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le], simp only [add_left_eq_self, list.nth_le], cases x' with x'', simp only [list.nth_le], simp only [add_left_eq_self, list.nth_le], cases x'' with x''', simp only [list.nth_le], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance : add_group (displacement3d s) := { add_left_neg := begin exact add_left_neg_displacement3d, end, ..(show sub_neg_monoid (displacement3d s), by apply_instance), } lemma add_comm_displacement3d : ∀ a b : displacement3d s, a + b = b + a := begin intros, ext, dsimp only [has_add.add], dsimp only [add_displacement3d_displacement3d, has_add.add], dsimp only [add_vectr_vectr, has_add.add], dsimp only [add_vec_vec, mk_displacement3d', mk_vectr'], simp only [add_comm], end noncomputable instance add_comm_semigroup_displacement3d : add_comm_semigroup (displacement3d s) := ⟨ -- add_semigroup add_displacement3d_displacement3d, add_assoc_displacement3d, add_comm_displacement3d, ⟩ noncomputable instance add_comm_monoid_displacement3d : add_comm_monoid (displacement3d s) := { add_comm := begin exact add_comm_displacement3d end, ..(show add_monoid (displacement3d s), by apply_instance) } noncomputable instance has_scalar_displacement3d : has_scalar real_scalar (displacement3d s) := ⟨ smul_displacement3d, ⟩ lemma one_smul_displacement3d : ∀ b : displacement3d s, (1 : real_scalar) • b = b := begin intros, ext, dsimp only [has_scalar.smul], dsimp only [smul_displacement3d, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr'], simp only [one_mul], end lemma mul_smul_displacement3d : ∀ (x y : real_scalar) (b : displacement3d s), (x * y) • b = x • y • b := begin intros, cases b, ext, exact mul_assoc x y _, end noncomputable instance mul_action_displacement3d : mul_action real_scalar (displacement3d s) := ⟨ one_smul_displacement3d, mul_smul_displacement3d, ⟩ lemma smul_add_displacement3d : ∀(r : real_scalar) (x y : displacement3d s), r • (x + y) = r • x + r • y := begin intros, ext, dsimp only [has_scalar.smul, has_add.add], dsimp only [smul_displacement3d, add_displacement3d_displacement3d, has_scalar.smul, has_add.add], dsimp only [smul_vectr, add_vectr_vectr, has_scalar.smul, has_add.add], dsimp only [smul_vec, add_vec_vec, mk_displacement3d', mk_vectr'], simp only [distrib.left_distrib], refl, end lemma smul_zero_displacement3d : ∀(r : real_scalar), r • (0 : displacement3d s) = 0 := begin intros, ext, dsimp only [has_scalar.smul, has_zero.zero], dsimp only [smul_displacement3d, displacement3d_zero, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, mul_zero], simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, mul_zero], simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, mul_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance distrib_mul_action_K_displacement3d : distrib_mul_action real_scalar (displacement3d s) := ⟨ smul_add_displacement3d, smul_zero_displacement3d, ⟩ -- renaming vs template due to clash with name "s" for prevailing variable lemma add_smul_displacement3d : ∀ (a b : real_scalar) (x : displacement3d s), (a + b) • x = a • x + b • x := begin intros, ext, exact right_distrib _ _ _, end lemma zero_smul_displacement3d : ∀ (x : displacement3d s), (0 : real_scalar) • x = 0 := begin intros, ext, dsimp only [has_scalar.smul, has_zero.zero], dsimp only [smul_displacement3d, displacement3d_zero, has_scalar.smul], dsimp only [smul_vectr, has_scalar.smul], dsimp only [smul_vec, mk_displacement3d', mk_vectr', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x_1, dsimp only [fin.mk], cases x_1_val with x', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, mul_eq_zero], apply or.inl, refl, have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_1_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_1_property, dsimp only [has_le.le], exact x_1_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end noncomputable instance module_K_displacement3d : module real_scalar (displacement3d s) := ⟨ add_smul_displacement3d, zero_smul_displacement3d ⟩ noncomputable instance add_comm_group_displacement3d : add_comm_group (displacement3d s) := { add_comm := begin exact add_comm_displacement3d end, ..(show add_group (displacement3d s), by apply_instance) } noncomputable instance : module real_scalar (displacement3d s) := @geom3d.module_K_displacement3d f s /- ******************** *** Affine space *** ******************** -/ /- Affine operations -/ noncomputable instance : has_add (displacement3d s) := ⟨add_displacement3d_displacement3d⟩ noncomputable instance : has_zero (displacement3d s) := ⟨displacement3d_zero⟩ noncomputable instance : has_neg (displacement3d s) := ⟨neg_displacement3d⟩ /- Lemmas needed to implement affine space API -/ @[simp] noncomputable def sub_position3d_position3d {f : geom3d_frame} {s : geom3d_space f } (p3 p2 : position3d s) : displacement3d s := mk_displacement3d' s (p3.to_point -ᵥ p2.to_point) @[simp] noncomputable def add_position3d_displacement3d {f : geom3d_frame} {s : geom3d_space f } (p : position3d s) (v : displacement3d s) : position3d s := mk_position3d' s (v.to_vectr +ᵥ p.to_point) -- reorder assumes order is irrelevant @[simp] noncomputable def add_displacement3d_position3d {f : geom3d_frame} {s : geom3d_space f } (v : displacement3d s) (p : position3d s) : position3d s := mk_position3d' s (v.to_vectr +ᵥ p.to_point) --@[simp] --def aff_displacement3d_group_action : displacement3d s → position3d s → position3d s := add_displacement3d_position3d real_scalar noncomputable instance : has_vadd (displacement3d s) (position3d s) := ⟨add_displacement3d_position3d⟩ lemma zero_displacement3d_vadd'_a3 : ∀ p : position3d s, (0 : displacement3d s) +ᵥ p = p := begin intros, ext, dsimp only [has_vadd.vadd, has_zero.zero], dsimp only [add_displacement3d_position3d, displacement3d_zero, has_vadd.vadd], dsimp only [add_vectr_point, has_vadd.vadd], dsimp only [aff_vec_group_action, add_vec_pt, mk_position3d', mk_point', mk_displacement3d, mk_vectr, mk_vec_n, mk_vec, vector.nth], cases x, dsimp only [fin.mk], cases x_val with x', simp only [list.nth_le, add_zero], simp only [list.nth_le], cases x' with x'', simp only [list.nth_le, add_zero], simp only [list.nth_le], cases x'' with x''', simp only [list.nth_le, add_zero], have h₀ : x'''.succ.succ.succ = x''' + 3 := rfl, have h₁ : 1 + 1 + 1 = 0 + 3 := rfl, rw [h₀, h₁] at x_property, have h₂ : x'''.succ + 3 ≤ 0 + 3 := begin dsimp only [has_lt.lt, nat.lt] at x_property, dsimp only [has_le.le], exact x_property, end, have h₃ := (add_le_add_iff_right 3).1 h₂, simp only [nat.not_succ_le_zero] at h₃, contradiction, end lemma displacement3d_add_assoc'_a3 : ∀ (g3 g2 : displacement3d s) (p : position3d s), g3 +ᵥ (g2 +ᵥ p) = (g3 + g2) +ᵥ p := begin intros, ext, dsimp only [has_add.add, has_vadd.vadd], dsimp only [add_displacement3d_position3d, add_displacement3d_displacement3d, has_add.add, has_vadd.vadd], dsimp only [add_vectr_point, add_vectr_vectr, has_add.add, has_vadd.vadd], dsimp only [aff_vec_group_action, add_vec_vec, add_vec_pt, mk_position3d', mk_point', mk_displacement3d', mk_vectr'], simp only [add_assoc, add_right_inj], simp only [add_comm], end noncomputable instance displacement3d_add_action: add_action (displacement3d s) (position3d s) := ⟨ zero_displacement3d_vadd'_a3, begin let h0 := displacement3d_add_assoc'_a3, intros, exact (h0 g₁ g₂ p).symm end⟩ --@[simp] noncomputable instance position3d_has_vsub : has_vsub (displacement3d s) (position3d s) := ⟨ sub_position3d_position3d⟩ instance : nonempty (position3d s) := ⟨mk_position3d s 0 0 0⟩ noncomputable instance : inhabited (position3d s) := ⟨mk_position3d s 0 0 0⟩ lemma position3d_vsub_vadd_a3 : ∀ (p3 p2 : (position3d s)), (p3 -ᵥ p2) +ᵥ p2 = p3 := begin intros, ext, dsimp only [has_vsub.vsub, has_vadd.vadd], dsimp only [add_displacement3d_position3d, sub_position3d_position3d, has_vsub.vsub, has_vadd.vadd], dsimp only [add_vectr_point, aff_point_group_sub, sub_point_point, has_vsub.vsub, has_vadd.vadd], dsimp only [aff_vec_group_action, aff_point_group_sub, add_vec_pt, aff_pt_group_sub, sub_pt_pt, mk_position3d', mk_point', mk_displacement3d', mk_vectr'], simp only [add_sub_cancel'_right], end lemma position3d_vadd_vsub_a3 : ∀ (g : displacement3d s) (p : position3d s), g +ᵥ p -ᵥ p = g := begin intros, ext, repeat { have h0 : ((g +ᵥ p -ᵥ p) : displacement3d s).to_vectr = (g.to_vectr +ᵥ p.to_point -ᵥ p.to_point) := rfl, rw h0, simp *, } end noncomputable instance aff_geom3d_torsor : add_torsor (displacement3d s) (position3d s) := ⟨ begin exact position3d_vsub_vadd_a3, end, begin exact position3d_vadd_vsub_a3, end, ⟩ open_locale affine noncomputable instance : affine_space (displacement3d s) (position3d s) := @geom3d.aff_geom3d_torsor f s end geom3d -- ha ha end fix_this_name_too /- Transformations in 3d geometric space -/ /- Newer version Tradeoff - Does not directly extend from affine equiv. Base class is an equiv on points and vectrs Extension methods are provided to directly transform Times and Duration between frames -/ @[ext] structure geom3d_transform {f3 : geom3d_frame} {f2 : geom3d_frame} (sp3 : geom3d_space f3) (sp2 : geom3d_space f2) extends fm_tr sp3 sp2 noncomputable def geom3d_space.mk_geom3d_transform_to {f3 : geom3d_frame} (s3 : geom3d_space f3) : Π {f2 : geom3d_frame} (s2 : geom3d_space f2), geom3d_transform s3 s2 := --(position3d s2) ≃ᵃ[scalar] (position3d s3) := λ f2 s2, ⟨s3.fm_tr s2⟩ noncomputable instance g3tr_inh {f3 : geom3d_frame} {f2 : geom3d_frame} (sp3 : geom3d_space f3) (sp2 : geom3d_space f2) : inhabited (geom3d_transform sp3 sp2) := ⟨sp3.mk_geom3d_transform_to sp2⟩ noncomputable def geom3d_transform.symm {f3 : geom3d_frame} {f2 : geom3d_frame} {sp3 : geom3d_space f3} {sp2 : geom3d_space f2} (ttr : geom3d_transform sp3 sp2) : geom3d_transform sp2 sp3 := ⟨(ttr.1).symm⟩ noncomputable def geom3d_transform.trans {f1 : geom3d_frame} {f2 : geom3d_frame} {f3 : geom3d_frame} {sp1 : geom3d_space f1} {sp2 : geom3d_space f2} {sp3 : geom3d_space f3} (ttr : geom3d_transform sp1 sp2) : geom3d_transform sp2 sp3 → geom3d_transform sp1 sp3 := λttr_, ⟨(ttr.1).trans ttr_.1⟩ noncomputable def geom3d_transform.transform_position3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : position3d s3 → position3d s2 := λt : position3d s3, ⟨tr.to_fm_tr.to_equiv t.to_point⟩ noncomputable def geom3d_transform.transform_displacement3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : displacement3d s3 → displacement3d s2 := λd, let as_pt : point s3 := ⟨λi, mk_pt real_scalar (d.coords i).coord⟩ in let tr_pt := (tr.to_equiv as_pt) in ⟨⟨λi, mk_vec real_scalar (tr_pt.coords i).coord⟩⟩ /- Orientation in 3D -/ variables {f : geom3d_frame} (s : geom3d_space f ) /- Background for the following definition: In an orientation object, id_vec keeps track of the physical dimension to which each basis vector belongs, allowing us to represent things like the product of a geometric space and a time space. orientation : Π {dim : ℕ} {id_vec : fin dim → ℕ} {f : fm K dim id_vec}, spc K f → Type -/ structure orientation3d extends orientation s := mk :: noncomputable instance o3i : inhabited (orientation3d s) := ⟨ ⟨mk_orientation s (λi, mk_vectr s ⟨[0,0,0],rfl⟩)⟩ ⟩ noncomputable def mk_orientation3d' /-(s1 s2 s3 s4 s5 s6 s7 s8 s9 : real_scalar)-/ (ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else -- if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr -- else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ : orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ noncomputable def mk_orientation3d (s1 s2 s3 s4 s5 s6 s7 s8 s9 : real_scalar) : orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ /- R = Ry(1)*Rx(2)*Rz(3) = | cos 1*cos 3+sin 1*sin 2*sin 3 cos 3*sin 1*sin 2-sin 3*cos 1 cos 2*sin 1 | | cos 2*sin 3 cos 3*cos 2 -sin 2 | | sin 3*cos 1*sin 2-sin 1*cos 3 sin 1*sin 3+cos 3*cos 1*sin 2 cos 2*cos 1 | -/ --okay, i can fill in this function now... noncomputable def mk_orientation3d_from_euler_angles (s1 s2 s3 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then (mk_displacement3d s ((real.cos s1)*(real.cos s3) + (real.sin s1*(real.sin s2)*(real.sin s3))) ((real.cos s3)*(real.sin s1)*(real.sin s2) - (real.sin s3)*(real.cos s1)) ((real.cos s2)*(real.sin s1))).to_vectr else if i.1 = 1 then (mk_displacement3d s ((real.cos s2)*(real.sin s3)) ((real.cos s3)*(real.cos s2)) (-(real.sin s2))).to_vectr else (mk_displacement3d s ((real.sin s3)*(real.cos s1)*(real.sin s2) - (real.sin s1)*(real.cos s3)) ((real.sin s1)*(real.sin s3) + (real.cos s3)*(real.cos s1)*(real.sin s2)) ((real.cos s2)*(real.cos s1))).to_vectr )⟩ noncomputable def mk_orientation3d_from_quaternion (s1 s2 s3 s4 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : orientation3d s := mk_orientation3d s (2*(s1*s1 + s2*s2) - 1) (2*(s2*s3 - s1*s4)) (2*(s2*s4 + s1*s3)) (2*(s2*s3 + s1*s4)) (2*(s1*s1 + s3*s3)) (2*(s3*s4 - s1*s2)) (2*(s2*s4 - s1*s3)) (2*(s3*s4 + s1*s2)) (2*(s1*s1 + s1*s1 + s4*s4) - 1) --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ noncomputable def geom3d_transform.transform_orientation {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : orientation3d s3 → orientation3d s2 := λo : orientation3d s3, ⟨mk_orientation s2 (λi, if i.1 = 0 then (tr.to_fm_tr.transform_vectr (o.to_orientation.to_vectr_basis.basis_vectrs ⟨0,by linarith⟩)) else if i.1 = 1 then (tr.to_fm_tr.transform_vectr (o.to_orientation.to_vectr_basis.basis_vectrs ⟨1,by linarith⟩)) else (tr.to_fm_tr.transform_vectr (o.to_orientation.to_vectr_basis.basis_vectrs ⟨2,by linarith⟩)) )⟩ -- ⟨tr.to_fm_tr.transform_orientation o.to_orientation⟩⟩ /- Rotations -/ structure rotation3d extends rotation s := mk :: /- noncomputable def mk_rotation3d (ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := ⟨mk_rotation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ -/ noncomputable def mk_rotation3d (s1 s2 s3 s4 s5 s6 s7 s8 s9 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := ⟨mk_rotation s (λi, if i.1 = 0 then (mk_displacement3d s s1 s2 s3).to_vectr else if i.1 = 1 then (mk_displacement3d s s4 s5 s6).to_vectr else (mk_displacement3d s s7 s8 s9).to_vectr )⟩ noncomputable instance r3i : inhabited (rotation3d s) := ⟨ mk_rotation3d s 1 1 1 1 1 1 1 1 1 ⟩ noncomputable def mk_rotation3d_from_quaternion (s1 s2 s3 s4 : real_scalar)--(ax1 : displacement3d s) (ax2 : displacement3d s) (ax3 : displacement3d s) : rotation3d s := mk_rotation3d s (2*(s1*s1 + s2*s2) - 1) (2*(s2*s3 - s1*s4)) (2*(s2*s4 + s1*s3)) (2*(s2*s3 + s1*s4)) (2*(s1*s1 + s3*s3)) (2*(s3*s4 - s1*s2)) (2*(s2*s4 - s1*s3)) (2*(s3*s4 + s1*s2)) (2*(s1*s1 + s1*s1 + s4*s4) - 1) --: orientation3d s := ⟨mk_orientation s (λi, if i.1 = 0 then ax1.to_vectr else if i.1 = 1 then ax2.to_vectr else ax3.to_vectr )⟩ /- Poses -/ structure pose3d := mk :: (orientation : orientation3d s) (position : position3d s) def mk_pose3d (orientation : orientation3d s) (position : position3d s) : pose3d s := ⟨orientation,position⟩ noncomputable instance p3i : inhabited (pose3d s) := ⟨ ( mk_pose3d _ (mk_orientation3d _ 0 0 0 0 0 0 0 0 0) (mk_position3d _ 0 0 0) ) ⟩ noncomputable def geom3d_transform.transform_pose3d {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : pose3d s3 → pose3d s2 := λp :_, (⟨tr.transform_orientation p.orientation, tr.transform_position3d p.position⟩:pose3d s2) notation tr⬝t := geom3d_transform.transform_pose3d tr t noncomputable def geom3d_transform.translation {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : geom3d_transform s3 s2 → displacement3d s2 := inhabited.default _ /- how to fill this in -/ noncomputable def geom3d_transform.rotation {f3 : geom3d_frame} {s3 : geom3d_space f3} {f2 : geom3d_frame} {s2 : geom3d_space f2} (tr: geom3d_transform s3 s2 ) : geom3d_transform s3 s2 → orientation3d s2 := inhabited.default _ /- how to fill this in -/
1a9cdf05c455ab0a6883ea4abda91ab142414b14
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/exp/fv.lean
cab7d60e587d3611e88f11ac85dd92946d63dab0
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,352
lean
import .core namespace tts ------------------------------------------------------------------ namespace exp ------------------------------------------------------------------ variables {V : Type} [decidable_eq V] -- Type of variable names variables {v : V} -- Variable names variables {x y : tagged V} -- Variables variables {ea eb ed ef : exp V} -- Expressions open occurs /-- Get the free variables of an expression -/ def fv : exp V → finset (tagged V) | (var bound _) := ∅ | (var free x) := {x} | (app ef ea) := fv ef ∪ fv ea | (lam _ eb) := fv eb | (let_ _ ed eb) := fv ed ∪ fv eb @[simp] theorem fv_var_bound : x ∉ fv (var bound y) := finset.not_mem_empty x @[simp] theorem fv_var_free : x ∉ fv (var free y) ↔ x ≠ y := ⟨finset.not_mem_singleton.mp, λ p h, absurd (finset.mem_of_mem_insert_of_ne h p) (finset.not_mem_empty x)⟩ @[simp] theorem fv_app : x ∉ fv (app ef ea) ↔ x ∉ fv ef ∧ x ∉ fv ea := finset.not_mem_union @[simp] theorem fv_lam : x ∉ fv (lam v eb) ↔ x ∉ fv eb := ⟨by rw fv; exact id, by rw fv; exact id⟩ @[simp] theorem fv_let_ : x ∉ fv (let_ v ed eb) ↔ x ∉ fv ed ∧ x ∉ fv eb := finset.not_mem_union end /- namespace -/ exp -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
e4f0879cdb3c43d4e86a2536645e7e044bbfc3ad
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/polynomial/eval.lean
fb9fe1b2ed7ebdc21eb394b30f9c38aa7fab904b
[ "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
34,240
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.degree.definitions import data.polynomial.induction /-! # Theory of univariate polynomials The main defs here are `eval₂`, `eval`, and `map`. We give several lemmas about their interaction with each other and with module operations. -/ noncomputable theory open finset add_monoid_algebra open_locale big_operators polynomial namespace polynomial universes u v w y variables {R : Type u} {S : Type v} {T : Type w} {ι : Type y} {a b : R} {m n : ℕ} section semiring variables [semiring R] {p q r : R[X]} section variables [semiring S] variables (f : R →+* S) (x : S) /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : R[X]) : S := p.sum (λ e a, f a * x ^ e) lemma eval₂_eq_sum {f : R →+* S} {x : S} : p.eval₂ f x = p.sum (λ e a, f a * x ^ e) := rfl lemma eval₂_congr {R S : Type*} [semiring R] [semiring S] {f g : R →+* S} {s t : S} {φ ψ : R[X]} : f = g → s = t → φ = ψ → eval₂ f s φ = eval₂ g t ψ := by rintro rfl rfl rfl; refl @[simp] lemma eval₂_at_zero : p.eval₂ f 0 = f (coeff p 0) := by simp only [eval₂_eq_sum, zero_pow_eq, mul_ite, mul_zero, mul_one, sum, not_not, mem_support_iff, sum_ite_eq', ite_eq_left_iff, ring_hom.map_zero, implies_true_iff, eq_self_iff_true] {contextual := tt} @[simp] lemma eval₂_zero : (0 : R[X]).eval₂ f x = 0 := by simp [eval₂_eq_sum] @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [eval₂_eq_sum] @[simp] lemma eval₂_monomial {n : ℕ} {r : R} : (monomial n r).eval₂ f x = (f r) * x^n := by simp [eval₂_eq_sum] @[simp] lemma eval₂_X_pow {n : ℕ} : (X^n).eval₂ f x = x^n := begin rw X_pow_eq_monomial, convert eval₂_monomial f x, simp, end @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := by { apply sum_add_index; simp [add_mul] } @[simp] lemma eval₂_one : (1 : R[X]).eval₂ f x = 1 := by rw [← C_1, eval₂_C, f.map_one] @[simp] lemma eval₂_bit0 : (bit0 p).eval₂ f x = bit0 (p.eval₂ f x) := by rw [bit0, eval₂_add, bit0] @[simp] lemma eval₂_bit1 : (bit1 p).eval₂ f x = bit1 (p.eval₂ f x) := by rw [bit1, eval₂_add, eval₂_bit0, eval₂_one, bit1] @[simp] lemma eval₂_smul (g : R →+* S) (p : R[X]) (x : S) {s : R} : eval₂ g x (s • p) = g s * eval₂ g x p := begin have A : p.nat_degree < p.nat_degree.succ := nat.lt_succ_self _, have B : (s • p).nat_degree < p.nat_degree.succ := (nat_degree_smul_le _ _).trans_lt A, rw [eval₂_eq_sum, eval₂_eq_sum, sum_over_range' _ _ _ A, sum_over_range' _ _ _ B]; simp [mul_sum, mul_assoc], end @[simp] lemma eval₂_C_X : eval₂ C X p = p := polynomial.induction_on' p (λ p q hp hq, by simp [hp, hq]) (λ n x, by rw [eval₂_monomial, ← smul_X_eq_monomial, C_mul']) /-- `eval₂_add_monoid_hom (f : R →+* S) (x : S)` is the `add_monoid_hom` from `R[X]` to `S` obtained by evaluating the pushforward of `p` along `f` at `x`. -/ @[simps] def eval₂_add_monoid_hom : R[X] →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ _ _, eval₂_add _ _ } @[simp] lemma eval₂_nat_cast (n : ℕ) : (n : R[X]).eval₂ f x = n := begin induction n with n ih, { simp only [eval₂_zero, nat.cast_zero] }, { rw [n.cast_succ, eval₂_add, ih, eval₂_one, n.cast_succ] } end variables [semiring T] lemma eval₂_sum (p : T[X]) (g : ℕ → T → R[X]) (x : S) : (p.sum g).eval₂ f x = p.sum (λ n a, (g n a).eval₂ f x) := begin let T : R[X] →+ S := { to_fun := eval₂ f x, map_zero' := eval₂_zero _ _, map_add' := λ p q, eval₂_add _ _ }, have A : ∀ y, eval₂ f x y = T y := λ y, rfl, simp only [A], rw [sum, T.map_sum, sum] end lemma eval₂_list_sum (l : list R[X]) (x : S) : eval₂ f x l.sum = (l.map (eval₂ f x)).sum := map_list_sum (eval₂_add_monoid_hom f x) l lemma eval₂_multiset_sum (s : multiset R[X]) (x : S) : eval₂ f x s.sum = (s.map (eval₂ f x)).sum := map_multiset_sum (eval₂_add_monoid_hom f x) s lemma eval₂_finset_sum (s : finset ι) (g : ι → R[X]) (x : S) : (∑ i in s, g i).eval₂ f x = ∑ i in s, (g i).eval₂ f x := map_sum (eval₂_add_monoid_hom f x) _ _ lemma eval₂_of_finsupp {f : R →+* S} {x : S} {p : add_monoid_algebra R ℕ} : eval₂ f x (⟨p⟩ : R[X]) = lift_nc ↑f (powers_hom S x) p := by { simp only [eval₂_eq_sum, sum, to_finsupp_sum, support, coeff], refl } lemma eval₂_mul_noncomm (hf : ∀ k, commute (f $ q.coeff k) x) : eval₂ f x (p * q) = eval₂ f x p * eval₂ f x q := begin rcases p, rcases q, simp only [coeff] at hf, simp only [←of_finsupp_mul, eval₂_of_finsupp], exact lift_nc_mul _ _ p q (λ k n hn, (hf k).pow_right n) end @[simp] lemma eval₂_mul_X : eval₂ f x (p * X) = eval₂ f x p * x := begin refine trans (eval₂_mul_noncomm _ _ $ λ k, _) (by rw eval₂_X), rcases em (k = 1) with (rfl|hk), { simp }, { simp [coeff_X_of_ne_one hk] } end @[simp] lemma eval₂_X_mul : eval₂ f x (X * p) = eval₂ f x p * x := by rw [X_mul, eval₂_mul_X] lemma eval₂_mul_C' (h : commute (f a) x) : eval₂ f x (p * C a) = eval₂ f x p * f a := begin rw [eval₂_mul_noncomm, eval₂_C], intro k, by_cases hk : k = 0, { simp only [hk, h, coeff_C_zero, coeff_C_ne_zero] }, { simp only [coeff_C_ne_zero hk, ring_hom.map_zero, commute.zero_left] } end lemma eval₂_list_prod_noncomm (ps : list R[X]) (hf : ∀ (p ∈ ps) k, commute (f $ coeff p k) x) : eval₂ f x ps.prod = (ps.map (polynomial.eval₂ f x)).prod := begin induction ps using list.reverse_rec_on with ps p ihp, { simp }, { simp only [list.forall_mem_append, list.forall_mem_singleton] at hf, simp [eval₂_mul_noncomm _ _ hf.2, ihp hf.1] } end /-- `eval₂` as a `ring_hom` for noncommutative rings -/ def eval₂_ring_hom' (f : R →+* S) (x : S) (hf : ∀ a, commute (f a) x) : R[X] →+* S := { to_fun := eval₂ f x, map_add' := λ _ _, eval₂_add _ _, map_zero' := eval₂_zero _ _, map_mul' := λ p q, eval₂_mul_noncomm f x (λ k, hf $ coeff q k), map_one' := eval₂_one _ _ } end /-! We next prove that eval₂ is multiplicative as long as target ring is commutative (even if the source ring is not). -/ section eval₂ section variables [semiring S] (f : R →+* S) (x : S) lemma eval₂_eq_sum_range : p.eval₂ f x = ∑ i in finset.range (p.nat_degree + 1), f (p.coeff i) * x^i := trans (congr_arg _ p.as_sum_range) (trans (eval₂_finset_sum f _ _ x) (congr_arg _ (by simp))) lemma eval₂_eq_sum_range' (f : R →+* S) {p : R[X]} {n : ℕ} (hn : p.nat_degree < n) (x : S) : eval₂ f x p = ∑ i in finset.range n, f (p.coeff i) * x ^ i := begin rw [eval₂_eq_sum, p.sum_over_range' _ _ hn], intro i, rw [f.map_zero, zero_mul] end end section variables [comm_semiring S] (f : R →+* S) (x : S) @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := eval₂_mul_noncomm _ _ $ λ k, commute.all _ _ lemma eval₂_mul_eq_zero_of_left (q : R[X]) (hp : p.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_left hp (q.eval₂ f x) end lemma eval₂_mul_eq_zero_of_right (p : R[X]) (hq : q.eval₂ f x = 0) : (p * q).eval₂ f x = 0 := begin rw eval₂_mul f x, exact mul_eq_zero_of_right (p.eval₂ f x) hq end /-- `eval₂` as a `ring_hom` -/ def eval₂_ring_hom (f : R →+* S) (x : S) : R[X] →+* S := { map_one' := eval₂_one _ _, map_mul' := λ _ _, eval₂_mul _ _, ..eval₂_add_monoid_hom f x } @[simp] lemma coe_eval₂_ring_hom (f : R →+* S) (x) : ⇑(eval₂_ring_hom f x) = eval₂ f x := rfl lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := (eval₂_ring_hom _ _).map_pow _ _ lemma eval₂_dvd : p ∣ q → eval₂ f x p ∣ eval₂ f x q := (eval₂_ring_hom f x).map_dvd lemma eval₂_eq_zero_of_dvd_of_eval₂_eq_zero (h : p ∣ q) (h0 : eval₂ f x p = 0) : eval₂ f x q = 0 := zero_dvd_iff.mp (h0 ▸ eval₂_dvd f x h) lemma eval₂_list_prod (l : list R[X]) (x : S) : eval₂ f x l.prod = (l.map (eval₂ f x)).prod := map_list_prod (eval₂_ring_hom f x) l end end eval₂ section eval variables {x : R} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : R → R[X] → R := eval₂ (ring_hom.id _) lemma eval_eq_sum : p.eval x = p.sum (λ e a, a * x ^ e) := rfl lemma eval_eq_sum_range {p : R[X]} (x : R) : p.eval x = ∑ i in finset.range (p.nat_degree + 1), p.coeff i * x ^ i := by rw [eval_eq_sum, sum_over_range]; simp lemma eval_eq_sum_range' {p : R[X]} {n : ℕ} (hn : p.nat_degree < n) (x : R) : p.eval x = ∑ i in finset.range n, p.coeff i * x ^ i := by rw [eval_eq_sum, p.sum_over_range' _ _ hn]; simp @[simp] lemma eval₂_at_apply {S : Type*} [semiring S] (f : R →+* S) (r : R) : p.eval₂ f (f r) = f (p.eval r) := begin rw [eval₂_eq_sum, eval_eq_sum, sum, sum, f.map_sum], simp only [f.map_mul, f.map_pow], end @[simp] lemma eval₂_at_one {S : Type*} [semiring S] (f : R →+* S) : p.eval₂ f 1 = f (p.eval 1) := begin convert eval₂_at_apply f 1, simp, end @[simp] lemma eval₂_at_nat_cast {S : Type*} [semiring S] (f : R →+* S) (n : ℕ) : p.eval₂ f n = f (p.eval n) := begin convert eval₂_at_apply f n, simp, end @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_nat_cast {n : ℕ} : (n : R[X]).eval x = n := by simp only [←C_eq_nat_cast, eval_C] @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_monomial {n a} : (monomial n a).eval x = a * x^n := eval₂_monomial _ _ @[simp] lemma eval_zero : (0 : R[X]).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : R[X]).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_bit0 : (bit0 p).eval x = bit0 (p.eval x) := eval₂_bit0 _ _ @[simp] lemma eval_bit1 : (bit1 p).eval x = bit1 (p.eval x) := eval₂_bit1 _ _ @[simp] lemma eval_smul [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p : R[X]) (x : R) : (s • p).eval x = s • p.eval x := by rw [← smul_one_smul R s p, eval, eval₂_smul, ring_hom.id_apply, smul_one_mul] @[simp] lemma eval_C_mul : (C a * p).eval x = a * p.eval x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [mul_add, eval_add, ph, qh], }, { intros n b, simp only [mul_assoc, C_mul_monomial, eval_monomial], } end /-- A reformulation of the expansion of (1 + y)^d: $$(d + 1) (1 + y)^d - (d + 1)y^d = \sum_{i = 0}^d {d + 1 \choose i} \cdot i \cdot y^{i - 1}.$$ -/ lemma eval_monomial_one_add_sub [comm_ring S] (d : ℕ) (y : S) : eval (1 + y) (monomial d (d + 1 : S)) - eval y (monomial d (d + 1 : S)) = ∑ (x_1 : ℕ) in range (d + 1), ↑((d + 1).choose x_1) * (↑x_1 * y ^ (x_1 - 1)) := begin have cast_succ : (d + 1 : S) = ((d.succ : ℕ) : S), { simp only [nat.cast_succ], }, rw [cast_succ, eval_monomial, eval_monomial, add_comm, add_pow], conv_lhs { congr, congr, skip, apply_congr, skip, rw [one_pow, mul_one, mul_comm], }, rw [sum_range_succ, mul_add, nat.choose_self, nat.cast_one, one_mul, add_sub_cancel, mul_sum, sum_range_succ', nat.cast_zero, zero_mul, mul_zero, add_zero], apply sum_congr rfl (λ y hy, _), rw [←mul_assoc, ←mul_assoc, ←nat.cast_mul, nat.succ_mul_choose_eq, nat.cast_mul, nat.add_sub_cancel], end /-- `polynomial.eval` as linear map -/ @[simps] def leval {R : Type*} [semiring R] (r : R) : R[X] →ₗ[R] R := { to_fun := λ f, f.eval r, map_add' := λ f g, eval_add, map_smul' := λ c f, eval_smul c f r } @[simp] lemma eval_nat_cast_mul {n : ℕ} : ((n : R[X]) * p).eval x = n * p.eval x := by rw [←C_eq_nat_cast, eval_C_mul] @[simp] lemma eval_mul_X : (p * X).eval x = p.eval x * x := begin apply polynomial.induction_on' p, { intros p q ph qh, simp only [add_mul, eval_add, ph, qh], }, { intros n a, simp only [←monomial_one_one_eq_X, monomial_mul_monomial, eval_monomial, mul_one, pow_succ', mul_assoc], } end @[simp] lemma eval_mul_X_pow {k : ℕ} : (p * X^k).eval x = p.eval x * x^k := begin induction k with k ih, { simp, }, { simp [pow_succ', ←mul_assoc, ih], } end lemma eval_sum (p : R[X]) (f : ℕ → R → R[X]) (x : R) : (p.sum f).eval x = p.sum (λ n a, (f n a).eval x) := eval₂_sum _ _ _ _ lemma eval_finset_sum (s : finset ι) (g : ι → R[X]) (x : R) : (∑ i in s, g i).eval x = ∑ i in s, (g i).eval x := eval₂_finset_sum _ _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : R[X]) (a : R) : Prop := p.eval a = 0 instance [decidable_eq R] : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma is_root.eq_zero (h : is_root p x) : eval x p = 0 := h lemma coeff_zero_eq_eval_zero (p : R[X]) : coeff p 0 = p.eval 0 := calc coeff p 0 = coeff p 0 * 0 ^ 0 : by simp ... = p.eval 0 : eq.symm $ finset.sum_eq_single _ (λ b _ hb, by simp [zero_pow (nat.pos_of_ne_zero hb)]) (by simp) lemma zero_is_root_of_coeff_zero_eq_zero {p : R[X]} (hp : p.coeff 0 = 0) : is_root p 0 := by rwa coeff_zero_eq_eval_zero at hp lemma is_root.dvd {R : Type*} [comm_semiring R] {p q : R[X]} {x : R} (h : p.is_root x) (hpq : p ∣ q) : q.is_root x := by rwa [is_root, eval, eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ hpq] lemma not_is_root_C (r a : R) (hr : r ≠ 0) : ¬ is_root (C r) a := by simpa using hr end eval section comp /-- The composition of polynomials as a polynomial. -/ def comp (p q : R[X]) : R[X] := p.eval₂ C q lemma comp_eq_sum_left : p.comp q = p.sum (λ e a, C a * q ^ e) := rfl @[simp] lemma comp_X : p.comp X = p := begin simp only [comp, eval₂, C_mul_X_pow_eq_monomial], exact sum_monomial_eq _ end @[simp] lemma X_comp : X.comp p = p := eval₂_X _ _ @[simp] lemma comp_C : p.comp (C a) = C (p.eval a) := by simp [comp, (C : R →+* _).map_sum] @[simp] lemma C_comp : (C a).comp p = C a := eval₂_C _ _ @[simp] lemma nat_cast_comp {n : ℕ} : (n : R[X]).comp p = n := by rw [←C_eq_nat_cast, C_comp] @[simp] lemma comp_zero : p.comp (0 : R[X]) = C (p.eval 0) := by rw [← C_0, comp_C] @[simp] lemma zero_comp : comp (0 : R[X]) p = 0 := by rw [← C_0, C_comp] @[simp] lemma comp_one : p.comp 1 = C (p.eval 1) := by rw [← C_1, comp_C] @[simp] lemma one_comp : comp (1 : R[X]) p = 1 := by rw [← C_1, C_comp] @[simp] lemma add_comp : (p + q).comp r = p.comp r + q.comp r := eval₂_add _ _ @[simp] lemma monomial_comp (n : ℕ) : (monomial n a).comp p = C a * p^n := eval₂_monomial _ _ @[simp] lemma mul_X_comp : (p * X).comp r = p.comp r * r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, add_mul, add_comp] }, { intros n b, simp only [pow_succ', mul_assoc, monomial_mul_X, monomial_comp] } end @[simp] lemma X_pow_comp {k : ℕ} : (X^k).comp p = p^k := begin induction k with k ih, { simp, }, { simp [pow_succ', mul_X_comp, ih], }, end @[simp] lemma mul_X_pow_comp {k : ℕ} : (p * X^k).comp r = p.comp r * r^k := begin induction k with k ih, { simp, }, { simp [ih, pow_succ', ←mul_assoc, mul_X_comp], }, end @[simp] lemma C_mul_comp : (C a * p).comp r = C a * p.comp r := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq, mul_add], }, { intros n b, simp [mul_assoc], } end @[simp] lemma nat_cast_mul_comp {n : ℕ} : ((n : R[X]) * p).comp r = n * p.comp r := by rw [←C_eq_nat_cast, C_mul_comp, C_eq_nat_cast] @[simp] lemma mul_comp {R : Type*} [comm_semiring R] (p q r : R[X]) : (p * q).comp r = p.comp r * q.comp r := eval₂_mul _ _ @[simp] lemma pow_comp {R : Type*} [comm_semiring R] (p q : R[X]) (n : ℕ) : (p^n).comp q = (p.comp q)^n := ((monoid_hom.mk (λ r : R[X], r.comp q)) one_comp (λ r s, mul_comp r s q)).map_pow p n @[simp] lemma bit0_comp : comp (bit0 p : R[X]) q = bit0 (p.comp q) := by simp only [bit0, add_comp] @[simp] lemma bit1_comp : comp (bit1 p : R[X]) q = bit1 (p.comp q) := by simp only [bit1, add_comp, bit0_comp, one_comp] @[simp] lemma smul_comp [monoid S] [distrib_mul_action S R] [is_scalar_tower S R R] (s : S) (p q : R[X]) : (s • p).comp q = s • p.comp q := by rw [← smul_one_smul R s p, comp, comp, eval₂_smul, ← smul_eq_C_mul, smul_assoc, one_smul] lemma comp_assoc {R : Type*} [comm_semiring R] (φ ψ χ : R[X]) : (φ.comp ψ).comp χ = φ.comp (ψ.comp χ) := begin apply polynomial.induction_on φ; { intros, simp only [add_comp, mul_comp, C_comp, X_comp, pow_succ', ← mul_assoc, *] at * } end lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) : coeff (p.comp q) (nat_degree p * nat_degree q) = leading_coeff p * leading_coeff q ^ nat_degree p := begin rw [comp, eval₂, coeff_sum], convert finset.sum_eq_single p.nat_degree _ _, { simp only [coeff_nat_degree, coeff_C_mul, coeff_pow_mul_nat_degree] }, { assume b hbs hbp, refine coeff_eq_zero_of_nat_degree_lt ((nat_degree_mul_le).trans_lt _), rw [nat_degree_C, zero_add], refine (nat_degree_pow_le).trans_lt ((mul_lt_mul_right (pos_iff_ne_zero.mpr hqd0)).mpr _), exact lt_of_le_of_ne (le_nat_degree_of_mem_supp _ hbs) hbp }, { simp {contextual := tt} } end end comp section map variables [semiring S] variables (f : R →+* S) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : R[X] → S[X] := eval₂ (C.comp f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_monomial {n a} : (monomial n a).map f = monomial n (f a) := begin dsimp only [map], rw [eval₂_monomial, ← C_mul_X_pow_eq_monomial], refl, end @[simp] protected lemma map_zero : (0 : R[X]).map f = 0 := eval₂_zero _ _ @[simp] protected lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] protected lemma map_one : (1 : R[X]).map f = 1 := eval₂_one _ _ @[simp] protected lemma map_mul : (p * q).map f = p.map f * q.map f := by { rw [map, eval₂_mul_noncomm], exact λ k, (commute_X _).symm } @[simp] protected lemma map_smul (r : R) : (r • p).map f = f r • p.map f := by rw [map, eval₂_smul, ring_hom.comp_apply, C_mul'] /-- `polynomial.map` as a `ring_hom`. -/ -- `map` is a ring-hom unconditionally, and theoretically the definition could be replaced, -- but this turns out not to be easy because `p.map f` does not resolve to `polynomial.map` -- if `map` is a `ring_hom` instead of a plain function; the elaborator does not try to coerce -- to a function before trying field (dot) notation (this may be technically infeasible); -- the relevant code is (both lines): https://github.com/leanprover-community/ -- lean/blob/487ac5d7e9b34800502e1ddf3c7c806c01cf9d51/src/frontends/lean/elaborator.cpp#L1876-L1913 def map_ring_hom (f : R →+* S) : R[X] →+* S[X] := { to_fun := polynomial.map f, map_add' := λ _ _, polynomial.map_add f, map_zero' := polynomial.map_zero f, map_mul' := λ _ _, polynomial.map_mul f, map_one' := polynomial.map_one f } @[simp] lemma coe_map_ring_hom (f : R →+* S) : ⇑(map_ring_hom f) = map f := rfl -- This is protected to not clash with the global `map_nat_cast`. @[simp] protected theorem map_nat_cast (n : ℕ) : (n : R[X]).map f = n := map_nat_cast (map_ring_hom f) n @[simp] protected lemma map_bit0 : (bit0 p).map f = bit0 (p.map f) := map_bit0 (map_ring_hom f) p @[simp] protected lemma map_bit1 : (bit1 p).map f = bit1 (p.map f) := map_bit1 (map_ring_hom f) p --TODO rename to `map_dvd_map` lemma map_dvd (f : R →+* S) {x y : R[X]} : x ∣ y → x.map f ∣ y.map f := (map_ring_hom f).map_dvd @[simp] lemma coeff_map (n : ℕ) : coeff (p.map f) n = f (coeff p n) := begin rw [map, eval₂, coeff_sum, sum], conv_rhs { rw [← sum_C_mul_X_pow_eq p, coeff_sum, sum, ring_hom.map_sum], }, refine finset.sum_congr rfl (λ x hx, _), simp [function.comp, coeff_C_mul_X_pow, f.map_mul], split_ifs; simp [f.map_zero], end /-- If `R` and `S` are isomorphic, then so are their polynomial rings. -/ @[simps] def map_equiv (e : R ≃+* S) : R[X] ≃+* S[X] := ring_equiv.of_hom_inv (map_ring_hom (e : R →+* S)) (map_ring_hom (e.symm : S →+* R)) (by ext; simp) (by ext; simp) lemma map_map [semiring T] (g : S →+* T) (p : R[X]) : (p.map f).map g = p.map (g.comp f) := ext (by simp [coeff_map]) @[simp] lemma map_id : p.map (ring_hom.id _) = p := by simp [polynomial.ext_iff, coeff_map] lemma eval₂_eq_eval_map {x : S} : p.eval₂ f x = (p.map f).eval x := begin apply polynomial.induction_on' p, { intros p q hp hq, simp [hp, hq], }, { intros n r, simp, } end lemma map_injective (hf : function.injective f) : function.injective (map f) := λ p q h, ext $ λ m, hf $ by rw [← coeff_map f, ← coeff_map f, h] lemma map_surjective (hf : function.surjective f) : function.surjective (map f) := λ p, polynomial.induction_on' p (λ p q hp hq, let ⟨p', hp'⟩ := hp, ⟨q', hq'⟩ := hq in ⟨p' + q', by rw [polynomial.map_add f, hp', hq']⟩) (λ n s, let ⟨r, hr⟩ := hf s in ⟨monomial n r, by rw [map_monomial f, hr]⟩) lemma degree_map_le (p : R[X]) : degree (p.map f) ≤ degree p := begin apply (degree_le_iff_coeff_zero _ _).2 (λ m hm, _), rw degree_lt_iff_coeff_zero at hm, simp [hm m le_rfl], end lemma nat_degree_map_le (p : R[X]) : nat_degree (p.map f) ≤ nat_degree p := nat_degree_le_nat_degree (degree_map_le f p) variables {f} protected lemma map_eq_zero_iff (hf : function.injective f) : p.map f = 0 ↔ p = 0 := map_eq_zero_iff (map_ring_hom f) (map_injective f hf) protected lemma map_ne_zero_iff (hf : function.injective f) : p.map f ≠ 0 ↔ p ≠ 0 := (polynomial.map_eq_zero_iff hf).not lemma map_monic_eq_zero_iff (hp : p.monic) : p.map f = 0 ↔ ∀ x, f x = 0 := ⟨ λ hfp x, calc f x = f x * f p.leading_coeff : by simp only [mul_one, hp.leading_coeff, f.map_one] ... = f x * (p.map f).coeff p.nat_degree : congr_arg _ (coeff_map _ _).symm ... = 0 : by simp only [hfp, mul_zero, coeff_zero], λ h, ext (λ n, by simp only [h, coeff_map, coeff_zero]) ⟩ lemma map_monic_ne_zero (hp : p.monic) [nontrivial S] : p.map f ≠ 0 := λ h, f.map_one_ne_zero ((map_monic_eq_zero_iff hp).mp h _) lemma degree_map_eq_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : degree (p.map f) = degree p := le_antisymm (degree_map_le f _) $ have hp0 : p ≠ 0, from leading_coeff_ne_zero.mp (λ hp0, hf (trans (congr_arg _ hp0) f.map_zero)), begin rw [degree_eq_nat_degree hp0], refine le_degree_of_ne_zero _, rw [coeff_map], exact hf end lemma nat_degree_map_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map_eq_of_leading_coeff_ne_zero f hf) lemma leading_coeff_map_of_leading_coeff_ne_zero (f : R →+* S) (hf : f (leading_coeff p) ≠ 0) : leading_coeff (p.map f) = f (leading_coeff p) := begin unfold leading_coeff, rw [coeff_map, nat_degree_map_of_leading_coeff_ne_zero f hf], end variables (f) @[simp] lemma map_ring_hom_id : map_ring_hom (ring_hom.id R) = ring_hom.id R[X] := ring_hom.ext $ λ x, map_id @[simp] lemma map_ring_hom_comp [semiring T] (f : S →+* T) (g : R →+* S) : (map_ring_hom f).comp (map_ring_hom g) = map_ring_hom (f.comp g) := ring_hom.ext $ polynomial.map_map g f protected lemma map_list_prod (L : list R[X]) : L.prod.map f = (L.map $ map f).prod := eq.symm $ list.prod_hom _ (map_ring_hom f).to_monoid_hom @[simp] protected lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := (map_ring_hom f).map_pow _ _ lemma mem_map_srange {p : S[X]} : p ∈ (map_ring_hom f).srange ↔ ∀ n, p.coeff n ∈ f.srange := begin split, { rintro ⟨p, rfl⟩ n, rw [coe_map_ring_hom, coeff_map], exact set.mem_range_self _ }, { intro h, rw p.as_sum_range_C_mul_X_pow, refine (map_ring_hom f).srange.sum_mem _, intros i hi, rcases h i with ⟨c, hc⟩, use [C c * X^i], rw [coe_map_ring_hom, polynomial.map_mul, map_C, hc, polynomial.map_pow, map_X] } end lemma mem_map_range {R S : Type*} [ring R] [ring S] (f : R →+* S) {p : S[X]} : p ∈ (map_ring_hom f).range ↔ ∀ n, p.coeff n ∈ f.range := mem_map_srange f lemma eval₂_map [semiring T] (g : S →+* T) (x : T) : (p.map f).eval₂ g x = p.eval₂ (g.comp f) x := by rw [eval₂_eq_eval_map, eval₂_eq_eval_map, map_map] lemma eval_map (x : S) : (p.map f).eval x = p.eval₂ f x := (eval₂_eq_eval_map f).symm protected lemma map_sum {ι : Type*} (g : ι → R[X]) (s : finset ι) : (∑ i in s, g i).map f = ∑ i in s, (g i).map f := (map_ring_hom f).map_sum _ _ lemma map_comp (p q : R[X]) : map f (p.comp q) = (map f p).comp (map f q) := polynomial.induction_on p (by simp only [map_C, forall_const, C_comp, eq_self_iff_true]) (by simp only [polynomial.map_add, add_comp, forall_const, implies_true_iff, eq_self_iff_true] {contextual := tt}) (by simp only [pow_succ', ←mul_assoc, comp, forall_const, eval₂_mul_X, implies_true_iff, eq_self_iff_true, map_X, polynomial.map_mul] {contextual := tt}) @[simp] lemma eval_zero_map (f : R →+* S) (p : R[X]) : (p.map f).eval 0 = f (p.eval 0) := by simp [←coeff_zero_eq_eval_zero] @[simp] lemma eval_one_map (f : R →+* S) (p : R[X]) : (p.map f).eval 1 = f (p.eval 1) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [one_pow, mul_one, eval_monomial, map_monomial] } end @[simp] lemma eval_nat_cast_map (f : R →+* S) (p : R[X]) (n : ℕ) : (p.map f).eval n = f (p.eval n) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [map_nat_cast f, eval_monomial, map_monomial, f.map_pow, f.map_mul] } end @[simp] lemma eval_int_cast_map {R S : Type*} [ring R] [ring S] (f : R →+* S) (p : R[X]) (i : ℤ) : (p.map f).eval i = f (p.eval i) := begin apply polynomial.induction_on' p, { intros p q hp hq, simp only [hp, hq, polynomial.map_add, ring_hom.map_add, eval_add] }, { intros n r, simp only [map_int_cast, eval_monomial, map_monomial, map_pow, map_mul] } end end map /-! After having set up the basic theory of `eval₂`, `eval`, `comp`, and `map`, we make `eval₂` irreducible. Perhaps we can make the others irreducible too? -/ attribute [irreducible] polynomial.eval₂ section hom_eval₂ variables [semiring S] [semiring T] (f : R →+* S) (g : S →+* T) (p) lemma hom_eval₂ (x : S) : g (p.eval₂ f x) = p.eval₂ (g.comp f) (g x) := by rw [←eval₂_map, eval₂_at_apply, eval_map] end hom_eval₂ end semiring section comm_semiring section eval section variables [semiring R] {p q : R[X]} {x : R} [semiring S] (f : R →+* S) lemma eval₂_hom (x : R) : p.eval₂ f (f x) = f (p.eval x) := (ring_hom.comp_id f) ▸ (hom_eval₂ p (ring_hom.id R) f x).symm end section variables [semiring R] {p q : R[X]} {x : R} [comm_semiring S] (f : R →+* S) lemma eval₂_comp {x : S} : eval₂ f x (p.comp q) = eval₂ f (eval₂ f x q) p := by rw [comp, p.as_sum_range]; simp [eval₂_finset_sum, eval₂_pow] end section variables [comm_semiring R] {p q : R[X]} {x : R} [comm_semiring S] (f : R →+* S) @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ /-- `eval r`, regarded as a ring homomorphism from `R[X]` to `R`. -/ def eval_ring_hom : R → R[X] →+* R := eval₂_ring_hom (ring_hom.id _) @[simp] lemma coe_eval_ring_hom (r : R) : ((eval_ring_hom r) : R[X] → R) = eval r := rfl lemma eval_ring_hom_zero : eval_ring_hom 0 = constant_coeff := fun_like.ext _ _ $ λ p, p.coeff_zero_eq_eval_zero.symm @[simp] lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ @[simp] lemma eval_comp : (p.comp q).eval x = p.eval (q.eval x) := begin apply polynomial.induction_on' p, { intros r s hr hs, simp [add_comp, hr, hs], }, { intros n a, simp, } end /-- `comp p`, regarded as a ring homomorphism from `R[X]` to itself. -/ def comp_ring_hom : R[X] → R[X] →+* R[X] := eval₂_ring_hom C @[simp] lemma coe_comp_ring_hom (q : R[X]) : (comp_ring_hom q : R[X] → R[X]) = λ p, comp p q := rfl lemma coe_comp_ring_hom_apply (p q : R[X]) : (comp_ring_hom q : R[X] → R[X]) p = comp p q := rfl lemma root_mul_left_of_is_root (p : R[X]) {q : R[X]} : is_root q a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, mul_zero] lemma root_mul_right_of_is_root {p : R[X]} (q : R[X]) : is_root p a → is_root (p * q) a := λ H, by rw [is_root, eval_mul, is_root.def.1 H, zero_mul] lemma eval₂_multiset_prod (s : multiset R[X]) (x : S) : eval₂ f x s.prod = (s.map (eval₂ f x)).prod := map_multiset_prod (eval₂_ring_hom f x) s lemma eval₂_finset_prod (s : finset ι) (g : ι → R[X]) (x : S) : (∏ i in s, g i).eval₂ f x = ∏ i in s, (g i).eval₂ f x := map_prod (eval₂_ring_hom f x) _ _ /-- Polynomial evaluation commutes with `list.prod` -/ lemma eval_list_prod (l : list R[X]) (x : R) : eval x l.prod = (l.map (eval x)).prod := (eval_ring_hom x).map_list_prod l /-- Polynomial evaluation commutes with `multiset.prod` -/ lemma eval_multiset_prod (s : multiset R[X]) (x : R) : eval x s.prod = (s.map (eval x)).prod := (eval_ring_hom x).map_multiset_prod s /-- Polynomial evaluation commutes with `finset.prod` -/ lemma eval_prod {ι : Type*} (s : finset ι) (p : ι → R[X]) (x : R) : eval x (∏ j in s, p j) = ∏ j in s, eval x (p j) := (eval_ring_hom x).map_prod _ _ lemma list_prod_comp (l : list R[X]) (q : R[X]) : l.prod.comp q = (l.map (λ p : R[X], p.comp q)).prod := map_list_prod (comp_ring_hom q) _ lemma multiset_prod_comp (s : multiset R[X]) (q : R[X]) : s.prod.comp q = (s.map (λ p : R[X], p.comp q)).prod := map_multiset_prod (comp_ring_hom q) _ lemma prod_comp {ι : Type*} (s : finset ι) (p : ι → R[X]) (q : R[X]) : (∏ j in s, p j).comp q = ∏ j in s, (p j).comp q := map_prod (comp_ring_hom q) _ _ lemma is_root_prod {R} [comm_ring R] [is_domain R] {ι : Type*} (s : finset ι) (p : ι → R[X]) (x : R) : is_root (∏ j in s, p j) x ↔ ∃ i ∈ s, is_root (p i) x := by simp only [is_root, eval_prod, finset.prod_eq_zero_iff] lemma eval_dvd : p ∣ q → eval x p ∣ eval x q := eval₂_dvd _ _ lemma eval_eq_zero_of_dvd_of_eval_eq_zero : p ∣ q → eval x p = 0 → eval x q = 0 := eval₂_eq_zero_of_dvd_of_eval₂_eq_zero _ _ @[simp] lemma eval_geom_sum {R} [comm_semiring R] {n : ℕ} {x : R} : eval x (∑ i in range n, X ^ i) = ∑ i in range n, x ^ i := by simp [eval_finset_sum] end end eval section map lemma support_map_subset [semiring R] [semiring S] (f : R →+* S) (p : R[X]) : (map f p).support ⊆ p.support := begin intros x, contrapose!, simp { contextual := tt }, end lemma support_map_of_injective [semiring R] [semiring S] (p : R[X]) {f : R →+* S} (hf : function.injective f) : (map f p).support = p.support := by simp_rw [finset.ext_iff, mem_support_iff, coeff_map, ←map_zero f, hf.ne_iff, iff_self, forall_const] variables [comm_semiring R] [comm_semiring S] (f : R →+* S) protected lemma map_multiset_prod (m : multiset R[X]) : m.prod.map f = (m.map $ map f).prod := eq.symm $ multiset.prod_hom _ (map_ring_hom f).to_monoid_hom protected lemma map_prod {ι : Type*} (g : ι → R[X]) (s : finset ι) : (∏ i in s, g i).map f = ∏ i in s, (g i).map f := (map_ring_hom f).map_prod _ _ lemma is_root.map {f : R →+* S} {x : R} {p : R[X]} (h : is_root p x) : is_root (p.map f) (f x) := by rw [is_root, eval_map, eval₂_hom, h.eq_zero, f.map_zero] lemma is_root.of_map {R} [comm_ring R] {f : R →+* S} {x : R} {p : R[X]} (h : is_root (p.map f) (f x)) (hf : function.injective f) : is_root p x := by rwa [is_root, ←(injective_iff_map_eq_zero' f).mp hf, ←eval₂_hom, ←eval_map] lemma is_root_map_iff {R : Type*} [comm_ring R] {f : R →+* S} {x : R} {p : R[X]} (hf : function.injective f) : is_root (p.map f) (f x) ↔ is_root p x := ⟨λ h, h.of_map hf, λ h, h.map⟩ end map end comm_semiring section ring variables [ring R] {p q r : R[X]} lemma C_neg : C (-a) = -C a := ring_hom.map_neg C a lemma C_sub : C (a - b) = C a - C b := ring_hom.map_sub C a b @[simp] protected lemma map_sub {S} [ring S] (f : R →+* S) : (p - q).map f = p.map f - q.map f := (map_ring_hom f).map_sub p q @[simp] protected lemma map_neg {S} [ring S] (f : R →+* S) : (-p).map f = -(p.map f) := (map_ring_hom f).map_neg p @[simp] lemma map_int_cast {S} [ring S] (f : R →+* S) (n : ℤ) : map f ↑n = ↑n := map_int_cast (map_ring_hom f) n @[simp] lemma eval_int_cast {n : ℤ} {x : R} : (n : R[X]).eval x = n := by simp only [←C_eq_int_cast, eval_C] @[simp] lemma eval₂_neg {S} [ring S] (f : R →+* S) {x : S} : (-p).eval₂ f x = -p.eval₂ f x := by rw [eq_neg_iff_add_eq_zero, ←eval₂_add, add_left_neg, eval₂_zero] @[simp] lemma eval₂_sub {S} [ring S] (f : R →+* S) {x : S} : (p - q).eval₂ f x = p.eval₂ f x - q.eval₂ f x := by rw [sub_eq_add_neg, eval₂_add, eval₂_neg, sub_eq_add_neg] @[simp] lemma eval_neg (p : R[X]) (x : R) : (-p).eval x = -p.eval x := eval₂_neg _ @[simp] lemma eval_sub (p q : R[X]) (x : R) : (p - q).eval x = p.eval x - q.eval x := eval₂_sub _ lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero, eq_comm] @[simp] lemma neg_comp : (-p).comp q = -p.comp q := eval₂_neg _ @[simp] lemma sub_comp : (p - q).comp r = p.comp r - q.comp r := eval₂_sub _ @[simp] lemma cast_int_comp (i : ℤ) : comp (i : R[X]) p = i := by cases i; simp end ring end polynomial
e65654e4448b4f48ebc6e89c948153f5795d125c
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/uni_bug1.lean
ca00c51ee8779159b5c7c43325b2c51a4cf2f70d
[ "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
176
lean
-- open nat prod constant R : nat → nat → Prop constant f (a b : nat) (H : R a b) : nat axiom Rtrue (a b : nat) : R a b #check f 1 0 (Rtrue (fst (prod.mk 1 (0:nat))) 0)
71da29d2068d33ddcee51aa57de0fb5da91bdedb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/widget/interactive_expr_auto.lean
10b9e5b4735fbc19df32e96847e5970a6fc2f962
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
439
lean
/- Copyright (c) E.W.Ayers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: E.W.Ayers -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.widget.basic import Mathlib.Lean3Lib.init.meta.widget.tactic_component import Mathlib.Lean3Lib.init.meta.tagged_format import Mathlib.Lean3Lib.init.data.punit import Mathlib.Lean3Lib.init.meta.mk_dec_eq_instance namespace Mathlib end Mathlib
95a70d6b2472e4a07db58b03584ca1edc27e549b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/LCNF/CompatibleTypes.lean
5ec1bb005dc7ed616a7b99acaee0f0f691211f71
[ "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
5,910
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.LCNF.InferType namespace Lean.Compiler.LCNF /-! # Compatible Types We used to type check LCNF after each compiler pass. However, we disable this capability because cast management was too costly. The casts may be needed to ensure the result of each pass is still typeable. However, these sanity checks are useful for catching silly mistakes. Thus, we have added an "LCNF type linter". When turned on, this "linter" option instructs the compiler to perform compatibility type checking in the LCNF code after some compiler passes. Recall most casts are only needed in functions that make heavy use of dependent types. We claim it is "defensible" to say this sanity checker is a linter. If the sanity checker fails, it means the user is "abusing" dependent types and performance may suffer at runtime. Here is an example of code that "abuses" dependent types: ``` def Tuple (α : Type u) : Nat → Type u | 0 => PUnit | 1 => α | n+2 => α × Tuple α (n+1) def mkConstTuple (a : α) : (n : Nat) → Tuple α n | 0 => ⟨⟩ | 1 => a | n+2 => (a, mkConstTuple a (n+1)) def Tuple.map (f : α → β) (xs : Tuple α n) : Tuple β n := match n with | 0 => ⟨⟩ | 1 => f xs | _+2 => match xs with | (a, xs) => (f a, Tuple.map f xs) ``` -/ /-- Quick check for `compatibleTypes`. It is not monadic, but it is incomplete because it does not eta-expand type formers. See comment at `compatibleTypes`. Remark: if the result is `true`, then `a` and `b` are indeed compatible. If it is `false`, we must use the full-check. -/ partial def compatibleTypesQuick (a b : Expr) : Bool := if a.isErased || b.isErased then true else let a' := a.headBeta let b' := b.headBeta if a != a' || b != b' then compatibleTypesQuick a' b' else if a == b then true else match a, b with -- Note that even after reducing to head-beta, we can still have `.app` terms. For example, -- an inductive constructor application such as `List Int` | .app f a, .app g b => compatibleTypesQuick f g && compatibleTypesQuick a b | .forallE _ d₁ b₁ _, .forallE _ d₂ b₂ _ => compatibleTypesQuick d₁ d₂ && compatibleTypesQuick b₁ b₂ | .lam _ d₁ b₁ _, .lam _ d₂ b₂ _ => compatibleTypesQuick d₁ d₂ && compatibleTypesQuick b₁ b₂ | .sort u, .sort v => Level.isEquiv u v | .const n us, .const m vs => n == m && List.isEqv us vs Level.isEquiv | _, _ => false /-- Complete check for `compatibleTypes`. It eta-expands type formers. See comment at `compatibleTypes`. -/ partial def InferType.compatibleTypesFull (a b : Expr) : InferTypeM Bool := do if a.isErased || b.isErased then return true else let a' := a.headBeta let b' := b.headBeta if a != a' || b != b' then compatibleTypesFull a' b' else if a == b then return true else match a, b with -- Note that even after reducing to head-beta, we can still have `.app` terms. For example, -- an inductive constructor application such as `List Int` | .app f a, .app g b => compatibleTypesFull f g <&&> compatibleTypesFull a b | .forallE n d₁ b₁ bi, .forallE _ d₂ b₂ _ => unless (← compatibleTypesFull d₁ d₂) do return false withLocalDecl n d₁ bi fun x => compatibleTypesFull (b₁.instantiate1 x) (b₂.instantiate1 x) | .lam n d₁ b₁ bi, .lam _ d₂ b₂ _ => unless (← compatibleTypesFull d₁ d₂) do return false withLocalDecl n d₁ bi fun x => compatibleTypesFull (b₁.instantiate1 x) (b₂.instantiate1 x) | .sort u, .sort v => return Level.isEquiv u v | .const n us, .const m vs => return n == m && List.isEqv us vs Level.isEquiv | _, _ => if a.isLambda then let some b ← etaExpand? b | return false compatibleTypesFull a b else if b.isLambda then let some a ← etaExpand? a | return false compatibleTypesFull a b else return false where etaExpand? (e : Expr) : InferTypeM (Option Expr) := do match (← inferType e).headBeta with | .forallE n d _ bi => /- In principle, `.app e (.bvar 0)` may not be a valid LCNF type sub-expression because `d` may not be a type former type, See remark `compatibleTypes` for a justification why this is ok. -/ return some (.lam n d (.app e (.bvar 0)) bi) | _ => return none /-- Return true if the LCNF types `a` and `b` are compatible. Remark: `a` and `b` can be type formers (e.g., `List`, or `fun (α : Type) => Nat → Nat × α`) Remark: We may need to eta-expand type formers to establish whether they are compatible or not. For example, suppose we have ``` fun (x : B) => Id B ◾ ◾ Id B ◾ ``` We must eta-expand `Id B ◾` to `fun (x : B) => Id B ◾ x`. Note that, we use `x` instead of `◾` to make the implementation simpler and skip the check whether `B` is a type former type. However, this simplification should not affect correctness since `◾` is compatible with everything. Remark: see comment at `isErasedCompatible`. Remark: because of "erasure confusion" see note above, we assume `◾` (aka `lcErasure`) is compatible with everything. This is a simplification. We used to use `isErasedCompatible`, but this only address item 1. For item 2, we would have to modify the `toLCNFType` function and make sure a type former is erased if the expected type is not always a type former (see `S.mk` type and example in the note above). -/ def InferType.compatibleTypes (a b : Expr) : InferTypeM Bool := do if compatibleTypesQuick a b then return true else compatibleTypesFull a b end Lean.Compiler.LCNF
e6a6a1489e7b85267b45d058e30abea1f4236c5c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1686.lean
57750fdecbc50c80bf8ffae1cf97ce3f525314f2
[ "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
227
lean
import Lean open Lean Meta def substIssue (hLocalDecl : LocalDecl) : MetaM Unit := do let error {α} _ : MetaM α := throwError "{hLocalDecl.type}" let some (_, lhs, rhs) ← matchEq? hLocalDecl.type | error () error ()
abeefbc6967f0afd5fd854a3d3c770915ed338e3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/default.lean
0b78bd13fb19a1b2c82fce54d3d6a363eb270920
[ "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
36
lean
import ring_theory.polynomial.basic
f8ff5da58dee0e8fc374861db3ac8ea782224793
3268ab3a126f0fef71459fbf170dc38efe5d0506
/algebra/module_chain_complex.hlean
6c5f03e4a45331483b047dadd08afb7f7710d01e
[ "Apache-2.0" ]
permissive
soraismus/Spectral
f043fed1a4e02ddfeba531769b2980eb817471f4
32512bf47db3a1b932856e7ed7c7830b1fc07ef0
refs/heads/master
1,585,628,705,579
1,538,609,948,000
1,538,609,974,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,795
hlean
/- Author: Jeremy Avigad -/ import homotopy.chain_complex .left_module .exactness ..move_to_lib open eq pointed sigma fiber equiv is_equiv sigma.ops is_trunc nat trunc open algebra function open chain_complex open succ_str open left_module structure module_chain_complex (R : Ring) (N : succ_str) : Type := (mod : N → LeftModule R) (hom : Π (n : N), mod (S n) →lm mod n) (is_chain_complex : Π (n : N) (x : mod (S (S n))), hom n (hom (S n) x) = 0) namespace module_chain_complex variables {R : Ring} {N : succ_str} definition mcc_mod [unfold 2] [coercion] (C : module_chain_complex R N) (n : N) : LeftModule R := module_chain_complex.mod C n definition mcc_carr [unfold 2] [coercion] (C : module_chain_complex R N) (n : N) : Type := C n definition mcc_pcarr [unfold 2] [coercion] (C : module_chain_complex R N) (n : N) : Set* := mcc_mod C n definition mcc_hom (C : module_chain_complex R N) {n : N} : C (S n) →lm C n := module_chain_complex.hom C n definition mcc_is_chain_complex (C : module_chain_complex R N) (n : N) (x : C (S (S n))) : mcc_hom C (mcc_hom C x) = 0 := module_chain_complex.is_chain_complex C n x protected definition to_chain_complex [coercion] (C : module_chain_complex R N) : chain_complex N := chain_complex.mk (λ n, mcc_pcarr C n) (λ n, pmap_of_homomorphism (@mcc_hom R N C n)) (mcc_is_chain_complex C) -- maybe we don't even need this? definition is_exact_at_m (C : module_chain_complex R N) (n : N) : Type := is_exact_at C n end module_chain_complex namespace left_module variable {R : Ring} variables {A₀ B₀ C₀ : LeftModule R} variables (f₀ : A₀ →lm B₀) (g₀ : B₀ →lm C₀) definition is_short_exact := @algebra.is_short_exact _ _ C₀ f₀ g₀ end left_module
35e45aeb7c2cea4f87db2b44eeec66010b9e14de
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/bool/basic.lean
bc94fe07905befd615a2a59be9619339efb88883
[ "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,935
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad -/ /-! # booleans > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/534 > Any changes to this file require a corresponding PR to mathlib4. This file proves various trivial lemmas about booleans and their relation to decidable propositions. ## Notations This file introduces the notation `!b` for `bnot b`, the boolean "not". ## Tags bool, boolean, De Morgan -/ prefix `!`:90 := bnot namespace bool -- TODO: duplicate of a lemma in core theorem coe_sort_tt : coe_sort.{1 1} tt = true := coe_sort_tt -- TODO: duplicate of a lemma in core theorem coe_sort_ff : coe_sort.{1 1} ff = false := coe_sort_ff -- TODO: duplicate of a lemma in core theorem to_bool_true {h} : @to_bool true h = tt := to_bool_true_eq_tt h -- TODO: duplicate of a lemma in core theorem to_bool_false {h} : @to_bool false h = ff := to_bool_false_eq_ff h @[simp] theorem to_bool_coe (b:bool) {h} : @to_bool b h = b := (show _ = to_bool b, by congr).trans (by cases b; refl) theorem coe_to_bool (p : Prop) [decidable p] : to_bool p ↔ p := to_bool_iff _ @[simp] lemma of_to_bool_iff {p : Prop} [decidable p] : to_bool p ↔ p := ⟨of_to_bool_true, _root_.to_bool_true⟩ @[simp] lemma tt_eq_to_bool_iff {p : Prop} [decidable p] : tt = to_bool p ↔ p := eq_comm.trans of_to_bool_iff @[simp] lemma ff_eq_to_bool_iff {p : Prop} [decidable p] : ff = to_bool p ↔ ¬ p := eq_comm.trans (to_bool_ff_iff _) @[simp] theorem to_bool_not (p : Prop) [decidable p] : to_bool (¬ p) = !(to_bool p) := by by_cases p; simp * @[simp] theorem to_bool_and (p q : Prop) [decidable p] [decidable q] : to_bool (p ∧ q) = p && q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_or (p q : Prop) [decidable p] [decidable q] : to_bool (p ∨ q) = p || q := by by_cases p; by_cases q; simp * @[simp] theorem to_bool_eq {p q : Prop} [decidable p] [decidable q] : to_bool p = to_bool q ↔ (p ↔ q) := ⟨λ h, (coe_to_bool p).symm.trans $ by simp [h], to_bool_congr⟩ lemma not_ff : ¬ ff := ff_ne_tt @[simp] theorem default_bool : default = ff := rfl theorem dichotomy (b : bool) : b = ff ∨ b = tt := by cases b; simp @[simp] theorem forall_bool {p : bool → Prop} : (∀ b, p b) ↔ p ff ∧ p tt := ⟨λ h, by simp [h], λ ⟨h₁, h₂⟩ b, by cases b; assumption⟩ @[simp] theorem exists_bool {p : bool → Prop} : (∃ b, p b) ↔ p ff ∨ p tt := ⟨λ ⟨b, h⟩, by cases b; [exact or.inl h, exact or.inr h], λ h, by cases h; exact ⟨_, h⟩⟩ /-- If `p b` is decidable for all `b : bool`, then `∀ b, p b` is decidable -/ instance decidable_forall_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∀ b, p b) := decidable_of_decidable_of_iff and.decidable forall_bool.symm /-- If `p b` is decidable for all `b : bool`, then `∃ b, p b` is decidable -/ instance decidable_exists_bool {p : bool → Prop} [∀ b, decidable (p b)] : decidable (∃ b, p b) := decidable_of_decidable_of_iff or.decidable exists_bool.symm @[simp] theorem cond_ff {α} (t e : α) : cond ff t e = e := rfl @[simp] theorem cond_tt {α} (t e : α) : cond tt t e = t := rfl theorem cond_eq_ite {α} (b : bool) (t e : α) : cond b t e = if b then t else e := by cases b; simp @[simp] theorem cond_to_bool {α} (p : Prop) [decidable p] (t e : α) : cond (to_bool p) t e = if p then t else e := by simp [cond_eq_ite] @[simp] theorem cond_bnot {α} (b : bool) (t e : α) : cond (!b) t e = cond b e t := by cases b; refl theorem bnot_ne_id : bnot ≠ id := λ h, ff_ne_tt $ congr_fun h tt theorem coe_bool_iff : ∀ {a b : bool}, (a ↔ b) ↔ a = b := dec_trivial theorem eq_tt_of_ne_ff : ∀ {a : bool}, a ≠ ff → a = tt := dec_trivial theorem eq_ff_of_ne_tt : ∀ {a : bool}, a ≠ tt → a = ff := dec_trivial theorem bor_comm : ∀ a b, a || b = b || a := dec_trivial @[simp] theorem bor_assoc : ∀ a b c, (a || b) || c = a || (b || c) := dec_trivial theorem bor_left_comm : ∀ a b c, a || (b || c) = b || (a || c) := dec_trivial theorem bor_inl {a b : bool} (H : a) : a || b := by simp [H] theorem bor_inr {a b : bool} (H : b) : a || b := by simp [H] theorem band_comm : ∀ a b, a && b = b && a := dec_trivial @[simp] theorem band_assoc : ∀ a b c, (a && b) && c = a && (b && c) := dec_trivial theorem band_left_comm : ∀ a b c, a && (b && c) = b && (a && c) := dec_trivial theorem band_elim_left : ∀ {a b : bool}, a && b → a := dec_trivial theorem band_intro : ∀ {a b : bool}, a → b → a && b := dec_trivial theorem band_elim_right : ∀ {a b : bool}, a && b → b := dec_trivial lemma band_bor_distrib_left (a b c : bool) : a && (b || c) = a && b || a && c := by cases a; simp lemma band_bor_distrib_right (a b c : bool) : (a || b) && c = a && c || b && c := by cases c; simp lemma bor_band_distrib_left (a b c : bool) : a || b && c = (a || b) && (a || c) := by cases a; simp lemma bor_band_distrib_right (a b c : bool) : a && b || c = (a || c) && (b || c) := by cases c; simp @[simp] theorem bnot_ff : !ff = tt := rfl @[simp] theorem bnot_tt : !tt = ff := rfl lemma eq_bnot_iff : ∀ {a b : bool}, a = !b ↔ a ≠ b := dec_trivial lemma bnot_eq_iff : ∀ {a b : bool}, !a = b ↔ a ≠ b := dec_trivial @[simp] lemma not_eq_bnot : ∀ {a b : bool}, ¬a = !b ↔ a = b := dec_trivial @[simp] lemma bnot_not_eq : ∀ {a b : bool}, ¬!a = b ↔ a = b := dec_trivial lemma ne_bnot {a b : bool} : a ≠ !b ↔ a = b := not_eq_bnot lemma bnot_ne {a b : bool} : !a ≠ b ↔ a = b := bnot_not_eq lemma bnot_ne_self : ∀ b : bool, !b ≠ b := dec_trivial lemma self_ne_bnot : ∀ b : bool, b ≠ !b := dec_trivial lemma eq_or_eq_bnot : ∀ a b, a = b ∨ a = !b := dec_trivial @[simp] theorem bnot_iff_not : ∀ {b : bool}, !b ↔ ¬b := dec_trivial theorem eq_tt_of_bnot_eq_ff : ∀ {a : bool}, !a = ff → a = tt := dec_trivial theorem eq_ff_of_bnot_eq_tt : ∀ {a : bool}, !a = tt → a = ff := dec_trivial @[simp] lemma band_bnot_self : ∀ x, x && !x = ff := dec_trivial @[simp] lemma bnot_band_self : ∀ x, !x && x = ff := dec_trivial @[simp] lemma bor_bnot_self : ∀ x, x || !x = tt := dec_trivial @[simp] lemma bnot_bor_self : ∀ x, !x || x = tt := dec_trivial theorem bxor_comm : ∀ a b, bxor a b = bxor b a := dec_trivial @[simp] theorem bxor_assoc : ∀ a b c, bxor (bxor a b) c = bxor a (bxor b c) := dec_trivial theorem bxor_left_comm : ∀ a b c, bxor a (bxor b c) = bxor b (bxor a c) := dec_trivial @[simp] theorem bxor_bnot_left : ∀ a, bxor (!a) a = tt := dec_trivial @[simp] theorem bxor_bnot_right : ∀ a, bxor a (!a) = tt := dec_trivial @[simp] theorem bxor_bnot_bnot : ∀ a b, bxor (!a) (!b) = bxor a b := dec_trivial @[simp] theorem bxor_ff_left : ∀ a, bxor ff a = a := dec_trivial @[simp] theorem bxor_ff_right : ∀ a, bxor a ff = a := dec_trivial lemma band_bxor_distrib_left (a b c : bool) : a && (bxor b c) = bxor (a && b) (a && c) := by cases a; simp lemma band_bxor_distrib_right (a b c : bool) : (bxor a b) && c = bxor (a && c) (b && c) := by cases c; simp lemma bxor_iff_ne : ∀ {x y : bool}, bxor x y = tt ↔ x ≠ y := dec_trivial /-! ### De Morgan's laws for booleans-/ @[simp] lemma bnot_band : ∀ (a b : bool), !(a && b) = !a || !b := dec_trivial @[simp] lemma bnot_bor : ∀ (a b : bool), !(a || b) = !a && !b := dec_trivial lemma bnot_inj : ∀ {a b : bool}, !a = !b → a = b := dec_trivial instance : linear_order bool := { le := λ a b, a = ff ∨ b = tt, le_refl := dec_trivial, le_trans := dec_trivial, le_antisymm := dec_trivial, le_total := dec_trivial, decidable_le := infer_instance, decidable_eq := infer_instance, max := bor, max_def := by { funext x y, revert x y, exact dec_trivial }, min := band, min_def := by { funext x y, revert x y, exact dec_trivial } } @[simp] lemma ff_le {x : bool} : ff ≤ x := or.intro_left _ rfl @[simp] lemma le_tt {x : bool} : x ≤ tt := or.intro_right _ rfl lemma lt_iff : ∀ {x y : bool}, x < y ↔ x = ff ∧ y = tt := dec_trivial @[simp] lemma ff_lt_tt : ff < tt := lt_iff.2 ⟨rfl, rfl⟩ lemma le_iff_imp : ∀ {x y : bool}, x ≤ y ↔ (x → y) := dec_trivial lemma band_le_left : ∀ x y : bool, x && y ≤ x := dec_trivial lemma band_le_right : ∀ x y : bool, x && y ≤ y := dec_trivial lemma le_band : ∀ {x y z : bool}, x ≤ y → x ≤ z → x ≤ y && z := dec_trivial lemma left_le_bor : ∀ x y : bool, x ≤ x || y := dec_trivial lemma right_le_bor : ∀ x y : bool, y ≤ x || y := dec_trivial lemma bor_le : ∀ {x y z}, x ≤ z → y ≤ z → x || y ≤ z := dec_trivial /-- convert a `bool` to a `ℕ`, `false -> 0`, `true -> 1` -/ def to_nat (b : bool) : ℕ := cond b 1 0 /-- convert a `ℕ` to a `bool`, `0 -> false`, everything else -> `true` -/ def of_nat (n : ℕ) : bool := to_bool (n ≠ 0) lemma of_nat_le_of_nat {n m : ℕ} (h : n ≤ m) : of_nat n ≤ of_nat m := begin simp [of_nat]; cases nat.decidable_eq n 0; cases nat.decidable_eq m 0; simp only [to_bool], { subst m, have h := le_antisymm h (nat.zero_le _), contradiction }, { left, refl } end lemma to_nat_le_to_nat {b₀ b₁ : bool} (h : b₀ ≤ b₁) : to_nat b₀ ≤ to_nat b₁ := by cases h; subst h; [cases b₁, cases b₀]; simp [to_nat,nat.zero_le] lemma of_nat_to_nat (b : bool) : of_nat (to_nat b) = b := by cases b; simp only [of_nat,to_nat]; exact dec_trivial @[simp] lemma injective_iff {α : Sort*} {f : bool → α} : function.injective f ↔ f ff ≠ f tt := ⟨λ Hinj Heq, ff_ne_tt (Hinj Heq), λ H x y hxy, by { cases x; cases y, exacts [rfl, (H hxy).elim, (H hxy.symm).elim, rfl] }⟩ /-- **Kaminski's Equation** -/ theorem apply_apply_apply (f : bool → bool) (x : bool) : f (f (f x)) = f x := by cases x; cases h₁ : f tt; cases h₂ : f ff; simp only [h₁, h₂] end bool
58d1d737a71950ada9df038b1d8384bdfd635040
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Util/Name.lean
a827eee1354a549f9ad688914e8ef47e41b50b78
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
583
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Daniel Selsam -/ import Lean namespace Lean.Name def mapStrings (f : String → String) : Name → Name | anonymous => anonymous | str p s .. => mkStr (mapStrings f p) (f s) | num p k .. => mkNum (mapStrings f p) k def toFilePath (n : Name) : System.FilePath := ⟨"/".intercalate (n.components.map Name.getString!)⟩ end Lean.Name def String.toName' (n : String) : Lean.Name := (Lean.Syntax.decodeNameLit ("`" ++ n)).get!
ecb2408fd63223edb6886f91a16bc38fe252430c
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/inst.lean
a249771a54358949ee2f3db68a7a7fea4aac8728
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
621
lean
set_option pp.notation false class inductive C (A : Type*) | mk : A → C definition val {A : Type*} (c : C A) : A := C.rec (λa, a) c constant magic (A : Type*) : A attribute [instance, priority std.priority.max] noncomputable definition C_magic (A : Type*) : C A := C.mk (magic A) attribute [instance] definition C_prop : C Prop := C.mk true attribute [instance] definition C_prod {A B : Type*} (Ha : C A) (Hb : C B) : C (prod A B) := C.mk (prod.mk (val Ha) (val Hb)) -- C_magic will be used because it has max priority noncomputable definition test : C (prod Prop Prop) := by tactic.apply_instance #reduce test
8a477fcedc73796c9966e4da70ce03f4c6fc30ef
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/tactic/interactive.lean
240add269dc915363c7fe0b945c6c9ecc80235d1
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
37,816
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.lint import tactic.dependencies open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- Similar to `constructor`, but does not reorder goals. -/ meta def fconstructor : tactic unit := concat_tags tactic.fconstructor add_tactic_doc { name := "fconstructor", category := doc_category.tactic, decl_names := [`tactic.interactive.fconstructor], tags := ["logic", "goal management"] } /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple `subst`. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) add_tactic_doc { name := "substs", category := doc_category.tactic, decl_names := [`tactic.interactive.substs], tags := ["rewriting"] } /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc add_tactic_doc { name := "unfold_coes", category := doc_category.tactic, decl_names := [`tactic.interactive.unfold_coes], tags := ["simplification"] } /-- Unfold `has_well_founded.r`, `sizeof` and other such definitions. -/ meta def unfold_wf := propagate_tags (well_founded_tactics.unfold_wf_rel; well_founded_tactics.unfold_sizeof) /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- `id { tac }` is the same as `tac`, but it is useful for creating a block scope without requiring the goal to be solved at the end like `{ tac }`. It can also be used to enclose a non-interactive tactic for patterns like `tac1; id {tac2}` where `tac2` is non-interactive. -/ @[inline] protected meta def id (tac : itactic) : tactic unit := tac /-- `work_on_goal n { tac }` creates a block scope for the `n`-goal (indexed from zero), and does not require that the goal be solved at the end (any remaining subgoals are inserted back into the list of goals). Typically usage might look like: ```` intros, simp, apply lemma_1, work_on_goal 2 { dsimp, simp }, refl ```` See also `id { tac }`, which is equivalent to `work_on_goal 0 { tac }`. -/ meta def work_on_goal : parse small_nat → itactic → tactic unit | n t := do goals ← get_goals, let earlier_goals := goals.take n, let later_goals := goals.drop (n+1), set_goals (goals.nth n).to_list, t, new_goals ← get_goals, set_goals (earlier_goals ++ new_goals ++ later_goals) /-- `swap n` will move the `n`th goal to the front. `swap` defaults to `swap 2`, and so interchanges the first and second goals. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end add_tactic_doc { name := "swap", category := doc_category.tactic, decl_names := [`tactic.interactive.swap], tags := ["goal management"] } /-- `rotate` moves the first goal to the back. `rotate n` will do this `n` times. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n add_tactic_doc { name := "rotate", category := doc_category.tactic, decl_names := [`tactic.interactive.rotate], tags := ["goal management"] } /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h add_tactic_doc { name := "clear_", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_], tags := ["context management"] } /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end add_tactic_doc { name := "replace", category := doc_category.tactic, decl_names := [`tactic.interactive.replace], tags := ["context management"] } /-- Make every proposition in the context decidable. -/ meta def classical := tactic.classical add_tactic_doc { name := "classical", category := doc_category.tactic, decl_names := [`tactic.interactive.classical], tags := ["classical logic", "type class"] } private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux @[nolint def_lemma] lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end add_tactic_doc { name := "generalize_hyp", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize_hyp], tags := ["context management"] } meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← infer_type v', if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs /-- go from (x₀ : t₀) (x₁ : t₀) (x₂ : t₀) to (x₀ x₁ x₂ : t₀) -/ meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.clean meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target >>= whnf, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (dsimp_target simp_lemmas.mk), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ```lean refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` `have_field`, used after `refine_struct _`, poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp' h : t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `match_hyp h : t` fails if the hypothesis `h` does not match the type `t` (which may be a pattern). We use this tactic for writing tests. -/ meta def match_hyp (n : parse ident) (p : parse $ tk ":" *> texpr) (m := reducible) : tactic (list expr) := do h ← get_local n >>= infer_type >>= instantiate_mvars, match_expr p h m /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h : t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p /-- Tests that there are `n` hypotheses in the current context. -/ meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" /-- Test that `t` is the tag of the main goal. -/ meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `guard_proof_term { t } e` applies tactic `t` and tests whether the resulting proof term unifies with `p`. -/ meta def guard_proof_term (t : itactic) (p : parse texpr) : itactic := do g :: _ ← get_goals, e ← to_expr p, t, g ← instantiate_mvars g, unify e g /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac /-- Get the field of the current goal. -/ meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ```lean refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ```lean refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc add_tactic_doc { name := "refine_struct", category := doc_category.tactic, decl_names := [`tactic.interactive.refine_struct, `tactic.interactive.apply_field, `tactic.interactive.have_field], tags := ["structures"], inherit_description_from := `tactic.interactive.refine_struct } /-- `apply_rules hs n` applies the list of lemmas `hs` and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is optional, equal to 50 by default. You can pass an `apply_cfg` option argument as `apply_rules hs n opt`. (A typical usage would be with `apply_rules hs n { md := reducible })`, which asks `apply_rules` to not unfold `semireducible` definitions (i.e. most) when checking if a lemma matches the goal.) `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. For instance: ```lean @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := -- any of the following lines solve the goal: add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] by apply_rules [mono_rules] by apply_rules mono_rules ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) (opt : apply_cfg := {}) : tactic unit := tactic.apply_rules hs n opt add_tactic_doc { name := "apply_rules", category := doc_category.tactic, decl_names := [`tactic.interactive.apply_rules], tags := ["lemma application"] } meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. - `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`; - `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`; - `h_generalize! Hx : e == x` reverts `Hx`; - when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) add_tactic_doc { name := "h_generalize", category := doc_category.tactic, decl_names := [`tactic.interactive.h_generalize], tags := ["context management"] } /-- Tests whether `t` is definitionally equal to `p`. The difference with `guard_expr_eq` is that this uses definitional equality instead of alpha-equivalence. -/ meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target' t` fails if the target of the main goal is not definitionally equal to `t`. We use this tactic for writing tests. The difference with `guard_target` is that this uses definitional equality instead of alpha-equivalence. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p add_tactic_doc { name := "guard_target'", category := doc_category.tactic, decl_names := [`tactic.interactive.guard_target'], tags := ["testing"] } /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" add_tactic_doc { name := "triv", category := doc_category.tactic, decl_names := [`tactic.interactive.triv], tags := ["finishing"] } /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. It will then try to close the new goal using `triv`, or try to simplify it by applying `exists_prop`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: ```lean example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ n > 0, n = n := begin use 1, -- goal is now 1 > 0 ∧ 1 = 1, whereas it would be ∃ (H : 1 > 0), 1 = 1 after existsi 1. exact ⟨zero_lt_one, rfl⟩, end example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] ``` -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := focus1 $ tactic.use l; try (triv <|> (do `(Exists %%p) ← target, to_expr ``(exists_prop.mpr) >>= tactic.apply >> skip)) add_tactic_doc { name := "use", category := doc_category.tactic, decl_names := [`tactic.interactive.use, `tactic.interactive.existsi], tags := ["logic"], inherit_description_from := `tactic.interactive.use } /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. ```lean example (n m : ℕ) (h₁ : n = m) (h₂ : ∃ a : ℕ, a = n ∧ a = m) : 2 * m = 2 * n := let ⟨a, ha⟩ := h₂ in begin clear_aux_decl, -- subst will fail without this line subst h₁ end example (x y : ℕ) (h₁ : ∃ n : ℕ, n * 1 = 2) (h₂ : 1 + 1 = 2 → x * 1 = y) : x = y := let ⟨n, hn⟩ := h₁ in begin clear_aux_decl, -- finish produces an error without this line finish end ``` -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl add_tactic_doc { name := "clear_aux_decl", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_aux_decl, `tactic.clear_aux_decl], tags := ["context management"], inherit_description_from := `tactic.interactive.clear_aux_decl } meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) add_tactic_doc { name := "change'", category := doc_category.tactic, decl_names := [`tactic.interactive.change', `tactic.interactive.change], tags := ["renaming"], inherit_description_from := `tactic.interactive.change' } private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. ```lean example (x : ℕ) (h : x = 3) : x + x + x = 9 := begin set y := x with ←h_xy, /- x : ℕ, y : ℕ := x, h_xy : x = y, h : y = 3 ⊢ y + y + y = 9 -/ end ``` -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do tp ← i_to_expr $ tp.get_or_else pexpr.mk_placeholder, pv ← to_expr ``(%%pv : %%tp), tp ← instantiate_mvars tp, definev a tp pv, when h_simp.is_none $ change' ``(%%pv) (some (expr.const a [])) $ interactive.loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, mk_app `eq (cond flip [pv, nv] [nv, pv]) >>= assert id, reflexivity | none := skip end add_tactic_doc { name := "set", category := doc_category.tactic, decl_names := [`tactic.interactive.set], tags := ["context management"] } /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do n ← xs.mmap (try_core ∘ get_local) >>= revert_lst ∘ list.filter_map id, ls ← local_context, ls.reverse.mmap' $ try ∘ tactic.clear, intron_no_renames n add_tactic_doc { name := "clear_except", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_except], tags := ["context management"] } meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def indent_bindents (l r : string) : option (list name) → expr → tactic format | none e := do e ← pp e, pformat!"{l}{format.nest l.length e}{r}" | (some ns) e := do e ← pp e, let ns := format_names ns, let margin := l.length + ns.to_string.length + " : ".length, pformat!"{l}{ns} : {format.nest margin e}{r}" private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := indent_bindents "(" ")" ns t | (ns, binder_info.implicit, t) := indent_bindents "{" "}" ns t | (ns, binder_info.strict_implicit, t) := indent_bindents "⦃" "⦄" ns t | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then indent_bindents "[" "]" none t else indent_bindents "[" "]" [n] t | (ns, binder_info.inst_implicit, t) := indent_bindents "[" "]" ns t | (ns, binder_info.aux_decl, t) := indent_bindents "(" ")" ns t private meta def partition_vars' (s : name_set) : list expr → list expr → list expr → tactic (list expr × list expr) | [] as bs := pure (as.reverse, bs.reverse) | (x :: xs) as bs := do t ← infer_type x, if t.has_local_in s then partition_vars' xs as (x :: bs) else partition_vars' xs (x :: as) bs private meta def partition_vars : tactic (list expr × list expr) := do ls ← local_context, partition_vars' (name_set.of_list $ ls.map expr.local_uniq_name) ls [] [] /-- Format the current goal as a stand-alone example. Useful for testing tactics or creating [minimal working examples](https://leanprover-community.github.io/mwe.html). * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end extract_goal my_lemma -- prints: -- lemma my_lemma (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- admit, -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) -- (h₁ : p ≤ q) : -- i ≤ k := -- begin -- admit, -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {p i j k : ℕ} -- (h₀ : i ≤ j) -- (h₁ : j ≤ k) -- (h₁ : k ≤ p) : -- i ≤ k := -- begin -- admit, -- end end example : true := begin let n := 0, have m : ℕ, admit, have k : fin n, admit, have : n + m + k.1 = 0, extract_goal, -- prints: -- example (m : ℕ) : let n : ℕ := 0 in ∀ (k : fin n), n + m + k.val = 0 := -- begin -- intros n k, -- admit, -- end end ``` -/ meta def extract_goal (print_use : parse $ tt <$ tk "!" <|> pure ff) (n : parse ident?) (vs : parse with_ident_list) : tactic unit := do tgt ← target, solve_aux tgt $ do { ((cxt₀,cxt₁,ls,tgt),_) ← solve_aux tgt $ do { when (¬ vs.empty) (clear_except vs), ls ← local_context, ls ← ls.mfilter $ succeeds ∘ is_local_def, n ← revert_lst ls, (c₀,c₁) ← partition_vars, tgt ← target, ls ← intron' n, pure (c₀,c₁,ls,tgt) }, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt₀ ← compact_decl cxt₀ >>= list.mmap format_binders, cxt₁ ← compact_decl cxt₁ >>= list.mmap format_binders, stmt ← pformat!"{tgt} :=", let fmt := format.group $ format.nest 2 $ title ++ cxt₀.foldl (λ acc x, acc ++ format.group (format.line ++ x)) "" ++ format.join (list.map (λ x, format.line ++ x) cxt₁) ++ " :" ++ format.line ++ stmt, trace $ fmt.to_string $ options.mk.set_nat `pp.width 80, let var_names := format.intercalate " " $ ls.map (to_fmt ∘ local_pp_name), let call_intron := if ls.empty then to_fmt "" else format!"\n intros {var_names},", trace!"begin{call_intron}\n admit,\nend\n" }, skip add_tactic_doc { name := "extract_goal", category := doc_category.tactic, decl_names := [`tactic.interactive.extract_goal], tags := ["goal management", "proof extraction", "debugging"] } /-- `inhabit α` tries to derive a `nonempty α` instance and then upgrades this to an `inhabited α` instance. If the target is a `Prop`, this is done constructively; otherwise, it uses `classical.choice`. ```lean example (α) [nonempty α] : ∃ a : α, true := begin inhabit α, existsi default α, trivial end ``` -/ meta def inhabit (t : parse parser.pexpr) (inst_name : parse ident?) : tactic unit := do ty ← i_to_expr t, nm ← returnopt inst_name <|> get_unused_name `inst, tgt ← target, tgt_is_prop ← is_prop tgt, if tgt_is_prop then do decorate_error "could not infer nonempty instance:" $ mk_mapp ``nonempty.elim_to_inhabited [ty, none, tgt] >>= tactic.apply, introI nm else do decorate_error "could not infer nonempty instance:" $ mk_mapp ``classical.inhabited_of_nonempty' [ty, none] >>= note nm none, resetI add_tactic_doc { name := "inhabit", category := doc_category.tactic, decl_names := [`tactic.interactive.inhabit], tags := ["context management", "type class"] } /-- `revert_deps n₁ n₂ ...` reverts all the hypotheses that depend on one of `n₁, n₂, ...` It does not revert `n₁, n₂, ...` themselves (unless they depend on another `nᵢ`). -/ meta def revert_deps (ns : parse ident*) : tactic unit := propagate_tags $ ns.mmap get_local >>= revert_reverse_dependencies_of_hyps >> skip add_tactic_doc { name := "revert_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_deps], tags := ["context management", "goal management"] } /-- `revert_after n` reverts all the hypotheses after `n`. -/ meta def revert_after (n : parse ident) : tactic unit := propagate_tags $ get_local n >>= tactic.revert_after >> skip add_tactic_doc { name := "revert_after", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_after], tags := ["context management", "goal management"] } /-- Reverts all local constants on which the target depends (recursively). -/ meta def revert_target_deps : tactic unit := propagate_tags $ tactic.revert_target_deps >> skip add_tactic_doc { name := "revert_target_deps", category := doc_category.tactic, decl_names := [`tactic.interactive.revert_target_deps], tags := ["context management", "goal management"] } /-- `clear_value n₁ n₂ ...` clears the bodies of the local definitions `n₁, n₂ ...`, changing them into regular hypotheses. A hypothesis `n : α := t` is changed to `n : α`. -/ meta def clear_value (ns : parse ident*) : tactic unit := propagate_tags $ ns.reverse.mmap get_local >>= tactic.clear_value add_tactic_doc { name := "clear_value", category := doc_category.tactic, decl_names := [`tactic.interactive.clear_value], tags := ["context management"] } /-- `generalize' : e = x` replaces all occurrences of `e` in the target with a new hypothesis `x` of the same type. `generalize' h : e = x` in addition registers the hypothesis `h : e = x`. `generalize'` is similar to `generalize`. The difference is that `generalize' : e = x` also succeeds when `e` does not occur in the goal. It is similar to `set`, but the resulting hypothesis `x` is not a local definition. -/ meta def generalize' (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) : tactic unit := propagate_tags $ do let (p, x) := p, e ← i_to_expr p, some h ← pure h | tactic.generalize' e x >> skip, -- `h` is given, the regular implementation of `generalize` works. tgt ← target, tgt' ← do { ⟨tgt', _⟩ ← solve_aux tgt (tactic.generalize e x >> target), to_expr ``(Π x, %%e = x → %%(tgt'.binding_body.lift_vars 0 1)) } <|> to_expr ``(Π x, %%e = x → %%tgt), t ← assert h tgt', swap, exact ``(%%t %%e rfl), intro x, intro h add_tactic_doc { name := "generalize'", category := doc_category.tactic, decl_names := [`tactic.interactive.generalize'], tags := ["context management"] } end interactive end tactic
24397fc0904082fd57ed58dcf696089db2d5bdee
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/measure_theory/outer_measure.lean
9a8f9b2a53518ecd8571d73eb251760a1ecfafaf
[ "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
19,560
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 Outer measures -- overapproximations of measures -/ import algebra.big_operators algebra.module topology.instances.ennreal analysis.specific_limits measure_theory.measurable_space noncomputable theory open set lattice finset function filter encodable open_locale classical namespace measure_theory structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i))) namespace outer_measure instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0) {β} [encodable β] (s : β → set α) : (∑ b, m (s b)) = ∑ i, m (⋃ b ∈ decode2 β i, s b) := begin have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some, { intros n h, cases decode2 β n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 β n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := begin convert m.Union (λ b, cond b s₁ s₂), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ @[ext] lemma ext : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑i, m₁ (s i)) + (∑i, m₂ (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, zero_add _ } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≤ (∑ (i : ℕ), m.val (f i)) : m.val.Union_nat _ ... ≤ (∑i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩ private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩ private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, Sup_le, le_Sup := assume s m, le_Sup, Inf := Inf, Inf_le := assume s m, Inf_le, le_Inf := assume s m, le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, Inf_le $ by simp, inf_le_right := assume a b, Inf_le $ by simp, le_inf := assume a b c ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ λ i, le_supr (λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum def map {β} (f : α → β) (m : outer_measure α) : outer_measure β := { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β, map} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑ i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑ i, f i s := rfl instance : has_scalar ennreal (outer_measure α) := ⟨λ a m, { measure_of := λs, a * m s, empty := by simp, mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := λ s, by rw ennreal.mul_tsum; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) : (a • m) s = a * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _, add_smul := λ a b m, ext $ λ s, add_mul _ _ _, mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _, one_smul := λ m, ext $ λ s, one_mul _, zero_smul := λ m, ext $ λ s, zero_mul _, smul_zero := λ a, ext $ λ s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set α} (h : s ≠ ∅) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq] end private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Caratheodory measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma is_caratheodory {s : set α} : caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set α} : caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀) in (is_caratheodory_le o).2 $ λ t, le_infi $ λ f, le_infi $ λ hf, begin refine le_trans (add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, by by_cases ht : t = ∅; simp [ht, top_apply] theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨆(h : s ≠ ∅), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s @[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 := by simp [Inf_gen] lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t ≠ ∅) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin by_cases ht : t = ∅, { simp [ht], refine (bot_unique $ infi_le_of_le μ $ _).symm, refine infi_le_of_le h (le_refl ⊥) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (lattice.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _); by_cases ht : t = ∅; simp [ht, Inf_gen_nonempty1], { assume μ hμ, exact (show Inf m ≤ μ, from lattice.Inf_le hμ) t }, { exact infi_le_of_le μ (infi_le _ hμ) } end end Inf_gen end outer_measure end measure_theory
517568673de712ff84a3621e2a247bb378a1af33
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/dedekind_domain/factorization.lean
3527aeb7fcd0b011569af2464aeb3ef8054283bb
[ "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
8,264
lean
/- Copyright (c) 2022 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import ring_theory.dedekind_domain.ideal /-! # Factorization of ideals of Dedekind domains Every nonzero ideal `I` of a Dedekind domain `R` can be factored as a product `∏_v v^{n_v}` over the maximal ideals of `R`, where the exponents `n_v` are natural numbers. TODO: Extend the results in this file to fractional ideals of `R`. ## Main results - `ideal.finite_factors` : Only finitely many maximal ideals of `R` divide a given nonzero ideal. - `ideal.finprod_height_one_spectrum_factorization` : The ideal `I` equals the finprod `∏_v v^(val_v(I))`,where `val_v(I)` denotes the multiplicity of `v` in the factorization of `I` and `v` runs over the maximal ideals of `R`. ## Tags dedekind domain, ideal, factorization -/ noncomputable theory open_locale big_operators classical non_zero_divisors open set function unique_factorization_monoid is_dedekind_domain is_dedekind_domain.height_one_spectrum /-! ### Factorization of ideals of Dedekind domains -/ variables {R : Type*} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type*} [field K] [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R) /-- Given a maximal ideal `v` and an ideal `I` of `R`, `max_pow_dividing` returns the maximal power of `v` dividing `I`. -/ def is_dedekind_domain.height_one_spectrum.max_pow_dividing (I : ideal R) : ideal R := v.as_ideal^(associates.mk v.as_ideal).count (associates.mk I).factors /-- Only finitely many maximal ideals of `R` divide a given nonzero ideal. -/ lemma ideal.finite_factors {I : ideal R} (hI : I ≠ 0) : {v : height_one_spectrum R | v.as_ideal ∣ I}.finite := begin rw [← set.finite_coe_iff, set.coe_set_of], haveI h_fin := fintype_subtype_dvd I hI, refine finite.of_injective (λ v, (⟨(v : height_one_spectrum R).as_ideal, v.2⟩ : {x // x ∣ I})) _, intros v w hvw, simp only at hvw, exact subtype.coe_injective ((height_one_spectrum.ext_iff ↑v ↑w).mpr hvw) end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that the multiplicity of `v` in the factorization of `I`, denoted `val_v(I)`, is nonzero. -/ lemma associates.finite_factors {I : ideal R} (hI : I ≠ 0) : ∀ᶠ (v : height_one_spectrum R) in filter.cofinite, ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = 0 := begin have h_supp : {v : height_one_spectrum R | ¬((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = 0} = {v : height_one_spectrum R | v.as_ideal ∣ I}, { ext v, simp_rw int.coe_nat_eq_zero, exact associates.count_ne_zero_iff_dvd hI v.irreducible, }, rw [filter.eventually_cofinite, h_supp], exact ideal.finite_factors hI, end namespace ideal /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^(val_v(I))` is not the unit ideal. -/ lemma finite_mul_support {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), v.max_pow_dividing I)).finite := begin have h_subset : {v : height_one_spectrum R | v.max_pow_dividing I ≠ 1} ⊆ {v : height_one_spectrum R | ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) ≠ 0}, { intros v hv h_zero, have hv' : v.max_pow_dividing I = 1, { rw [is_dedekind_domain.height_one_spectrum.max_pow_dividing, int.coe_nat_eq_zero.mp h_zero, pow_zero _] }, exact hv hv', }, exact finite.subset (filter.eventually_cofinite.mp (associates.finite_factors hI)) h_subset, end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^(val_v(I))`, regarded as a fractional ideal, is not `(1)`. -/ lemma finite_mul_support_coe {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ))).finite := begin rw mul_support, simp_rw [ne.def, zpow_coe_nat, ← fractional_ideal.coe_ideal_pow, fractional_ideal.coe_ideal_eq_one], exact finite_mul_support hI, end /-- For every nonzero ideal `I` of `v`, there are finitely many maximal ideals `v` such that `v^-(val_v(I))` is not the unit ideal. -/ lemma finite_mul_support_inv {I : ideal R} (hI : I ≠ 0) : (mul_support (λ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ -((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ))).finite := begin rw mul_support, simp_rw [zpow_neg, ne.def, inv_eq_one], exact finite_mul_support_coe hI, end /-- For every nonzero ideal `I` of `v`, `v^(val_v(I) + 1)` does not divide `∏_v v^(val_v(I))`. -/ lemma finprod_not_dvd (I : ideal R) (hI : I ≠ 0) : ¬ (v.as_ideal) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors + 1) ∣ (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I) := begin have hf := finite_mul_support hI, have h_ne_zero : v.max_pow_dividing I ≠ 0 := pow_ne_zero _ v.ne_bot, rw [← mul_finprod_cond_ne v hf, pow_add, pow_one, finprod_cond_ne _ _ hf], intro h_contr, have hv_prime : prime v.as_ideal := ideal.prime_of_is_prime v.ne_bot v.is_prime, obtain ⟨w, hw, hvw'⟩ := prime.exists_mem_finset_dvd hv_prime ((mul_dvd_mul_iff_left h_ne_zero).mp h_contr), have hw_prime : prime w.as_ideal := ideal.prime_of_is_prime w.ne_bot w.is_prime, have hvw := prime.dvd_of_dvd_pow hv_prime hvw', rw [prime.dvd_prime_iff_associated hv_prime hw_prime, associated_iff_eq] at hvw, exact (finset.mem_erase.mp hw).1 (height_one_spectrum.ext w v (eq.symm hvw)), end end ideal lemma associates.finprod_ne_zero (I : ideal R) : associates.mk (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I) ≠ 0 := begin rw [associates.mk_ne_zero, finprod_def], split_ifs, { rw finset.prod_ne_zero_iff, intros v hv, apply pow_ne_zero _ v.ne_bot, }, { exact one_ne_zero, } end namespace ideal /-- The multiplicity of `v` in `∏_v v^(val_v(I))` equals `val_v(I)`. -/ lemma finprod_count (I : ideal R) (hI : I ≠ 0) : (associates.mk v.as_ideal).count (associates.mk (∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I)).factors = (associates.mk v.as_ideal).count (associates.mk I).factors := begin have h_ne_zero := associates.finprod_ne_zero I, have hv : irreducible (associates.mk v.as_ideal) := v.associates_irreducible, have h_dvd := finprod_mem_dvd v (ideal.finite_mul_support hI), have h_not_dvd := ideal.finprod_not_dvd v I hI, simp only [is_dedekind_domain.height_one_spectrum.max_pow_dividing] at h_dvd h_ne_zero h_not_dvd, rw [← associates.mk_dvd_mk, associates.dvd_eq_le, associates.mk_pow, associates.prime_pow_dvd_iff_le h_ne_zero hv] at h_dvd h_not_dvd, rw not_le at h_not_dvd, apply nat.eq_of_le_of_lt_succ h_dvd h_not_dvd, end /-- The ideal `I` equals the finprod `∏_v v^(val_v(I))`. -/ lemma finprod_height_one_spectrum_factorization (I : ideal R) (hI : I ≠ 0) : ∏ᶠ (v : height_one_spectrum R), v.max_pow_dividing I = I := begin rw [← associated_iff_eq, ← associates.mk_eq_mk_iff_associated], apply associates.eq_of_eq_counts, { apply associates.finprod_ne_zero I }, { apply associates.mk_ne_zero.mpr hI }, intros v hv, obtain ⟨J, hJv⟩ := associates.exists_rep v, rw [← hJv, associates.irreducible_mk] at hv, rw ← hJv, apply ideal.finprod_count ⟨J, ideal.is_prime_of_prime (irreducible_iff_prime.mp hv), irreducible.ne_zero hv⟩ I hI, end /-- The ideal `I` equals the finprod `∏_v v^(val_v(I))`, when both sides are regarded as fractional ideals of `R`. -/ lemma finprod_height_one_spectrum_factorization_coe (I : ideal R) (hI : I ≠ 0) : ∏ᶠ (v : height_one_spectrum R), (v.as_ideal : fractional_ideal R⁰ K) ^ ((associates.mk v.as_ideal).count (associates.mk I).factors : ℤ) = I := begin conv_rhs { rw ← ideal.finprod_height_one_spectrum_factorization I hI }, rw fractional_ideal.coe_ideal_finprod R⁰ K (le_refl _), simp_rw [is_dedekind_domain.height_one_spectrum.max_pow_dividing, fractional_ideal.coe_ideal_pow, zpow_coe_nat], end end ideal
80b0ced589d93f430976749ae3ca54009ee17705
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/linear_algebra/special_linear_group.lean
0006774c732d5a2860417280c703b4ec1540a25e
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,015
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.matrix.nonsingular_inverse import linear_algebra.matrix.to_lin /-! # The Special Linear group $SL(n, R)$ This file defines the elements of the Special Linear group `special_linear_group n R`, consisting of all square `R`-matrices with determinant `1` on the fintype `n` by `n`. In addition, we define the group structure on `special_linear_group n R` and the embedding into the general linear group `general_linear_group R (n → R)`. ## Main definitions * `matrix.special_linear_group` is the type of matrices with determinant 1 * `matrix.special_linear_group.group` gives the group structure (under multiplication) * `matrix.special_linear_group.to_GL` is the embedding `SLₙ(R) → GLₙ(R)` ## Notation For `m : ℕ`, we introduce the notation `SL(m,R)` for the special linear group on the fintype `n = fin m`, in the locale `matrix_groups`. ## Implementation notes The inverse operation in the `special_linear_group` is defined to be the adjugate matrix, so that `special_linear_group n R` has a group structure for all `comm_ring R`. We define the elements of `special_linear_group` to be matrices, since we need to compute their determinant. This is in contrast with `general_linear_group R M`, which consists of invertible `R`-linear maps on `M`. We provide `matrix.special_linear_group.has_coe_to_fun` for convenience, but do not state any lemmas about it, and use `matrix.special_linear_group.coe_fn_eq_coe` to eliminate it `⇑` in favor of a regular `↑` coercion. ## References * https://en.wikipedia.org/wiki/Special_linear_group ## Tags matrix group, group, matrix inverse -/ namespace matrix universes u v open_locale matrix open linear_map section variables (n : Type u) [decidable_eq n] [fintype n] (R : Type v) [comm_ring R] /-- `special_linear_group n R` is the group of `n` by `n` `R`-matrices with determinant equal to 1. -/ def special_linear_group := { A : matrix n n R // A.det = 1 } end localized "notation `SL(` n `,` R `)`:= special_linear_group (fin n) R" in matrix_groups namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] instance has_coe_to_matrix : has_coe (special_linear_group n R) (matrix n n R) := ⟨λ A, A.val⟩ /- In this file, Lean often has a hard time working out the values of `n` and `R` for an expression like `det ↑A`. Rather than writing `(A : matrix n n R)` everywhere in this file which is annoyingly verbose, or `A.val` which is not the simp-normal form for subtypes, we create a local notation `↑ₘA`. This notation references the local `n` and `R` variables, so is not valid as a global notation. -/ local prefix `↑ₘ`:1024 := @coe _ (matrix n n R) _ lemma ext_iff (A B : special_linear_group n R) : A = B ↔ (∀ i j, ↑ₘA i j = ↑ₘB i j) := subtype.ext_iff.trans matrix.ext_iff.symm @[ext] lemma ext (A B : special_linear_group n R) : (∀ i j, ↑ₘA i j = ↑ₘB i j) → A = B := (special_linear_group.ext_iff A B).mpr instance has_inv : has_inv (special_linear_group n R) := ⟨λ A, ⟨adjugate A, det_adjugate_eq_one A.2⟩⟩ instance has_mul : has_mul (special_linear_group n R) := ⟨λ A B, ⟨A.1 ⬝ B.1, by erw [det_mul, A.2, B.2, one_mul]⟩⟩ instance has_one : has_one (special_linear_group n R) := ⟨⟨1, det_one⟩⟩ instance : inhabited (special_linear_group n R) := ⟨1⟩ section coe_lemmas variables (A B : special_linear_group n R) @[simp] lemma coe_inv : ↑ₘ(A⁻¹) = adjugate A := rfl @[simp] lemma coe_mul : ↑ₘ(A * B) = ↑ₘA ⬝ ↑ₘB := rfl @[simp] lemma coe_one : ↑ₘ(1 : special_linear_group n R) = (1 : matrix n n R) := rfl @[simp] lemma det_coe : det ↑ₘA = 1 := A.2 lemma det_ne_zero [nontrivial R] (g : special_linear_group n R) : det ↑ₘg ≠ 0 := by { rw g.det_coe, norm_num } lemma row_ne_zero [nontrivial R] (g : special_linear_group n R) (i : n): ↑ₘg i ≠ 0 := λ h, g.det_ne_zero $ det_eq_zero_of_row_eq_zero i $ by simp [h] end coe_lemmas instance : monoid (special_linear_group n R) := function.injective.monoid coe subtype.coe_injective coe_one coe_mul instance : group (special_linear_group n R) := { mul_left_inv := λ A, by { ext1, simp [adjugate_mul] }, ..special_linear_group.monoid, ..special_linear_group.has_inv } /-- A version of `matrix.to_lin' A` that produces linear equivalences. -/ def to_lin' : special_linear_group n R →* (n → R) ≃ₗ[R] (n → R) := { to_fun := λ A, linear_equiv.of_linear (matrix.to_lin' ↑ₘA) (matrix.to_lin' ↑ₘ(A⁻¹)) (by rw [←to_lin'_mul, ←coe_mul, mul_right_inv, coe_one, to_lin'_one]) (by rw [←to_lin'_mul, ←coe_mul, mul_left_inv, coe_one, to_lin'_one]), map_one' := linear_equiv.to_linear_map_injective matrix.to_lin'_one, map_mul' := λ A B, linear_equiv.to_linear_map_injective $ matrix.to_lin'_mul A B } lemma to_lin'_apply (A : special_linear_group n R) (v : n → R) : special_linear_group.to_lin' A v = matrix.to_lin' ↑ₘA v := rfl lemma to_lin'_to_linear_map (A : special_linear_group n R) : ↑(special_linear_group.to_lin' A) = matrix.to_lin' ↑ₘA := rfl lemma to_lin'_symm_apply (A : special_linear_group n R) (v : n → R) : A.to_lin'.symm v = matrix.to_lin' ↑ₘ(A⁻¹) v := rfl lemma to_lin'_symm_to_linear_map (A : special_linear_group n R) : ↑(A.to_lin'.symm) = matrix.to_lin' ↑ₘ(A⁻¹) := rfl lemma to_lin'_injective : function.injective ⇑(to_lin' : special_linear_group n R →* (n → R) ≃ₗ[R] (n → R)) := λ A B h, subtype.coe_injective $ matrix.to_lin'.injective $ linear_equiv.to_linear_map_injective.eq_iff.mpr h /-- `to_GL` is the map from the special linear group to the general linear group -/ def to_GL : special_linear_group n R →* general_linear_group R (n → R) := (general_linear_group.general_linear_equiv _ _).symm.to_monoid_hom.comp to_lin' lemma coe_to_GL (A : special_linear_group n R) : ↑A.to_GL = A.to_lin'.to_linear_map := rfl section has_neg variables [fact (even (fintype.card n))] /-- Formal operation of negation on special linear group on even cardinality `n` given by negating each element. -/ instance : has_neg (special_linear_group n R) := ⟨λ g, ⟨- g, by simpa [nat.neg_one_pow_of_even (fact.out (even (fintype.card n))), g.det_coe] using det_smul ↑ₘg (-1)⟩⟩ @[simp] lemma coe_neg (g : special_linear_group n R) : ↑(- g) = - (↑g : matrix n n R) := rfl end has_neg -- this section should be last to ensure we do not use it in lemmas section coe_fn_instance /-- This instance is here for convenience, but is not the simp-normal form. -/ instance : has_coe_to_fun (special_linear_group n R) (λ _, n → n → R) := { coe := λ A, A.val } @[simp] lemma coe_fn_eq_coe (s : special_linear_group n R) : ⇑s = ↑ₘs := rfl end coe_fn_instance end special_linear_group end matrix
d0aaa36b9f9b86269e851434755f3a2dcd11c3fe
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/computability/halting.lean
13d3ee4e131b6d6640f5d0e7b11a48d65c8e4361
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,700
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import computability.partrec_code /-! # Computability theory and the halting problem A universal partial recursive function, Rice's theorem, and the halting problem. ## References * [Mario Carneiro, *Formalizing computability theory via partial recursive functions*][carneiro2019] -/ open encodable denumerable namespace nat.partrec open computable roption theorem merge' {f g} (hf : nat.partrec f) (hg : nat.partrec g) : ∃ h, nat.partrec h ∧ ∀ a, (∀ x ∈ h a, x ∈ f a ∨ x ∈ g a) ∧ ((h a).dom ↔ (f a).dom ∨ (g a).dom) := begin rcases code.exists_code.1 hf with ⟨cf, rfl⟩, rcases code.exists_code.1 hg with ⟨cg, rfl⟩, have : nat.partrec (λ n, (nat.rfind_opt (λ k, cf.evaln k n <|> cg.evaln k n))) := partrec.nat_iff.1 (partrec.rfind_opt $ primrec.option_orelse.to_comp.comp (code.evaln_prim.to_comp.comp $ (snd.pair (const cf)).pair fst) (code.evaln_prim.to_comp.comp $ (snd.pair (const cg)).pair fst)), refine ⟨_, this, λ n, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, rw nat.rfind_opt_dom, simp [dom_iff_mem, code.evaln_complete] at h, rcases h with ⟨x, k, e⟩ | ⟨x, k, e⟩, { refine ⟨k, x, _⟩, simp [e] }, { refine ⟨k, _⟩, cases cf.evaln k n with y, { exact ⟨x, by simp [e]⟩ }, { exact ⟨y, by simp⟩ } } }, { intros x h, rcases nat.rfind_opt_spec h with ⟨k, e⟩, revert e, simp; cases e' : cf.evaln k n with y; simp; intro, { exact or.inr (code.evaln_sound e) }, { subst y, exact or.inl (code.evaln_sound e') } } end end nat.partrec namespace partrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] open computable roption nat.partrec (code) nat.partrec.code theorem merge' {f g : α →. σ} (hf : partrec f) (hg : partrec g) : ∃ k : α →. σ, partrec k ∧ ∀ a, (∀ x ∈ k a, x ∈ f a ∨ x ∈ g a) ∧ ((k a).dom ↔ (f a).dom ∨ (g a).dom) := let ⟨k, hk, H⟩ := nat.partrec.merge' (bind_decode2_iff.1 hf) (bind_decode2_iff.1 hg) in begin let k' := λ a, (k (encode a)).bind (λ n, decode σ n), refine ⟨k', ((nat_iff.2 hk).comp computable.encode).bind (computable.decode.of_option.comp snd).to₂, λ a, _⟩, suffices, refine ⟨this, ⟨λ h, (this _ ⟨h, rfl⟩).imp Exists.fst Exists.fst, _⟩⟩, { intro h, simp [k'], have hk : (k (encode a)).dom := (H _).2.2 (by simpa [encodek2] using h), existsi hk, cases (H _).1 _ ⟨hk, rfl⟩ with h h; { simp at h, rcases h with ⟨a', ha', y, hy, e⟩, simp [e.symm, encodek] } }, { intros x h', simp [k'] at h', rcases h' with ⟨n, hn, hx⟩, have := (H _).1 _ hn, simp [mem_decode2, encode_injective.eq_iff] at this, cases this with h h; { rcases h with ⟨a', ha, rfl⟩, simp [encodek] at hx, subst a', simp [ha] } }, end theorem merge {f g : α →. σ} (hf : partrec f) (hg : partrec g) (H : ∀ a (x ∈ f a) (y ∈ g a), x = y) : ∃ k : α →. σ, partrec k ∧ ∀ a x, x ∈ k a ↔ x ∈ f a ∨ x ∈ g a := let ⟨k, hk, K⟩ := merge' hf hg in ⟨k, hk, λ a x, ⟨(K _).1 _, λ h, begin have : (k a).dom := (K _).2.2 (h.imp Exists.fst Exists.fst), refine ⟨this, _⟩, cases h with h h; cases (K _).1 _ ⟨this, rfl⟩ with h' h', { exact mem_unique h' h }, { exact (H _ _ h _ h').symm }, { exact H _ _ h' _ h }, { exact mem_unique h' h } end⟩⟩ theorem cond {c : α → bool} {f : α →. σ} {g : α →. σ} (hc : computable c) (hf : partrec f) (hg : partrec g) : partrec (λ a, cond (c a) (f a) (g a)) := let ⟨cf, ef⟩ := exists_code.1 hf, ⟨cg, eg⟩ := exists_code.1 hg in ((eval_part.comp (computable.cond hc (const cf) (const cg)) computable.id).bind ((@computable.decode σ _).comp snd).of_option.to₂).of_eq $ λ a, by cases c a; simp [ef, eg, encodek] theorem sum_cases {f : α → β ⊕ γ} {g : α → β →. σ} {h : α → γ →. σ} (hf : computable f) (hg : partrec₂ g) (hh : partrec₂ h) : @partrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (sum_cases hf (const tt).to₂ (const ff).to₂) (sum_cases_left hf (option_some_iff.2 hg).to₂ (const option.none).to₂) (sum_cases_right hf (const option.none).to₂ (option_some_iff.2 hh).to₂)) .of_eq $ λ a, by cases f a; simp end partrec /-- A computable predicate is one whose indicator function is computable. -/ def computable_pred {α} [primcodable α] (p : α → Prop) := ∃ [D : decidable_pred p], by exactI computable (λ a, to_bool (p a)) /-- A recursively enumerable predicate is one which is the domain of a computable partial function. -/ def re_pred {α} [primcodable α] (p : α → Prop) := partrec (λ a, roption.assert (p a) (λ _, roption.some ())) theorem computable_pred.of_eq {α} [primcodable α] {p q : α → Prop} (hp : computable_pred p) (H : ∀ a, p a ↔ q a) : computable_pred q := (funext (λ a, propext (H a)) : p = q) ▸ hp namespace computable_pred variables {α : Type*} {σ : Type*} variables [primcodable α] [primcodable σ] open nat.partrec (code) nat.partrec.code computable theorem computable_iff {p : α → Prop} : computable_pred p ↔ ∃ f : α → bool, computable f ∧ p = λ a, f a := ⟨λ ⟨D, h⟩, by exactI ⟨_, h, funext $ λ a, propext (to_bool_iff _).symm⟩, by rintro ⟨f, h, rfl⟩; exact ⟨by apply_instance, by simpa using h⟩⟩ protected theorem not {p : α → Prop} (hp : computable_pred p) : computable_pred (λ a, ¬ p a) := by rcases computable_iff.1 hp with ⟨f, hf, rfl⟩; exact ⟨by apply_instance, (cond hf (const ff) (const tt)).of_eq (λ n, by {dsimp, cases f n; refl})⟩ theorem to_re {p : α → Prop} (hp : computable_pred p) : re_pred p := begin rcases computable_iff.1 hp with ⟨f, hf, rfl⟩, unfold re_pred, refine (partrec.cond hf (partrec.const' (roption.some ())) partrec.none).of_eq (λ n, roption.ext $ λ a, _), cases a, cases f n; simp end theorem rice (C : set (ℕ →. ℕ)) (h : computable_pred (λ c, eval c ∈ C)) {f g} (hf : nat.partrec f) (hg : nat.partrec g) (fC : f ∈ C) : g ∈ C := begin cases h with _ h, resetI, rcases fixed_point₂ (partrec.cond (h.comp fst) ((partrec.nat_iff.2 hg).comp snd).to₂ ((partrec.nat_iff.2 hf).comp snd).to₂).to₂ with ⟨c, e⟩, simp at e, by_cases eval c ∈ C, { simp [h] at e, rwa ← e }, { simp [h] at e, rw e at h, contradiction } end theorem rice₂ (C : set code) (H : ∀ cf cg, eval cf = eval cg → (cf ∈ C ↔ cg ∈ C)) : computable_pred (λ c, c ∈ C) ↔ C = ∅ ∨ C = set.univ := by haveI := classical.dec; exact have hC : ∀ f, f ∈ C ↔ eval f ∈ eval '' C, from λ f, ⟨set.mem_image_of_mem _, λ ⟨g, hg, e⟩, (H _ _ e).1 hg⟩, ⟨λ h, or_iff_not_imp_left.2 $ λ C0, set.eq_univ_of_forall $ λ cg, let ⟨cf, fC⟩ := set.ne_empty_iff_nonempty.1 C0 in (hC _).2 $ rice (eval '' C) (h.of_eq hC) (partrec.nat_iff.1 $ eval_part.comp (const cf) computable.id) (partrec.nat_iff.1 $ eval_part.comp (const cg) computable.id) ((hC _).1 fC), λ h, by rcases h with rfl | rfl; simp [computable_pred]; exact ⟨by apply_instance, computable.const _⟩⟩ theorem halting_problem (n) : ¬ computable_pred (λ c, (eval c n).dom) | h := rice {f | (f n).dom} h nat.partrec.zero nat.partrec.none trivial -- Post's theorem on the equivalence of r.e., co-r.e. sets and -- computable sets. The assumption that p is decidable is required -- unless we assume Markov's principle or LEM. @[nolint decidable_classical] theorem computable_iff_re_compl_re {p : α → Prop} [decidable_pred p] : computable_pred p ↔ re_pred p ∧ re_pred (λ a, ¬ p a) := ⟨λ h, ⟨h.to_re, h.not.to_re⟩, λ ⟨h₁, h₂⟩, ⟨‹_›, begin rcases partrec.merge (h₁.map (computable.const tt).to₂) (h₂.map (computable.const ff).to₂) _ with ⟨k, pk, hk⟩, { refine partrec.of_eq pk (λ n, roption.eq_some_iff.2 _), rw hk, simp, apply decidable.em }, { intros a x hx y hy, simp at hx hy, cases hy.1 hx.1 } end⟩⟩ end computable_pred namespace nat open vector roption /-- A simplified basis for `partrec`. -/ inductive partrec' : ∀ {n}, (vector ℕ n →. ℕ) → Prop | prim {n f} : @primrec' n f → @partrec' n f | comp {m n f} (g : fin n → vector ℕ m →. ℕ) : partrec' f → (∀ i, partrec' (g i)) → partrec' (λ v, m_of_fn (λ i, g i v) >>= f) | rfind {n} {f : vector ℕ (n+1) → ℕ} : @partrec' (n+1) f → partrec' (λ v, rfind (λ n, some (f (n :: v) = 0))) end nat namespace nat.partrec' open vector partrec computable nat (partrec') nat.partrec' theorem to_part {n f} (pf : @partrec' n f) : partrec f := begin induction pf, case nat.partrec'.prim : n f hf { exact hf.to_prim.to_comp }, case nat.partrec'.comp : m n f g _ _ hf hg { exact (vector_m_of_fn (λ i, hg i)).bind (hf.comp snd) }, case nat.partrec'.rfind : n f _ hf { have := ((primrec.eq.comp primrec.id (primrec.const 0)).to_comp.comp (hf.comp (vector_cons.comp snd fst))).to₂.part, exact this.rfind }, end theorem of_eq {n} {f g : vector ℕ n →. ℕ} (hf : partrec' f) (H : ∀ i, f i = g i) : partrec' g := (funext H : f = g) ▸ hf theorem of_prim {n} {f : vector ℕ n → ℕ} (hf : primrec f) : @partrec' n f := prim (nat.primrec'.of_prim hf) theorem head {n : ℕ} : @partrec' n.succ (@head ℕ n) := prim nat.primrec'.head theorem tail {n f} (hf : @partrec' n f) : @partrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @prim _ _ $ nat.primrec'.nth i.succ)).of_eq $ λ v, by simp; rw [← of_fn_nth v.tail]; congr; funext i; simp protected theorem bind {n f g} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).bind (λ a, g (a :: v))) := (@comp n (n+1) g (λ i, fin.cases f (λ i v, some (v.nth i)) i) hg (λ i, begin refine fin.cases _ (λ i, _) i; simp *, exact prim (nat.primrec'.nth _) end)).of_eq $ λ v, by simp [m_of_fn, roption.bind_assoc, pure] protected theorem map {n f} {g : vector ℕ (n+1) → ℕ} (hf : @partrec' n f) (hg : @partrec' (n+1) g) : @partrec' n (λ v, (f v).map (λ a, g (a :: v))) := by simp [(roption.bind_some_eq_map _ _).symm]; exact hf.bind hg /-- Analogous to `nat.partrec'` for `ℕ`-valued functions, a predicate for partial recursive vector-valued functions.-/ def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, partrec' (λ v, (f v).nth i) theorem vec.prim {n m f} (hf : @nat.primrec'.vec n m f) : vec f := λ i, prim $ hf i protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m} {f : vector ℕ n → ℕ} {g} (hf : @partrec' n f) (hg : @vec n m g) : vec (λ v, f v :: g v) := λ i, fin.cases (by simp *) (λ i, by simp [hg i]) i theorem idv {n} : @vec n n id := vec.prim nat.primrec'.idv theorem comp' {n m f g} (hf : @partrec' m f) (hg : @vec n m g) : partrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ {n} (f : ℕ →. ℕ) {g : vector ℕ n → ℕ} (hf : @partrec' 1 (λ v, f v.head)) (hg : @partrec' n g) : @partrec' n (λ v, f (g v)) := by simpa using hf.comp' (partrec'.cons hg partrec'.nil) theorem rfind_opt {n} {f : vector ℕ (n+1) → ℕ} (hf : @partrec' (n+1) f) : @partrec' n (λ v, nat.rfind_opt (λ a, of_nat (option ℕ) (f (a :: v)))) := ((rfind $ (of_prim (primrec.nat_sub.comp (primrec.const 1) primrec.vector_head)) .comp₁ (λ n, roption.some (1 - n)) hf) .bind ((prim nat.primrec'.pred).comp₁ nat.pred hf)).of_eq $ λ v, roption.ext $ λ b, begin simp [nat.rfind_opt, -nat.mem_rfind], refine exists_congr (λ a, (and_congr (iff_of_eq _) iff.rfl).trans (and_congr_right (λ h, _))), { congr; funext n, simp, cases f (n :: v); simp [nat.succ_ne_zero]; refl }, { have := nat.rfind_spec h, simp at this, cases f (a :: v) with c, {cases this}, rw [← option.some_inj, eq_comm], refl } end open nat.partrec.code theorem of_part : ∀ {n f}, partrec f → @partrec' n f := suffices ∀ f, nat.partrec f → @partrec' 1 (λ v, f v.head), from λ n f hf, begin let g, swap, exact (comp₁ g (this g hf) (prim nat.primrec'.encode)).of_eq (λ i, by dsimp [g]; simp [encodek, roption.map_id']), end, λ f hf, begin rcases exists_code.1 hf with ⟨c, rfl⟩, simpa [eval_eq_rfind_opt] using (rfind_opt $ of_prim $ primrec.encode_iff.2 $ evaln_prim.comp $ (primrec.vector_head.pair (primrec.const c)).pair $ primrec.vector_head.comp primrec.vector_tail) end theorem part_iff {n f} : @partrec' n f ↔ partrec f := ⟨to_part, of_part⟩ theorem part_iff₁ {f : ℕ →. ℕ} : @partrec' 1 (λ v, f v.head) ↔ partrec f := part_iff.trans ⟨ λ h, (h.comp $ (primrec.vector_of_fn $ λ i, primrec.id).to_comp).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem part_iff₂ {f : ℕ → ℕ →. ℕ} : @partrec' 2 (λ v, f v.head v.tail.head) ↔ partrec₂ f := part_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (const nil)).of_eq (λ v, by simp), λ h, h.comp vector_head (vector_head.comp vector_tail)⟩ theorem vec_iff {m n f} : @vec m n f ↔ computable f := ⟨λ h, by simpa using vector_of_fn (λ i, to_part (h i)), λ h i, of_part $ vector_nth.comp h (const i)⟩ end nat.partrec'
19b04be8af8fadca483cc5519c0820dda058d668
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/convex/function.lean
9a3ff010574879afc0c5c67162eff23248d5ffcd
[ "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
37,453
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, François Dupuis -/ import analysis.convex.basic import order.order_dual import tactic.field_simp import tactic.linarith import tactic.ring /-! # Convex and concave functions This file defines convex and concave functions in vector spaces and proves the finite Jensen inequality. The integral version can be found in `analysis.convex.integral`. A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two points `x y ∈ s`, the segment joining `(x, f x)` to `(y, f y)` is above the graph of `f`. Equivalently, `convex_on 𝕜 f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is a convex set. ## Main declarations * `convex_on 𝕜 s f`: The function `f` is convex on `s` with scalars `𝕜`. * `concave_on 𝕜 s f`: The function `f` is concave on `s` with scalars `𝕜`. * `strict_convex_on 𝕜 s f`: The function `f` is strictly convex on `s` with scalars `𝕜`. * `strict_concave_on 𝕜 s f`: The function `f` is strictly concave on `s` with scalars `𝕜`. -/ open finset linear_map set open_locale big_operators classical convex pointwise variables {𝕜 E F β ι : Type*} section ordered_semiring variables [ordered_semiring 𝕜] section add_comm_monoid variables [add_comm_monoid E] [add_comm_monoid F] section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] section has_scalar variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 β] (s : set E) (f : E → β) /-- Convexity of functions -/ def convex_on : Prop := convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y /-- Concavity of functions -/ def concave_on : Prop := convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) /-- Strict convexity of functions -/ def strict_convex_on : Prop := convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) < a • f x + b • f y /-- Strict concavity of functions -/ def strict_concave_on : Prop := convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y < f (a • x + b • y) variables {𝕜 s f} open order_dual (to_dual of_dual) lemma convex_on.dual (hf : convex_on 𝕜 s f) : concave_on 𝕜 s (to_dual ∘ f) := hf lemma concave_on.dual (hf : concave_on 𝕜 s f) : convex_on 𝕜 s (to_dual ∘ f) := hf lemma strict_convex_on.dual (hf : strict_convex_on 𝕜 s f) : strict_concave_on 𝕜 s (to_dual ∘ f) := hf lemma strict_concave_on.dual (hf : strict_concave_on 𝕜 s f) : strict_convex_on 𝕜 s (to_dual ∘ f) := hf lemma convex_on_id {s : set β} (hs : convex 𝕜 s) : convex_on 𝕜 s id := ⟨hs, by { intros, refl }⟩ lemma concave_on_id {s : set β} (hs : convex 𝕜 s) : concave_on 𝕜 s id := ⟨hs, by { intros, refl }⟩ lemma convex_on.subset {t : set E} (hf : convex_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) : convex_on 𝕜 s f := ⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩ lemma concave_on.subset {t : set E} (hf : concave_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) : concave_on 𝕜 s f := ⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩ lemma strict_convex_on.subset {t : set E} (hf : strict_convex_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) : strict_convex_on 𝕜 s f := ⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩ lemma strict_concave_on.subset {t : set E} (hf : strict_concave_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) : strict_concave_on 𝕜 s f := ⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩ end has_scalar section distrib_mul_action variables [has_scalar 𝕜 E] [distrib_mul_action 𝕜 β] {s : set E} {f g : E → β} lemma convex_on.add (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) : convex_on 𝕜 s (f + g) := ⟨hf.1, λ x y hx hy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y) : add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab) ... = a • (f x + g x) + b • (f y + g y) : by rw [smul_add, smul_add, add_add_add_comm]⟩ lemma concave_on.add (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) : concave_on 𝕜 s (f + g) := hf.dual.add hg end distrib_mul_action section module variables [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β} lemma convex_on_const (c : β) (hs : convex 𝕜 s) : convex_on 𝕜 s (λ x:E, c) := ⟨hs, λ x y _ _ a b _ _ hab, (convex.combo_self hab c).ge⟩ lemma concave_on_const (c : β) (hs : convex 𝕜 s) : concave_on 𝕜 s (λ x:E, c) := @convex_on_const _ _ (order_dual β) _ _ _ _ _ _ c hs end module section ordered_smul variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} lemma convex_on.convex_le (hf : convex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x ≤ r} := λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha hb hab, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha hb hab ... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha) (smul_le_smul_of_nonneg hy.2 hb) ... = r : convex.combo_self hab r⟩ lemma concave_on.convex_ge (hf : concave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r ≤ f x} := hf.dual.convex_le r lemma convex_on.convex_epigraph (hf : convex_on 𝕜 s f) : convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} := begin rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha hb hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha) (smul_le_smul_of_nonneg ht hb) end lemma concave_on.convex_hypograph (hf : concave_on 𝕜 s f) : convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} := hf.dual.convex_epigraph lemma convex_on_iff_convex_epigraph : convex_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} := ⟨convex_on.convex_epigraph, λ h, ⟨λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).1, λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).2⟩⟩ lemma concave_on_iff_convex_hypograph : concave_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} := @convex_on_iff_convex_epigraph 𝕜 E (order_dual β) _ _ _ _ _ _ _ f end ordered_smul section module variables [module 𝕜 E] [has_scalar 𝕜 β] {s : set E} {f : E → β} /-- Right translation preserves convexity. -/ lemma convex_on.translate_right (hf : convex_on 𝕜 s f) (c : E) : convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) := ⟨hf.1.translate_preimage_right _, λ x y hx hy a b ha hb hab, calc f (c + (a • x + b • y)) = f (a • (c + x) + b • (c + y)) : by rw [smul_add, smul_add, add_add_add_comm, convex.combo_self hab] ... ≤ a • f (c + x) + b • f (c + y) : hf.2 hx hy ha hb hab⟩ /-- Right translation preserves concavity. -/ lemma concave_on.translate_right (hf : concave_on 𝕜 s f) (c : E) : concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) := hf.dual.translate_right _ /-- Left translation preserves convexity. -/ lemma convex_on.translate_left (hf : convex_on 𝕜 s f) (c : E) : convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) := by simpa only [add_comm] using hf.translate_right _ /-- Left translation preserves concavity. -/ lemma concave_on.translate_left (hf : concave_on 𝕜 s f) (c : E) : concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) := hf.dual.translate_left _ end module section module variables [module 𝕜 E] [module 𝕜 β] lemma convex_on_iff_forall_pos {s : set E} {f : E → β} : convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y := begin refine and_congr_right' ⟨λ h x y hx hy a b ha hb hab, h hx hy ha.le hb.le hab, λ h x y hx hy a b ha hb hab, _⟩, obtain rfl | ha' := ha.eq_or_lt, { rw [zero_add] at hab, subst b, simp_rw [zero_smul, zero_add, one_smul] }, obtain rfl | hb' := hb.eq_or_lt, { rw [add_zero] at hab, subst a, simp_rw [zero_smul, add_zero, one_smul] }, exact h hx hy ha' hb' hab, end lemma concave_on_iff_forall_pos {s : set E} {f : E → β} : concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y) := @convex_on_iff_forall_pos 𝕜 E (order_dual β) _ _ _ _ _ _ _ lemma convex_on_iff_pairwise_pos {s : set E} {f : E → β} : convex_on 𝕜 s f ↔ convex 𝕜 s ∧ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) := begin rw convex_on_iff_forall_pos, refine and_congr_right' ⟨λ h x hx y hy _ a b ha hb hab, h hx hy ha hb hab, λ h x y hx hy a b ha hb hab, _⟩, obtain rfl | hxy := eq_or_ne x y, { rw [convex.combo_self hab, convex.combo_self hab] }, exact h x hx y hy hxy ha hb hab, end lemma concave_on_iff_pairwise_pos {s : set E} {f : E → β} : concave_on 𝕜 s f ↔ convex 𝕜 s ∧ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) := @convex_on_iff_pairwise_pos 𝕜 E (order_dual β) _ _ _ _ _ _ _ /-- A linear map is convex. -/ lemma linear_map.convex_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : convex_on 𝕜 s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ /-- A linear map is concave. -/ lemma linear_map.concave_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : concave_on 𝕜 s f := ⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩ lemma strict_convex_on.convex_on {s : set E} {f : E → β} (hf : strict_convex_on 𝕜 s f) : convex_on 𝕜 s f := ⟨hf.1, λ x y hx hy a b ha hb hab, begin obtain rfl | hxy := eq_or_ne x y, { rw [convex.combo_self hab, convex.combo_self hab] }, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rw [hab, zero_smul, zero_smul, one_smul, one_smul, zero_add, zero_add] }, obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rw [hab, zero_smul, zero_smul, one_smul, one_smul, add_zero, add_zero] }, exact (hf.2 hx hy hxy ha' hb' hab).le, end⟩ lemma strict_concave_on.concave_on {s : set E} {f : E → β} (hf : strict_concave_on 𝕜 s f) : concave_on 𝕜 s f := hf.dual.convex_on section ordered_smul variables [ordered_smul 𝕜 β] {s : set E} {f : E → β} lemma strict_convex_on.convex_lt (hf : strict_convex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x < r} := convex_iff_pairwise_pos.2 $ λ x hx y hy hxy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha.le hb.le hab, calc f (a • x + b • y) < a • f x + b • f y : hf.2 hx.1 hy.1 hxy ha hb hab ... ≤ a • r + b • r : add_le_add (smul_lt_smul_of_pos hx.2 ha).le (smul_lt_smul_of_pos hy.2 hb).le ... = r : convex.combo_self hab r⟩ lemma strict_concave_on.convex_gt (hf : strict_concave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r < f x} := hf.dual.convex_lt r end ordered_smul section linear_order variables [linear_order E] {s : set E} {f : E → β} /-- For a function on a convex set in a linearly ordered space (where the order and the algebraic structures aren't necessarily compatible), in order to prove that it is convex, it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`, `b`. The main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order. -/ lemma linear_order.convex_on_of_lt (hs : convex 𝕜 s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) ≤ a • f x + b • f y) : convex_on 𝕜 s f := begin refine convex_on_iff_pairwise_pos.2 ⟨hs, λ x hx y hy hxy a b ha hb hab, _⟩, wlog h : x ≤ y using [x y a b, y x b a], { exact le_total _ _ }, exact hf hx hy (h.lt_of_ne hxy) ha hb hab, end /-- For a function on a convex set in a linearly ordered space (where the order and the algebraic structures aren't necessarily compatible), in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` for `x < y` and positive `a`, `b`. The main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/ lemma linear_order.concave_on_of_lt (hs : convex 𝕜 s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y ≤ f (a • x + b • y)) : concave_on 𝕜 s f := @linear_order.convex_on_of_lt _ _ (order_dual β) _ _ _ _ _ _ s f hs hf /-- For a function on a convex set in a linearly ordered space (where the order and the algebraic structures aren't necessarily compatible), in order to prove that it is convex, it suffices to verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` for `x < y` and positive `a`, `b`. The main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order. -/ lemma linear_order.strict_convex_on_of_lt (hs : convex 𝕜 s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → f (a • x + b • y) < a • f x + b • f y) : strict_convex_on 𝕜 s f := begin refine ⟨hs, λ x y hx hy hxy a b ha hb hab, _⟩, wlog h : x ≤ y using [x y a b, y x b a], { exact le_total _ _ }, exact hf hx hy (h.lt_of_ne hxy) ha hb hab, end /-- For a function on a convex set in a linearly ordered space (where the order and the algebraic structures aren't necessarily compatible), in order to prove that it is concave it suffices to verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` for `x < y` and positive `a`, `b`. The main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order. -/ lemma linear_order.strict_concave_on_of_lt (hs : convex 𝕜 s) (hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • f x + b • f y < f (a • x + b • y)) : strict_concave_on 𝕜 s f := @linear_order.strict_convex_on_of_lt _ _ (order_dual β) _ _ _ _ _ _ _ _ hs hf end linear_order end module section module variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β] /-- If `g` is convex on `s`, so is `(f ∘ g)` on `f ⁻¹' s` for a linear `f`. -/ lemma convex_on.comp_linear_map {f : F → β} {s : set F} (hf : convex_on 𝕜 s f) (g : E →ₗ[𝕜] F) : convex_on 𝕜 (g ⁻¹' s) (f ∘ g) := ⟨hf.1.linear_preimage _, λ x y hx hy a b ha hb hab, calc f (g (a • x + b • y)) = f (a • (g x) + b • (g y)) : by rw [g.map_add, g.map_smul, g.map_smul] ... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩ /-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/ lemma concave_on.comp_linear_map {f : F → β} {s : set F} (hf : concave_on 𝕜 s f) (g : E →ₗ[𝕜] F) : concave_on 𝕜 (g ⁻¹' s) (f ∘ g) := hf.dual.comp_linear_map g end module end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] section distrib_mul_action variables [has_scalar 𝕜 E] [distrib_mul_action 𝕜 β] {s : set E} {f g : E → β} lemma strict_convex_on.add (hf : strict_convex_on 𝕜 s f) (hg : strict_convex_on 𝕜 s g) : strict_convex_on 𝕜 s (f + g) := ⟨hf.1, λ x y hx hy hxy a b ha hb hab, calc f (a • x + b • y) + g (a • x + b • y) < (a • f x + b • f y) + (a • g x + b • g y) : add_lt_add (hf.2 hx hy hxy ha hb hab) (hg.2 hx hy hxy ha hb hab) ... = a • (f x + g x) + b • (f y + g y) : by rw [smul_add, smul_add, add_add_add_comm]⟩ lemma strict_concave_on.add (hf : strict_concave_on 𝕜 s f) (hg : strict_concave_on 𝕜 s g) : strict_concave_on 𝕜 s (f + g) := hf.dual.add hg end distrib_mul_action section module variables [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} lemma convex_on.convex_lt (hf : convex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x < r} := convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha.le hb.le hab, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha.le hb.le hab ... < a • r + b • r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx.2 ha) (smul_le_smul_of_nonneg hy.2.le hb.le) ... = r : convex.combo_self hab _⟩ lemma concave_on.convex_gt (hf : concave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r < f x} := hf.dual.convex_lt r lemma convex_on.convex_strict_epigraph (hf : convex_on 𝕜 s f) : convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 < p.2} := begin rw convex_iff_forall_pos, rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab, refine ⟨hf.1 hx hy ha.le hb.le hab, _⟩, calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb.le hab ... < a • r + b • t : add_lt_add (smul_lt_smul_of_pos hr ha) (smul_lt_smul_of_pos ht hb) end lemma concave_on.convex_strict_hypograph (hf : concave_on 𝕜 s f) : convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 < f p.1} := hf.dual.convex_strict_epigraph end module end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid β] [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β} /-- The pointwise maximum of convex functions is convex. -/ lemma convex_on.sup (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) : convex_on 𝕜 s (f ⊔ g) := begin refine ⟨hf.left, λ x y hx hy a b ha hb hab, sup_le _ _⟩, { calc f (a • x + b • y) ≤ a • f x + b • f y : hf.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_left ha) (smul_le_smul_of_nonneg le_sup_left hb) }, { calc g (a • x + b • y) ≤ a • g x + b • g y : hg.right hx hy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_right ha) (smul_le_smul_of_nonneg le_sup_right hb) } end /-- The pointwise minimum of concave functions is concave. -/ lemma concave_on.inf (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) : concave_on 𝕜 s (f ⊓ g) := hf.dual.sup hg /-- The pointwise maximum of strictly convex functions is strictly convex. -/ lemma strict_convex_on.sup (hf : strict_convex_on 𝕜 s f) (hg : strict_convex_on 𝕜 s g) : strict_convex_on 𝕜 s (f ⊔ g) := ⟨hf.left, λ x y hx hy hxy a b ha hb hab, max_lt (calc f (a • x + b • y) < a • f x + b • f y : hf.2 hx hy hxy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_left ha.le) (smul_le_smul_of_nonneg le_sup_left hb.le)) (calc g (a • x + b • y) < a • g x + b • g y : hg.2 hx hy hxy ha hb hab ... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add (smul_le_smul_of_nonneg le_sup_right ha.le) (smul_le_smul_of_nonneg le_sup_right hb.le))⟩ /-- The pointwise minimum of strictly concave functions is strictly concave. -/ lemma strict_concave_on.inf (hf : strict_concave_on 𝕜 s f) (hg : strict_concave_on 𝕜 s g) : strict_concave_on 𝕜 s (f ⊓ g) := hf.dual.sup hg /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : f (a • x + b • y) ≤ max (f x) (f y) := calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb) ... = max (f x) (f y) : convex.combo_self hab _ /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.ge_on_segment' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min (f x) (f y) ≤ f (a • x + b • y) := hf.dual.le_on_segment' hx hy ha hb hab /-- A convex function on a segment is upper-bounded by the max of its endpoints. -/ lemma convex_on.le_on_segment (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x -[𝕜] y]) : f z ≤ max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab /-- A concave function on a segment is lower-bounded by the min of its endpoints. -/ lemma concave_on.ge_on_segment (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ [x -[𝕜] y]) : min (f x) (f y) ≤ f z := hf.dual.le_on_segment hx hy hz /-- A strictly convex function on an open segment is strictly upper-bounded by the max of its endpoints. -/ lemma strict_convex_on.lt_on_open_segment' (hf : strict_convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : f (a • x + b • y) < max (f x) (f y) := calc f (a • x + b • y) < a • f x + b • f y : hf.2 hx hy hxy ha hb hab ... ≤ a • max (f x) (f y) + b • max (f x) (f y) : add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha.le) (smul_le_smul_of_nonneg (le_max_right _ _) hb.le) ... = max (f x) (f y) : convex.combo_self hab _ /-- A strictly concave function on an open segment is strictly lower-bounded by the min of its endpoints. -/ lemma strict_concave_on.lt_on_open_segment' (hf : strict_concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) : min (f x) (f y) < f (a • x + b • y) := hf.dual.lt_on_open_segment' hx hy hxy ha hb hab /-- A strictly convex function on an open segment is strictly upper-bounded by the max of its endpoints. -/ lemma strict_convex_on.lt_on_open_segment (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) (hz : z ∈ open_segment 𝕜 x y) : f z < max (f x) (f y) := let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.lt_on_open_segment' hx hy hxy ha hb hab /-- A strictly concave function on an open segment is strictly lower-bounded by the min of its endpoints. -/ lemma strict_concave_on.lt_on_open_segment (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hxy : x ≠ y) (hz : z ∈ open_segment 𝕜 x y) : min (f x) (f y) < f z := hf.dual.lt_on_open_segment hx hy hxy hz end linear_ordered_add_comm_monoid section linear_ordered_cancel_add_comm_monoid variables [linear_ordered_cancel_add_comm_monoid β] section ordered_smul variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β} lemma convex_on.le_left_of_right_le' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f y ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f x := le_of_not_lt $ λ h, lt_irrefl (f (a • x + b • y)) $ calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab ... < a • f (a • x + b • y) + b • f (a • x + b • y) : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hfy hb) ... = f (a • x + b • y) : convex.combo_self hab _ lemma concave_on.left_le_of_le_right' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f (a • x + b • y) ≤ f y) : f x ≤ f (a • x + b • y) := hf.dual.le_left_of_right_le' hx hy ha hb hab hfy lemma convex_on.le_right_of_left_le' (hf : convex_on 𝕜 s f) {x y : E} {a b : 𝕜} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hfx : f x ≤ f (a • x + b • y)) : f (a • x + b • y) ≤ f y := begin rw add_comm at ⊢ hab hfx, exact hf.le_left_of_right_le' hy hx hb ha hab hfx, end lemma concave_on.le_right_of_left_le' (hf : concave_on 𝕜 s f) {x y : E} {a b : 𝕜} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) (hfx : f (a • x + b • y) ≤ f x) : f y ≤ f (a • x + b • y) := hf.dual.le_right_of_left_le' hx hy ha hb hab hfx lemma convex_on.le_left_of_right_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f y ≤ f z) : f z ≤ f x := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz, end lemma concave_on.left_le_of_le_right (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f z ≤ f y) : f x ≤ f z := hf.dual.le_left_of_right_le hx hy hz hyz lemma convex_on.le_right_of_left_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f x ≤ f z) : f z ≤ f y := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz, end lemma concave_on.le_right_of_left_le (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f z ≤ f x) : f y ≤ f z := hf.dual.le_right_of_left_le hx hy hz hxz end ordered_smul section module variables [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β} /- The following lemmas don't require `module 𝕜 E` if you add the hypothesis `x ≠ y`. At the time of the writing, we decided the resulting lemmas wouldn't be useful. Feel free to reintroduce them. -/ lemma strict_convex_on.lt_left_of_right_lt' (hf : strict_convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (hfy : f y < f (a • x + b • y)) : f (a • x + b • y) < f x := not_le.1 $ λ h, lt_irrefl (f (a • x + b • y)) $ calc f (a • x + b • y) < a • f x + b • f y : hf.2 hx hy begin rintro rfl, rw convex.combo_self hab at hfy, exact lt_irrefl _ hfy, end ha hb hab ... < a • f (a • x + b • y) + b • f (a • x + b • y) : add_lt_add_of_le_of_lt (smul_le_smul_of_nonneg h ha.le) (smul_lt_smul_of_pos hfy hb) ... = f (a • x + b • y) : convex.combo_self hab _ lemma strict_concave_on.left_lt_of_lt_right' (hf : strict_concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (hfy : f (a • x + b • y) < f y) : f x < f (a • x + b • y) := hf.dual.lt_left_of_right_lt' hx hy ha hb hab hfy lemma strict_convex_on.lt_right_of_left_lt' (hf : strict_convex_on 𝕜 s f) {x y : E} {a b : 𝕜} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (hfx : f x < f (a • x + b • y)) : f (a • x + b • y) < f y := begin rw add_comm at ⊢ hab hfx, exact hf.lt_left_of_right_lt' hy hx hb ha hab hfx, end lemma strict_concave_on.lt_right_of_left_lt' (hf : strict_concave_on 𝕜 s f) {x y : E} {a b : 𝕜} (hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) (hfx : f (a • x + b • y) < f x) : f y < f (a • x + b • y) := hf.dual.lt_right_of_left_lt' hx hy ha hb hab hfx lemma strict_convex_on.lt_left_of_right_lt (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f y < f z) : f z < f x := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.lt_left_of_right_lt' hx hy ha hb hab hyz, end lemma strict_concave_on.left_lt_of_lt_right (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f z < f y) : f x < f z := hf.dual.lt_left_of_right_lt hx hy hz hyz lemma strict_convex_on.lt_right_of_left_lt (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f x < f z) : f z < f y := begin obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz, exact hf.lt_right_of_left_lt' hx hy ha hb hab hxz, end lemma strict_concave_on.lt_right_of_left_lt (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f z < f x) : f y < f z := hf.dual.lt_right_of_left_lt hx hy hz hxz end module end linear_ordered_cancel_add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group β] [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β} /-- A function `-f` is convex iff `f` is concave. -/ @[simp] lemma neg_convex_on_iff : convex_on 𝕜 s (-f) ↔ concave_on 𝕜 s f := begin split, { rintro ⟨hconv, h⟩, refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩, simp [neg_apply, neg_le, add_comm] at h, exact h hx hy ha hb hab }, { rintro ⟨hconv, h⟩, refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩, rw ←neg_le_neg_iff, simp_rw [neg_add, pi.neg_apply, smul_neg, neg_neg], exact h hx hy ha hb hab } end /-- A function `-f` is concave iff `f` is convex. -/ @[simp] lemma neg_concave_on_iff : concave_on 𝕜 s (-f) ↔ convex_on 𝕜 s f:= by rw [← neg_convex_on_iff, neg_neg f] /-- A function `-f` is strictly convex iff `f` is strictly concave. -/ @[simp] lemma neg_strict_convex_on_iff : strict_convex_on 𝕜 s (-f) ↔ strict_concave_on 𝕜 s f := begin split, { rintro ⟨hconv, h⟩, refine ⟨hconv, λ x y hx hy hxy a b ha hb hab, _⟩, simp [neg_apply, neg_lt, add_comm] at h, exact h hx hy hxy ha hb hab }, { rintro ⟨hconv, h⟩, refine ⟨hconv, λ x y hx hy hxy a b ha hb hab, _⟩, rw ←neg_lt_neg_iff, simp_rw [neg_add, pi.neg_apply, smul_neg, neg_neg], exact h hx hy hxy ha hb hab } end /-- A function `-f` is strictly concave iff `f` is strictly convex. -/ @[simp] lemma neg_strict_concave_on_iff : strict_concave_on 𝕜 s (-f) ↔ strict_convex_on 𝕜 s f := by rw [← neg_strict_convex_on_iff, neg_neg f] alias neg_convex_on_iff ↔ _ concave_on.neg alias neg_concave_on_iff ↔ _ convex_on.neg alias neg_strict_convex_on_iff ↔ _ strict_concave_on.neg alias neg_strict_concave_on_iff ↔ _ strict_convex_on.neg end ordered_add_comm_group end add_comm_monoid section add_cancel_comm_monoid variables [add_cancel_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E] [has_scalar 𝕜 β] {s : set E} {f : E → β} /-- Right translation preserves strict convexity. -/ lemma strict_convex_on.translate_right (hf : strict_convex_on 𝕜 s f) (c : E) : strict_convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) := ⟨hf.1.translate_preimage_right _, λ x y hx hy hxy a b ha hb hab, calc f (c + (a • x + b • y)) = f (a • (c + x) + b • (c + y)) : by rw [smul_add, smul_add, add_add_add_comm, convex.combo_self hab] ... < a • f (c + x) + b • f (c + y) : hf.2 hx hy ((add_right_injective c).ne hxy) ha hb hab⟩ /-- Right translation preserves strict concavity. -/ lemma strict_concave_on.translate_right (hf : strict_concave_on 𝕜 s f) (c : E) : strict_concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) := hf.dual.translate_right _ /-- Left translation preserves strict convexity. -/ lemma strict_convex_on.translate_left (hf : strict_convex_on 𝕜 s f) (c : E) : strict_convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) := by simpa only [add_comm] using hf.translate_right _ /-- Left translation preserves strict concavity. -/ lemma strict_concave_on.translate_left (hf : strict_concave_on 𝕜 s f) (c : E) : strict_concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) := by simpa only [add_comm] using hf.translate_right _ end add_cancel_comm_monoid end ordered_semiring section ordered_comm_semiring variables [ordered_comm_semiring 𝕜] [add_comm_monoid E] section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] section module variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β} lemma convex_on.smul {c : 𝕜} (hc : 0 ≤ c) (hf : convex_on 𝕜 s f) : convex_on 𝕜 s (λ x, c • f x) := ⟨hf.1, λ x y hx hy a b ha hb hab, calc c • f (a • x + b • y) ≤ c • (a • f x + b • f y) : smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc ... = a • (c • f x) + b • (c • f y) : by rw [smul_add, smul_comm c, smul_comm c]; apply_instance⟩ lemma concave_on.smul {c : 𝕜} (hc : 0 ≤ c) (hf : concave_on 𝕜 s f) : concave_on 𝕜 s (λ x, c • f x) := hf.dual.smul hc end module end ordered_add_comm_monoid end ordered_comm_semiring section ordered_ring variables [linear_ordered_field 𝕜] [add_comm_group E] [add_comm_group F] section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] section module variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β] /-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/ lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : convex_on 𝕜 s f) : convex_on 𝕜 (g ⁻¹' s) (f ∘ g) := ⟨hf.1.affine_preimage _, λ x y hx hy a b ha hb hab, calc (f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl ... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab] ... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩ /-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/ lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : concave_on 𝕜 s f) : concave_on 𝕜 (g ⁻¹' s) (f ∘ g) := hf.dual.comp_affine_map g end module end ordered_add_comm_monoid end ordered_ring section linear_ordered_field variables [linear_ordered_field 𝕜] [add_comm_monoid E] section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] section has_scalar variables [has_scalar 𝕜 E] [has_scalar 𝕜 β] {s : set E} lemma convex_on_iff_div {f : E → β} : convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy a b ha hb hab, apply h hx hy (div_nonneg ha hab.le) (div_nonneg hb hab.le), rw [←add_div, div_self hab.ne'], end, begin intros h x y hx hy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy ha hb, end⟩ lemma concave_on_iff_div {f : E → β} : concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) := @convex_on_iff_div _ _ (order_dual β) _ _ _ _ _ _ _ lemma strict_convex_on_iff_div {f : E → β} : strict_convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → f ((a/(a+b)) • x + (b/(a+b)) • y) < (a/(a+b)) • f x + (b/(a+b)) • f y := and_congr iff.rfl ⟨begin intros h x y hx hy hxy a b ha hb, have hab := add_pos ha hb, apply h hx hy hxy (div_pos ha hab) (div_pos hb hab), rw [←add_div, div_self hab.ne'], end, begin intros h x y hx hy hxy a b ha hb hab, simpa [hab, zero_lt_one] using h hx hy hxy ha hb, end⟩ lemma strict_concave_on_iff_div {f : E → β} : strict_concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → (a/(a+b)) • f x + (b/(a+b)) • f y < f ((a/(a+b)) • x + (b/(a+b)) • y) := @strict_convex_on_iff_div _ _ (order_dual β) _ _ _ _ _ _ _ end has_scalar end ordered_add_comm_monoid end linear_ordered_field
0b2717f6573650a561ca1397e977ff7428422853
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/constructions/polish.lean
4d548be5a4024dbd40e951d7896a3b0df34007d7
[ "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
33,410
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.metric_space.polish import measure_theory.constructions.borel_space /-! # The Borel sigma-algebra on Polish spaces We discuss several results pertaining to the relationship between the topology and the Borel structure on Polish spaces. ## Main definitions and results First, we define the class of analytic sets and establish its basic properties. * `measure_theory.analytic_set s`: a set in a topological space is analytic if it is the continuous image of a Polish space. Equivalently, it is empty, or the image of `ℕ → ℕ`. * `measure_theory.analytic_set.image_of_continuous`: a continuous image of an analytic set is analytic. * `measurable_set.analytic_set`: in a Polish space, any Borel-measurable set is analytic. Then, we show Lusin's theorem that two disjoint analytic sets can be separated by Borel sets. * `measurably_separable s t` states that there exists a measurable set containing `s` and disjoint from `t`. * `analytic_set.measurably_separable` shows that two disjoint analytic sets are separated by a Borel set. Finally, we prove the Lusin-Souslin theorem that a continuous injective image of a Borel subset of a Polish space is Borel. The proof of this nontrivial result relies on the above results on analytic sets. * `measurable_set.image_of_continuous_on_inj_on` asserts that, if `s` is a Borel measurable set in a Polish space, then the image of `s` under a continuous injective map is still Borel measurable. * `continuous.measurable_embedding` states that a continuous injective map on a Polish space is a measurable embedding for the Borel sigma-algebra. * `continuous_on.measurable_embedding` is the same result for a map restricted to a measurable set on which it is continuous. * `measurable.measurable_embedding` states that a measurable injective map from a Polish space to a second-countable topological space is a measurable embedding. * `is_clopenable_iff_measurable_set`: in a Polish space, a set is clopenable (i.e., it can be made open and closed by using a finer Polish topology) if and only if it is Borel-measurable. -/ open set function polish_space pi_nat topological_space metric filter open_locale topological_space measure_theory variables {α : Type*} [topological_space α] {ι : Type*} namespace measure_theory /-! ### Analytic sets -/ /-- An analytic set is a set which is the continuous image of some Polish space. There are several equivalent characterizations of this definition. For the definition, we pick one that avoids universe issues: a set is analytic if and only if it is a continuous image of `ℕ → ℕ` (or if it is empty). The above more usual characterization is given in `analytic_set_iff_exists_polish_space_range`. Warning: these are analytic sets in the context of descriptive set theory (which is why they are registered in the namespace `measure_theory`). They have nothing to do with analytic sets in the context of complex analysis. -/ @[irreducible] def analytic_set (s : set α) : Prop := s = ∅ ∨ ∃ (f : (ℕ → ℕ) → α), continuous f ∧ range f = s lemma analytic_set_empty : analytic_set (∅ : set α) := begin rw analytic_set, exact or.inl rfl end lemma analytic_set_range_of_polish_space {β : Type*} [topological_space β] [polish_space β] {f : β → α} (f_cont : continuous f) : analytic_set (range f) := begin casesI is_empty_or_nonempty β, { rw range_eq_empty, exact analytic_set_empty }, { rw analytic_set, obtain ⟨g, g_cont, hg⟩ : ∃ (g : (ℕ → ℕ) → β), continuous g ∧ surjective g := exists_nat_nat_continuous_surjective β, refine or.inr ⟨f ∘ g, f_cont.comp g_cont, _⟩, rwa hg.range_comp } end /-- The image of an open set under a continuous map is analytic. -/ lemma _root_.is_open.analytic_set_image {β : Type*} [topological_space β] [polish_space β] {s : set β} (hs : is_open s) {f : β → α} (f_cont : continuous f) : analytic_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := hs.polish_space, exact analytic_set_range_of_polish_space (f_cont.comp continuous_subtype_coe), end /-- A set is analytic if and only if it is the continuous image of some Polish space. -/ theorem analytic_set_iff_exists_polish_space_range {s : set α} : analytic_set s ↔ ∃ (β : Type) (h : topological_space β) (h' : @polish_space β h) (f : β → α), @continuous _ _ h _ f ∧ range f = s := begin split, { assume h, rw analytic_set at h, cases h, { refine ⟨empty, by apply_instance, by apply_instance, empty.elim, continuous_bot, _⟩, rw h, exact range_eq_empty _ }, { exact ⟨ℕ → ℕ, by apply_instance, by apply_instance, h⟩ } }, { rintros ⟨β, h, h', f, f_cont, f_range⟩, resetI, rw ← f_range, exact analytic_set_range_of_polish_space f_cont } end /-- The continuous image of an analytic set is analytic -/ lemma analytic_set.image_of_continuous_on {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous_on f s) : analytic_set (f '' s) := begin rcases analytic_set_iff_exists_polish_space_range.1 hs with ⟨γ, γtop, γpolish, g, g_cont, gs⟩, resetI, have : f '' s = range (f ∘ g), by rw [range_comp, gs], rw this, apply analytic_set_range_of_polish_space, apply hf.comp_continuous g_cont (λ x, _), rw ← gs, exact mem_range_self _ end lemma analytic_set.image_of_continuous {β : Type*} [topological_space β] {s : set α} (hs : analytic_set s) {f : α → β} (hf : continuous f) : analytic_set (f '' s) := hs.image_of_continuous_on hf.continuous_on /-- A countable intersection of analytic sets is analytic. -/ theorem analytic_set.Inter [hι : nonempty ι] [encodable ι] [t2_space α] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋂ n, s n) := begin unfreezingI { rcases hι with ⟨i₀⟩ }, /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The product space `γ = Π n, β n` is also Polish, and so is the subset `t` of sequences `x n` for which `f n (x n)` is independent of `n`. The set `t` is Polish, and the range of `x ↦ f 0 (x 0)` on `t` is exactly `⋂ n, s n`, so this set is analytic. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Π n, β n, let t : set γ := ⋂ n, {x | f n (x n) = f i₀ (x i₀)}, have t_closed : is_closed t, { apply is_closed_Inter, assume n, exact is_closed_eq ((f_cont n).comp (continuous_apply n)) ((f_cont i₀).comp (continuous_apply i₀)) }, haveI : polish_space t := t_closed.polish_space, let F : t → α := λ x, f i₀ ((x : γ) i₀), have F_cont : continuous F := (f_cont i₀).comp ((continuous_apply i₀).comp continuous_subtype_coe), have F_range : range F = ⋂ (n : ι), s n, { apply subset.antisymm, { rintros y ⟨x, rfl⟩, apply mem_Inter.2 (λ n, _), have : f n ((x : γ) n) = F x := (mem_Inter.1 x.2 n : _), rw [← this, ← f_range n], exact mem_range_self _ }, { assume y hy, have A : ∀ n, ∃ (x : β n), f n x = y, { assume n, rw [← mem_range, f_range n], exact mem_Inter.1 hy n }, choose x hx using A, have xt : x ∈ t, { apply mem_Inter.2 (λ n, _), simp [hx] }, refine ⟨⟨x, xt⟩, _⟩, exact hx i₀ } }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end /-- A countable union of analytic sets is analytic. -/ theorem analytic_set.Union [encodable ι] {s : ι → set α} (hs : ∀ n, analytic_set (s n)) : analytic_set (⋃ n, s n) := begin /- For the proof, write each `s n` as the continuous image under a map `f n` of a Polish space `β n`. The union space `γ = Σ n, β n` is also Polish, and the map `F : γ → α` which coincides with `f n` on `β n` sends it to `⋃ n, s n`. -/ choose β hβ h'β f f_cont f_range using λ n, analytic_set_iff_exists_polish_space_range.1 (hs n), resetI, let γ := Σ n, β n, let F : γ → α := by { rintros ⟨n, x⟩, exact f n x }, have F_cont : continuous F := continuous_sigma f_cont, have F_range : range F = ⋃ n, s n, { rw [range_sigma_eq_Union_range], congr, ext1 n, rw ← f_range n }, rw ← F_range, exact analytic_set_range_of_polish_space F_cont, end theorem _root_.is_closed.analytic_set [polish_space α] {s : set α} (hs : is_closed s) : analytic_set s := begin haveI : polish_space s := hs.polish_space, rw ← @subtype.range_val α s, exact analytic_set_range_of_polish_space continuous_subtype_coe, end /-- Given a Borel-measurable set in a Polish space, there exists a finer Polish topology making it clopen. This is in fact an equivalence, see `is_clopenable_iff_measurable_set`. -/ lemma _root_.measurable_set.is_clopenable [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : is_clopenable s := begin revert s, apply measurable_set.induction_on_open, { exact λ u hu, hu.is_clopenable }, { exact λ u hu h'u, h'u.compl }, { exact λ f f_disj f_meas hf, is_clopenable.Union hf } end theorem _root_.measurable_set.analytic_set {α : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] {s : set α} (hs : measurable_set s) : analytic_set s := begin /- For a short proof (avoiding measurable induction), one sees `s` as a closed set for a finer topology `t'`. It is analytic for this topology. As the identity from `t'` to `t` is continuous and the image of an analytic set is analytic, it follows that `s` is also analytic for `t`. -/ obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space α), t' ≤ t ∧ @polish_space α t' ∧ @is_closed α t' s ∧ @is_open α t' s := hs.is_clopenable, have A := @is_closed.analytic_set α t' t'_polish s s_closed, convert @analytic_set.image_of_continuous α t' α t s A id (continuous_id_of_le t't), simp only [id.def, image_id'], end /-- Given a Borel-measurable function from a Polish space to a second-countable space, there exists a finer Polish topology on the source space for which the function is continuous. -/ lemma _root_.measurable.exists_continuous {α β : Type*} [t : topological_space α] [polish_space α] [measurable_space α] [borel_space α] [tβ : topological_space β] [second_countable_topology β] [measurable_space β] [borel_space β] {f : α → β} (hf : measurable f) : ∃ (t' : topological_space α), t' ≤ t ∧ @continuous α β t' tβ f ∧ @polish_space α t' := begin obtain ⟨b, b_count, -, hb⟩ : ∃b : set (set β), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis β, haveI : encodable b := b_count.to_encodable, have : ∀ (s : b), is_clopenable (f ⁻¹' s), { assume s, apply measurable_set.is_clopenable, exact hf (hb.is_open s.2).measurable_set }, choose T Tt Tpolish Tclosed Topen using this, obtain ⟨t', t'T, t't, t'_polish⟩ : ∃ (t' : topological_space α), (∀ i, t' ≤ T i) ∧ (t' ≤ t) ∧ @polish_space α t' := exists_polish_space_forall_le T Tt Tpolish, refine ⟨t', t't, _, t'_polish⟩, apply hb.continuous _ (λ s hs, _), exact t'T ⟨s, hs⟩ _ (Topen ⟨s, hs⟩), end /-! ### Separating sets with measurable sets -/ /-- Two sets `u` and `v` in a measurable space are measurably separable if there exists a measurable set containing `u` and disjoint from `v`. This is mostly interesting for Borel-separable sets. -/ def measurably_separable {α : Type*} [measurable_space α] (s t : set α) : Prop := ∃ u, s ⊆ u ∧ disjoint t u ∧ measurable_set u lemma measurably_separable.Union [encodable ι] {α : Type*} [measurable_space α] {s t : ι → set α} (h : ∀ m n, measurably_separable (s m) (t n)) : measurably_separable (⋃ n, s n) (⋃ m, t m) := begin choose u hsu htu hu using h, refine ⟨⋃ m, (⋂ n, u m n), _, _, _⟩, { refine Union_subset (λ m, subset_Union_of_subset m _), exact subset_Inter (λ n, hsu m n) }, { simp_rw [disjoint_Union_left, disjoint_Union_right], assume n m, apply disjoint.mono_right _ (htu m n), apply Inter_subset }, { refine measurable_set.Union (λ m, _), exact measurable_set.Inter (λ n, hu m n) } end /-- The hard part of the Lusin separation theorem saying that two disjoint analytic sets are contained in disjoint Borel sets (see the full statement in `analytic_set.measurably_separable`). Here, we prove this when our analytic sets are the ranges of functions from `ℕ → ℕ`. -/ lemma measurably_separable_range_of_disjoint [t2_space α] [measurable_space α] [borel_space α] {f g : (ℕ → ℕ) → α} (hf : continuous f) (hg : continuous g) (h : disjoint (range f) (range g)) : measurably_separable (range f) (range g) := begin /- We follow [Kechris, *Classical Descriptive Set Theory* (Theorem 14.7)][kechris1995]. If the ranges are not Borel-separated, then one can find two cylinders of length one whose images are not Borel-separated, and then two smaller cylinders of length two whose images are not Borel-separated, and so on. One thus gets two sequences of cylinders, that decrease to two points `x` and `y`. Their images are different by the disjointness assumption, hence contained in two disjoint open sets by the T2 property. By continuity, long enough cylinders around `x` and `y` have images which are separated by these two disjoint open sets, a contradiction. -/ by_contra hfg, have I : ∀ n x y, (¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)))) → ∃ x' y', x' ∈ cylinder x n ∧ y' ∈ cylinder y n ∧ ¬(measurably_separable (f '' (cylinder x' (n+1))) (g '' (cylinder y' (n+1)))), { assume n x y, contrapose!, assume H, rw [← Union_cylinder_update x n, ← Union_cylinder_update y n, image_Union, image_Union], refine measurably_separable.Union (λ i j, _), exact H _ _ (update_mem_cylinder _ _ _) (update_mem_cylinder _ _ _) }, -- consider the set of pairs of cylinders of some length whose images are not Borel-separated let A := {p : ℕ × (ℕ → ℕ) × (ℕ → ℕ) // ¬(measurably_separable (f '' (cylinder p.2.1 p.1)) (g '' (cylinder p.2.2 p.1)))}, -- for each such pair, one can find longer cylinders whose images are not Borel-separated either have : ∀ (p : A), ∃ (q : A), q.1.1 = p.1.1 + 1 ∧ q.1.2.1 ∈ cylinder p.1.2.1 p.1.1 ∧ q.1.2.2 ∈ cylinder p.1.2.2 p.1.1, { rintros ⟨⟨n, x, y⟩, hp⟩, rcases I n x y hp with ⟨x', y', hx', hy', h'⟩, exact ⟨⟨⟨n+1, x', y'⟩, h'⟩, rfl, hx', hy'⟩ }, choose F hFn hFx hFy using this, let p0 : A := ⟨⟨0, λ n, 0, λ n, 0⟩, by simp [hfg]⟩, -- construct inductively decreasing sequences of cylinders whose images are not separated let p : ℕ → A := λ n, F^[n] p0, have prec : ∀ n, p (n+1) = F (p n) := λ n, by simp only [p, iterate_succ'], -- check that at the `n`-th step we deal with cylinders of length `n` have pn_fst : ∀ n, (p n).1.1 = n, { assume n, induction n with n IH, { refl }, { simp only [prec, hFn, IH] } }, -- check that the cylinders we construct are indeed decreasing, by checking that the coordinates -- are stationary. have Ix : ∀ m n, m + 1 ≤ n → (p n).1.2.1 m = (p (m+1)).1.2.1 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.fst m = (p n).val.snd.fst m, { apply hFx (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, have Iy : ∀ m n, m + 1 ≤ n → (p n).1.2.2 m = (p (m+1)).1.2.2 m, { assume m, apply nat.le_induction, { refl }, assume n hmn IH, have I : (F (p n)).val.snd.snd m = (p n).val.snd.snd m, { apply hFy (p n) m, rw pn_fst, exact hmn }, rw [prec, I, IH] }, -- denote by `x` and `y` the limit points of these two sequences of cylinders. set x : ℕ → ℕ := λ n, (p (n+1)).1.2.1 n with hx, set y : ℕ → ℕ := λ n, (p (n+1)).1.2.2 n with hy, -- by design, the cylinders around these points have images which are not Borel-separable. have M : ∀ n, ¬(measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n))), { assume n, convert (p n).2 using 3, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hx, exact (Ix i n hi).symm }, { rw [pn_fst, ← mem_cylinder_iff_eq, mem_cylinder_iff], assume i hi, rw hy, exact (Iy i n hi).symm } }, -- consider two open sets separating `f x` and `g y`. obtain ⟨u, v, u_open, v_open, xu, yv, huv⟩ : ∃ u v : set α, is_open u ∧ is_open v ∧ f x ∈ u ∧ g y ∈ v ∧ u ∩ v = ∅, { apply t2_separation, exact disjoint_iff_forall_ne.1 h _ (mem_range_self _) _ (mem_range_self _) }, letI : metric_space (ℕ → ℕ) := metric_space_nat_nat, obtain ⟨εx, εxpos, hεx⟩ : ∃ (εx : ℝ) (H : εx > 0), metric.ball x εx ⊆ f ⁻¹' u, { apply metric.mem_nhds_iff.1, exact hf.continuous_at.preimage_mem_nhds (u_open.mem_nhds xu) }, obtain ⟨εy, εypos, hεy⟩ : ∃ (εy : ℝ) (H : εy > 0), metric.ball y εy ⊆ g ⁻¹' v, { apply metric.mem_nhds_iff.1, exact hg.continuous_at.preimage_mem_nhds (v_open.mem_nhds yv) }, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2 : ℝ)^n < min εx εy := exists_pow_lt_of_lt_one (lt_min εxpos εypos) (by norm_num), -- for large enough `n`, these open sets separate the images of long cylinders around `x` and `y` have B : measurably_separable (f '' (cylinder x n)) (g '' (cylinder y n)), { refine ⟨u, _, _, u_open.measurable_set⟩, { rw image_subset_iff, apply subset.trans _ hεx, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_left _ _)) }, { have D : disjoint v u, by rwa [disjoint_iff_inter_eq_empty, inter_comm], apply disjoint.mono_left _ D, change g '' cylinder y n ⊆ v, rw image_subset_iff, apply subset.trans _ hεy, assume z hz, rw mem_cylinder_iff_dist_le at hz, exact hz.trans_lt (hn.trans_le (min_le_right _ _)) } }, -- this is a contradiction. exact M n B end /-- The Lusin separation theorem: if two analytic sets are disjoint, then they are contained in disjoint Borel sets. -/ theorem analytic_set.measurably_separable [t2_space α] [measurable_space α] [borel_space α] {s t : set α} (hs : analytic_set s) (ht : analytic_set t) (h : disjoint s t) : measurably_separable s t := begin rw analytic_set at hs ht, rcases hs with rfl|⟨f, f_cont, rfl⟩, { refine ⟨∅, subset.refl _, by simp, measurable_set.empty⟩ }, rcases ht with rfl|⟨g, g_cont, rfl⟩, { exact ⟨univ, subset_univ _, by simp, measurable_set.univ⟩ }, exact measurably_separable_range_of_disjoint f_cont g_cont h, end /-! ### Injective images of Borel sets -/ variables {γ : Type*} [tγ : topological_space γ] [polish_space γ] include tγ /-- The Lusin-Souslin theorem: the range of a continuous injective function defined on a Polish space is Borel-measurable. -/ theorem measurable_set_range_of_continuous_injective {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {f : γ → β} (f_cont : continuous f) (f_inj : injective f) : measurable_set (range f) := begin /- We follow [Fremlin, *Measure Theory* (volume 4, 423I)][fremlin_vol4]. Let `b = {s i}` be a countable basis for `α`. When `s i` and `s j` are disjoint, their images are disjoint analytic sets, hence by the separation theorem one can find a Borel-measurable set `q i j` separating them. Let `E i = closure (f '' s i) ∩ ⋂ j, q i j \ q j i`. It contains `f '' (s i)` and it is measurable. Let `F n = ⋃ E i`, where the union is taken over those `i` for which `diam (s i)` is bounded by some number `u n` tending to `0` with `n`. We claim that `range f = ⋂ F n`, from which the measurability is obvious. The inclusion `⊆` is straightforward. To show `⊇`, consider a point `x` in the intersection. For each `n`, it belongs to some `E i` with `diam (s i) ≤ u n`. Pick a point `y i ∈ s i`. We claim that for such `i` and `j`, the intersection `s i ∩ s j` is nonempty: if it were empty, then thanks to the separating set `q i j` in the definition of `E i` one could not have `x ∈ E i ∩ E j`. Since these two sets have small diameter, it follows that `y i` and `y j` are close. Thus, `y` is a Cauchy sequence, converging to a limit `z`. We claim that `f z = x`, completing the proof. Otherwise, one could find open sets `v` and `w` separating `f z` from `x`. Then, for large `n`, the image `f '' (s i)` would be included in `v` by continuity of `f`, so its closure would be contained in the closure of `v`, and therefore it would be disjoint from `w`. This is a contradiction since `x` belongs both to this closure and to `w`. -/ letI := upgrade_polish_space γ, obtain ⟨b, b_count, b_nonempty, hb⟩ : ∃ b : set (set γ), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := exists_countable_basis γ, haveI : encodable b := b_count.to_encodable, let A := {p : b × b // disjoint (p.1 : set γ) p.2}, -- for each pair of disjoint sets in the topological basis `b`, consider Borel sets separating -- their images, by injectivity of `f` and the Lusin separation theorem. have : ∀ (p : A), ∃ (q : set β), f '' (p.1.1 : set γ) ⊆ q ∧ disjoint (f '' (p.1.2 : set γ)) q ∧ measurable_set q, { assume p, apply analytic_set.measurably_separable ((hb.is_open p.1.1.2).analytic_set_image f_cont) ((hb.is_open p.1.2.2).analytic_set_image f_cont), exact disjoint.image p.2 (f_inj.inj_on univ) (subset_univ _) (subset_univ _) }, choose q hq1 hq2 q_meas using this, -- define sets `E i` and `F n` as in the proof sketch above let E : b → set β := λ s, closure (f '' s) ∩ (⋂ (t : b) (ht : disjoint s.1 t.1), q ⟨(s, t), ht⟩ \ q ⟨(t, s), ht.symm⟩), obtain ⟨u, u_anti, u_pos, u_lim⟩ : ∃ (u : ℕ → ℝ), strict_anti u ∧ (∀ (n : ℕ), 0 < u n) ∧ tendsto u at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), let F : ℕ → set β := λ n, ⋃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), E s, -- it is enough to show that `range f = ⋂ F n`, as the latter set is obviously measurable. suffices : range f = ⋂ n, F n, { have E_meas : ∀ (s : b), measurable_set (E s), { assume b, refine is_closed_closure.measurable_set.inter _, refine measurable_set.Inter (λ s, _), exact measurable_set.Inter_Prop (λ hs, (q_meas _).diff (q_meas _)) }, have F_meas : ∀ n, measurable_set (F n), { assume n, refine measurable_set.Union (λ s, _), exact measurable_set.Union_Prop (λ hs, E_meas _) }, rw this, exact measurable_set.Inter (λ n, F_meas n) }, -- we check both inclusions. apply subset.antisymm, -- we start with the easy inclusion `range f ⊆ ⋂ F n`. One just needs to unfold the definitions. { rintros x ⟨y, rfl⟩, apply mem_Inter.2 (λ n, _), obtain ⟨s, sb, ys, hs⟩ : ∃ (s : set γ) (H : s ∈ b), y ∈ s ∧ s ⊆ ball y (u n / 2), { apply hb.mem_nhds_iff.1, exact ball_mem_nhds _ (half_pos (u_pos n)) }, have diam_s : diam s ≤ u n, { apply (diam_mono hs bounded_ball).trans, convert diam_ball (half_pos (u_pos n)).le, ring }, refine mem_Union.2 ⟨⟨s, sb⟩, _⟩, refine mem_Union.2 ⟨⟨metric.bounded.mono hs bounded_ball, diam_s⟩, _⟩, apply mem_inter (subset_closure (mem_image_of_mem _ ys)), refine mem_Inter.2 (λ t, mem_Inter.2 (λ ht, ⟨_, _⟩)), { apply hq1, exact mem_image_of_mem _ ys }, { apply disjoint_left.1 (hq2 ⟨(t, ⟨s, sb⟩), ht.symm⟩), exact mem_image_of_mem _ ys } }, -- Now, let us prove the harder inclusion `⋂ F n ⊆ range f`. { assume x hx, -- pick for each `n` a good set `s n` of small diameter for which `x ∈ E (s n)`. have C1 : ∀ n, ∃ (s : b) (hs : bounded s.1 ∧ diam s.1 ≤ u n), x ∈ E s := λ n, by simpa only [mem_Union] using mem_Inter.1 hx n, choose s hs hxs using C1, have C2 : ∀ n, (s n).1.nonempty, { assume n, rw ← ne_empty_iff_nonempty, assume hn, have := (s n).2, rw hn at this, exact b_nonempty this }, -- choose a point `y n ∈ s n`. choose y hy using C2, have I : ∀ m n, ((s m).1 ∩ (s n).1).nonempty, { assume m n, rw ← not_disjoint_iff_nonempty_inter, by_contra' h, have A : x ∈ q ⟨(s m, s n), h⟩ \ q ⟨(s n, s m), h.symm⟩, { have := mem_Inter.1 (hxs m).2 (s n), exact (mem_Inter.1 this h : _) }, have B : x ∈ q ⟨(s n, s m), h.symm⟩ \ q ⟨(s m, s n), h⟩, { have := mem_Inter.1 (hxs n).2 (s m), exact (mem_Inter.1 this h.symm : _) }, exact A.2 B.1 }, -- the points `y n` are nearby, and therefore they form a Cauchy sequence. have cauchy_y : cauchy_seq y, { have : tendsto (λ n, 2 * u n) at_top (𝓝 0), by simpa only [mul_zero] using u_lim.const_mul 2, apply cauchy_seq_of_le_tendsto_0' (λ n, 2 * u n) (λ m n hmn, _) this, rcases I m n with ⟨z, zsm, zsn⟩, calc dist (y m) (y n) ≤ dist (y m) z + dist z (y n) : dist_triangle _ _ _ ... ≤ u m + u n : add_le_add ((dist_le_diam_of_mem (hs m).1 (hy m) zsm).trans (hs m).2) ((dist_le_diam_of_mem (hs n).1 zsn (hy n)).trans (hs n).2) ... ≤ 2 * u m : by linarith [u_anti.antitone hmn] }, haveI : nonempty γ := ⟨y 0⟩, -- let `z` be its limit. let z := lim at_top y, have y_lim : tendsto y at_top (𝓝 z) := cauchy_y.tendsto_lim, suffices : f z = x, by { rw ← this, exact mem_range_self _ }, -- assume for a contradiction that `f z ≠ x`. by_contra' hne, -- introduce disjoint open sets `v` and `w` separating `f z` from `x`. obtain ⟨v, w, v_open, w_open, fzv, xw, hvw⟩ : ∃ v w : set β, is_open v ∧ is_open w ∧ f z ∈ v ∧ x ∈ w ∧ v ∩ w = ∅ := t2_separation hne, obtain ⟨δ, δpos, hδ⟩ : ∃ δ > (0 : ℝ), ball z δ ⊆ f ⁻¹' v, { apply metric.mem_nhds_iff.1, exact f_cont.continuous_at.preimage_mem_nhds (v_open.mem_nhds fzv) }, obtain ⟨n, hn⟩ : ∃ n, u n + dist (y n) z < δ, { have : tendsto (λ n, u n + dist (y n) z) at_top (𝓝 0), by simpa only [add_zero] using u_lim.add (tendsto_iff_dist_tendsto_zero.1 y_lim), exact ((tendsto_order.1 this).2 _ δpos).exists }, -- for large enough `n`, the image of `s n` is contained in `v`, by continuity of `f`. have fsnv : f '' (s n) ⊆ v, { rw image_subset_iff, apply subset.trans _ hδ, assume a ha, calc dist a z ≤ dist a (y n) + dist (y n) z : dist_triangle _ _ _ ... ≤ u n + dist (y n) z : add_le_add_right ((dist_le_diam_of_mem (hs n).1 ha (hy n)).trans (hs n).2) _ ... < δ : hn }, -- as `x` belongs to the closure of `f '' (s n)`, it belongs to the closure of `v`. have : x ∈ closure v := closure_mono fsnv (hxs n).1, -- this is a contradiction, as `x` is supposed to belong to `w`, which is disjoint from -- the closure of `v`. exact disjoint_left.1 ((disjoint_iff_inter_eq_empty.2 hvw).closure_left w_open) this xw } end theorem _root_.is_closed.measurable_set_image_of_continuous_on_inj_on {β : Type*} [topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} (hs : is_closed s) {f : γ → β} (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin rw image_eq_range, haveI : polish_space s := is_closed.polish_space hs, apply measurable_set_range_of_continuous_injective, { rwa continuous_on_iff_continuous_restrict at f_cont }, { rwa inj_on_iff_injective at f_inj } end variables [measurable_space γ] [borel_space γ] {β : Type*} [tβ : topological_space β] [t2_space β] [measurable_space β] [borel_space β] {s : set γ} {f : γ → β} include tβ /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a continuous injective map is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_continuous_on_inj_on (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_set (f '' s) := begin obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs.is_clopenable, exact @is_closed.measurable_set_image_of_continuous_on_inj_on γ t' t'_polish β _ _ _ _ s s_closed f (f_cont.mono_dom t't) f_inj, end /-- The Lusin-Souslin theorem: if `s` is Borel-measurable in a Polish space, then its image under a measurable injective map taking values in a second-countable topological space is also Borel-measurable. -/ theorem _root_.measurable_set.image_of_measurable_inj_on [second_countable_topology β] (hs : measurable_set s) (f_meas : measurable f) (f_inj : inj_on f s) : measurable_set (f '' s) := begin -- for a finer Polish topology, `f` is continuous. Therefore, one may apply the corresponding -- result for continuous maps. obtain ⟨t', t't, f_cont, t'_polish⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @continuous γ β t' tβ f ∧ @polish_space γ t' := f_meas.exists_continuous, have M : measurable_set[@borel γ t'] s := @continuous.measurable γ γ t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) tγ _ _ _ (continuous_id_of_le t't) s hs, exact @measurable_set.image_of_continuous_on_inj_on γ t' t'_polish (@borel γ t') (by { constructor, refl }) β _ _ _ _ s f M (@continuous.continuous_on γ β t' tβ f s f_cont) f_inj, end /-- An injective continuous function on a Polish space is a measurable embedding. -/ theorem _root_.continuous.measurable_embedding (f_cont : continuous f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_cont.measurable, measurable_set_image' := λ u hu, hu.image_of_continuous_on_inj_on f_cont.continuous_on (f_inj.inj_on _) } /-- If `s` is Borel-measurable in a Polish space and `f` is continuous injective on `s`, then the restriction of `f` to `s` is a measurable embedding. -/ theorem _root_.continuous_on.measurable_embedding (hs : measurable_set s) (f_cont : continuous_on f s) (f_inj : inj_on f s) : measurable_embedding (s.restrict f) := { injective := inj_on_iff_injective.1 f_inj, measurable := (continuous_on_iff_continuous_restrict.1 f_cont).measurable, measurable_set_image' := begin assume u hu, have A : measurable_set ((coe : s → γ) '' u) := (measurable_embedding.subtype_coe hs).measurable_set_image.2 hu, have B : measurable_set (f '' ((coe : s → γ) '' u)) := A.image_of_continuous_on_inj_on (f_cont.mono (subtype.coe_image_subset s u)) (f_inj.mono ((subtype.coe_image_subset s u))), rwa ← image_comp at B, end } /-- An injective measurable function from a Polish space to a second-countable topological space is a measurable embedding. -/ theorem _root_.measurable.measurable_embedding [second_countable_topology β] (f_meas : measurable f) (f_inj : injective f) : measurable_embedding f := { injective := f_inj, measurable := f_meas, measurable_set_image' := λ u hu, hu.image_of_measurable_inj_on f_meas (f_inj.inj_on _) } omit tβ /-- In a Polish space, a set is clopenable if and only if it is Borel-measurable. -/ lemma is_clopenable_iff_measurable_set : is_clopenable s ↔ measurable_set s := begin -- we already know that a measurable set is clopenable. Conversely, assume that `s` is clopenable. refine ⟨λ hs, _, λ hs, hs.is_clopenable⟩, -- consider a finer topology `t'` in which `s` is open and closed. obtain ⟨t', t't, t'_polish, s_closed, s_open⟩ : ∃ (t' : topological_space γ), t' ≤ tγ ∧ @polish_space γ t' ∧ @is_closed γ t' s ∧ @is_open γ t' s := hs, -- the identity is continuous from `t'` to `tγ`. have C : @continuous γ γ t' tγ id := continuous_id_of_le t't, -- therefore, it is also a measurable embedding, by the Lusin-Souslin theorem have E := @continuous.measurable_embedding γ t' t'_polish (@borel γ t') (by { constructor, refl }) γ tγ (polish_space.t2_space γ) _ _ id C injective_id, -- the set `s` is measurable for `t'` as it is closed. have M : @measurable_set γ (@borel γ t') s := @is_closed.measurable_set γ s t' (@borel γ t') (@borel_space.opens_measurable γ t' (@borel γ t') (by { constructor, refl })) s_closed, -- therefore, its image under the measurable embedding `id` is also measurable for `tγ`. convert E.measurable_set_image.2 M, simp only [id.def, image_id'], end end measure_theory
2e1ac347dd7a0f25a4ac4f5c78e864a8a61af974
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/induction_generalize_premise_args.lean
20c6a0f6f08521cd2662454aaaa0a21bccc6f298
[ "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
577
lean
namespace semantics inductive com | seq (c₁ c₂ : com) constant state : Type inductive smallstep : com × state → com × state → Prop | seq1 (c₁ c₂ σ c₁' σ') : smallstep ⟨c₁, σ⟩ ⟨c₂, σ'⟩ → smallstep ⟨com.seq c₁ c₂, σ⟩ ⟨com.seq c₁' c₂, σ'⟩ lemma deterministic_aux (c σ c'₁ c'₂ σ'₁ σ'₂) (h₁ : smallstep ⟨c, σ⟩ ⟨c'₁, σ'₁⟩) (h₂ : smallstep ⟨c, σ⟩ ⟨c'₂, σ'₂⟩) : (c'₁, σ'₁) = (c'₂, σ'₂) := begin induction h₁ generalizing c'₂ σ'₂, end end semantics
11f330d902cc5df1e07f62c7b953c152b3291747
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/linear_algebra/tensor_product.lean
a0cddef31cdd8b61194f051c439efe2151c406ed
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
19,681
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro Tensor product of modules over commutative rings. -/ import group_theory.free_abelian_group import linear_algebra.direct_sum_module variables {R : Type*} [comm_ring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] include R namespace linear_map variables (R) def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ N →ₗ P := ⟨λ m, ⟨f m, H3 m, λ c, H4 c m⟩, λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, λ c m, linear_map.ext $ H2 c m⟩ variables {R} @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ P) m n = f m n := rfl theorem ext₂ {f g : M →ₗ[R] N →ₗ[R] P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₗ[R] N →ₗ[R] P) : N →ₗ M →ₗ P := mk₂ R (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) variable (f : M →ₗ[R] N →ₗ[R] P) @[simp] theorem flip_apply (m : M) (n : N) : flip f n m = f m n := rfl variables {R} theorem flip_inj {f g : M →ₗ[R] N →ₗ P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H variables (R M N P) def lflip : (M →ₗ[R] N →ₗ P) →ₗ[R] N →ₗ M →ₗ P := ⟨flip, λ _ _, rfl, λ _ _, rfl⟩ variables {R M N P} @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl theorem map_zero₂ (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_add₂ (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (r:R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ variables (R P) def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P := flip $ linear_map.comp (flip id) f variables {R P} @[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) : lcomp R P f g x = g (f x) := rfl variables (R M N P) def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P := flip ⟨lcomp R P, λ f f', ext₂ $ λ g x, g.map_add _ _, λ c f, ext₂ $ λ g x, g.map_smul _ _⟩ variables {R M N P} section @[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) : llcomp R M N P f g x = f (g x) := rfl end def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q := linear_map.comp (llcomp R N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) def lsmul : R →ₗ M →ₗ M := mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end linear_map variables (M N) namespace tensor_product section open free_abelian_group variables (R) def relators : set (free_abelian_group (M × N)) := add_group.closure { x : free_abelian_group (M × N) | (∃ (m₁ m₂ : M) (n : N), x = of (m₁, n) + of (m₂, n) - of (m₁ + m₂, n)) ∨ (∃ (m : M) (n₁ n₂ : N), x = of (m, n₁) + of (m, n₂) - of (m, n₁ + n₂)) ∨ (∃ (r : R) (m : M) (n : N), x = of (r • m, n) - of (m, r • n)) } end namespace relators instance : normal_add_subgroup (relators R M N) := by unfold relators; apply normal_add_subgroup_of_add_comm_group end relators end tensor_product variables (R) def tensor_product : Type* := quotient_add_group.quotient (tensor_product.relators R M N) variables {R} localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product localized "notation M ` ⊗[`:100 R `] ` N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup instance : add_comm_group (M ⊗[R] N) := quotient_add_group.add_comm_group _ instance : inhabited (M ⊗[R] N) := ⟨0⟩ instance quotient.mk.is_add_group_hom : is_add_group_hom (quotient.mk : free_abelian_group (M × N) → M ⊗ N) := quotient_add_group.is_add_group_hom _ variables (R) {M N} def tmul (m : M) (n : N) : M ⊗[R] N := quotient_add_group.mk $ free_abelian_group.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] ` y := tmul R x y lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $ add_group.in_closure.basic $ or.inl $ ⟨m₁, m₂, n, rfl⟩ lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ sub_eq_zero.1 $ eq.symm $ quotient.sound $ add_group.in_closure.basic $ or.inr $ or.inl $ ⟨m, n₁, n₂, rfl⟩ lemma smul_tmul (r : R) (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := sub_eq_zero.1 $ eq.symm $ quotient.sound $ add_group.in_closure.basic $ or.inr $ or.inr $ ⟨r, m, n, rfl⟩ local attribute [instance] quotient_add_group.is_add_group_hom_quotient_lift def smul.aux (r : R) : free_abelian_group (M × N) → M ⊗[R] N := free_abelian_group.lift (λ (y : M × N), (r • y.1) ⊗ₜ y.2) instance (r : R) : is_add_group_hom (smul.aux r : _ → M ⊗ N) := by unfold smul.aux; apply_instance instance : has_scalar R (M ⊗ N) := ⟨λ r, quotient_add_group.lift _ (smul.aux r) $ λ x hx, begin refine (is_add_group_hom.mem_ker (smul.aux r : _ → M ⊗ N)).1 (add_group.closure_subset _ hx), clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩); simp only [smul.aux, is_add_group_hom.mem_ker, -sub_eq_add_neg, sub_self, add_tmul, tmul_add, smul_tmul, smul_add, smul_smul, mul_comm, free_abelian_group.lift.of, free_abelian_group.lift.add, free_abelian_group.lift.sub] end⟩ instance smul.is_add_group_hom (r : R) : is_add_group_hom ((•) r : M ⊗[R] N → M ⊗[R] N) := by unfold has_scalar.smul; apply_instance protected theorem smul_add (r : R) (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := is_add_hom.map_add _ _ _ instance : semimodule R (M ⊗ N) := semimodule.of_core { smul := (•), smul_add := tensor_product.smul_add, add_smul := begin intros r s x, apply quotient_add_group.induction_on' x, intro z, symmetry, refine @free_abelian_group.lift.unique _ _ _ _ _ (is_add_group_hom.mk' $ λ p q, _) _ z, { simp [tensor_product.smul_add, add_comm, add_left_comm] }, rintro ⟨m, n⟩, change (r • m) ⊗ₜ n + (s • m) ⊗ₜ n = ((r + s) • m) ⊗ₜ n, rw [add_smul, add_tmul] end, mul_smul := begin intros r s x, apply quotient_add_group.induction_on' x, intro z, symmetry, refine @free_abelian_group.lift.unique _ _ _ _ _ (is_add_group_hom.mk' $ λ p q, _) _ z, { simp [tensor_product.smul_add] }, rintro ⟨m, n⟩, change r • s • (m ⊗ₜ n) = ((r * s) • m) ⊗ₜ n, rw mul_smul, refl end, one_smul := λ x, quotient.induction_on x $ λ _, eq.symm $ free_abelian_group.lift.unique _ _ $ λ ⟨p, q⟩, by rw one_smul; refl } @[simp] lemma tmul_smul (r : R) (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm variables (R M N) def mk : M →ₗ N →ₗ M ⊗ N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl @[simp] lemma zero_tmul (n : N) : (0 ⊗ₜ[R] n : M ⊗ N) = 0 := (mk R M N).map_zero₂ _ @[simp] lemma tmul_zero (m : M) : (m ⊗ₜ[R] 0 : M ⊗ N) = 0 := (mk R M N _).map_zero lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := (mk R M N).map_neg₂ _ _ lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : ((if P then x₁ else 0) ⊗ₜ[R] x₂) = if P then (x₁ ⊗ₜ x₂) else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (x₁ ⊗ₜ[R] (if P then x₂ else 0)) = if P then (x₁ ⊗ₜ x₂) else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : ((∑ a in s, m a) ⊗ₜ[R] n) = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : (m ⊗ₜ[R] (∑ a in s, n a)) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end end module local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ x y, C $ x ⊗ₜ[R] y) (Cp : ∀ x y, C x → C y → C (x + y)) : C z := quotient.induction_on z $ λ x, free_abelian_group.induction_on x C0 (λ ⟨p, q⟩, C1 p q) (λ ⟨p, q⟩ _, show C (-(p ⊗ₜ q)), by rw ← neg_tmul; from C1 (-p) q) (λ _ _, Cp _ _) section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) local attribute [instance] free_abelian_group.lift.is_add_group_hom def lift_aux : (M ⊗[R] N) → P := quotient_add_group.lift _ (free_abelian_group.lift $ λ z, f z.1 z.2) $ λ x hx, begin refine (is_add_group_hom.mem_ker _).1 (add_group.closure_subset _ hx), clear hx x, rintro x (⟨m₁, m₂, n, rfl⟩ | ⟨m, n₁, n₂, rfl⟩ | ⟨q, m, n, rfl⟩); simp [is_add_group_hom.mem_ker, -sub_eq_add_neg, f.map_add, f.map_add₂, f.map_smul, f.map_smul₂, sub_self], end variable {f} local attribute [instance] quotient_add_group.left_rel normal_add_subgroup.to_is_add_subgroup @[simp] lemma lift_aux.add (x y) : lift_aux f (x + y) = lift_aux f x + lift_aux f y := quotient.induction_on₂ x y $ λ m n, free_abelian_group.lift.add _ _ _ @[simp] lemma lift_aux.smul (r:R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on _ _ x (smul_zero _).symm (λ p q, by rw [← tmul_smul]; simp [lift_aux, tmul]) (λ p q ih1 ih2, by simp [@smul_add _ _ _ _ _ _ p _, lift_aux.add, ih1, ih2, smul_add]) variable (f) def lift : M ⊗ N →ₗ P := { to_fun := lift_aux f, map_add' := lift_aux.add, map_smul' := lift_aux.smul } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := linear_map.ext $ λ z, begin apply quotient_add_group.induction_on' z, intro z, refine @free_abelian_group.lift.unique _ _ _ _ _ (is_add_group_hom.mk' $ λ p q, _) _ z, { simp [g.2] }, exact λ ⟨m, n⟩, H m n end theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂, lift_mk, linear_map.comp_id] @[ext] theorem ext {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := by rw ← lift_mk_compr₂ h; exact lift.unique H theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext $ λ m n, lift.tmul _ _, .. uncurry R M N P } def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin let e := linear_equiv.to_equiv (lift.equiv R (M ⊗[R] N) P Q), apply e.symm.injective, refine ext _, intros x y, ext z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin let e := linear_equiv.to_equiv (lift.equiv R ((M ⊗[R] N) ⊗[R] P) Q S), apply e.symm.injective, refine ext_threefold _, intros x y z, ext w, exact H x y z w, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext $ λ m n, rfl) (ext $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : ((tensor_product.comm R M N) : (M ⊗ N → N ⊗ M)) (m ⊗ₜ n) = n ⊗ₜ m := begin dsimp [tensor_product.comm], simp, end end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : ((tensor_product.rid R M) : (M ⊗ R → M)) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _) (mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : ((tensor_product.assoc R M N P) : (M ⊗[R] N) ⊗[R] P → M ⊗[R] (N ⊗[R] P)) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl /-- If M and P are linearly equivalent and N and Q are linearly equivalent then M ⊗ N and P ⊗ Q are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl variables (R) (ι₁ : Type*) (ι₂ : Type*) variables [decidable_eq ι₁] [decidable_eq ι₂] variables (M₁ : ι₁ → Type*) (M₂ : ι₂ → Type*) variables [Π i₁, add_comm_group (M₁ i₁)] [Π i₂, add_comm_group (M₂ i₂)] variables [Π i₁, module R (M₁ i₁)] [Π i₂, module R (M₂ i₂)] def direct_sum : direct_sum ι₁ M₁ ⊗[R] direct_sum ι₂ M₂ ≃ₗ[R] direct_sum (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) := begin refine linear_equiv.of_linear (lift $ direct_sum.to_module R _ _ $ λ i₁, flip $ direct_sum.to_module R _ _ $ λ i₂, flip $ curry $ direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂)) (direct_sum.to_module R _ _ $ λ i, map (direct_sum.lof R _ _ _) (direct_sum.lof R _ _ _)) (linear_map.ext $ direct_sum.to_module.ext _ $ λ i, mk_compr₂_inj $ linear_map.ext $ λ x₁, linear_map.ext $ λ x₂, _) (mk_compr₂_inj $ linear_map.ext $ direct_sum.to_module.ext _ $ λ i₁, linear_map.ext $ λ x₁, linear_map.ext $ direct_sum.to_module.ext _ $ λ i₂, linear_map.ext $ λ x₂, _); repeat { rw compr₂_apply <|> rw comp_apply <|> rw id_apply <|> rw mk_apply <|> rw direct_sum.to_module_lof <|> rw map_tmul <|> rw lift.tmul <|> rw flip_apply <|> rw curry_apply }, cases i; refl end @[simp] theorem direct_sum_lof_tmul_lof (i₁ : ι₁) (m₁ : M₁ i₁) (i₂ : ι₂) (m₂ : M₂ i₂) : direct_sum R ι₁ ι₂ M₁ M₂ (direct_sum.lof R ι₁ M₁ i₁ m₁ ⊗ₜ direct_sum.lof R ι₂ M₂ i₂ m₂) = direct_sum.lof R (ι₁ × ι₂) (λ i, M₁ i.1 ⊗[R] M₂ i.2) (i₁, i₂) (m₁ ⊗ₜ m₂) := by simp [direct_sum] end tensor_product
20bb16a7e8ff03f5001f2e3dd45a4db77cd17550
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/equiv/fintype.lean
253760caf46125fbb64f35cf82183aae3cbc65bc
[ "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
5,402
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import data.set.finite import group_theory.perm.sign import logic.equiv.basic /-! # Equivalence between fintypes This file contains some basic results on equivalences where one or both sides of the equivalence are `fintype`s. # Main definitions - `function.embedding.to_equiv_range`: computably turn an embedding of a fintype into an `equiv` of the domain to its range - `equiv.perm.via_fintype_embedding : perm α → (α ↪ β) → perm β` extends the domain of a permutation, fixing everything outside the range of the embedding # Implementation details - `function.embedding.to_equiv_range` uses a computable inverse, but one that has poor computational performance, since it operates by exhaustive search over the input `fintype`s. -/ variables {α β : Type*} [fintype α] [decidable_eq β] (e : equiv.perm α) (f : α ↪ β) /-- Computably turn an embedding `f : α ↪ β` into an equiv `α ≃ set.range f`, if `α` is a `fintype`. Has poor computational performance, due to exhaustive searching in constructed inverse. When a better inverse is known, use `equiv.of_left_inverse'` or `equiv.of_left_inverse` instead. This is the computable version of `equiv.of_injective`. -/ def function.embedding.to_equiv_range : α ≃ set.range f := ⟨λ a, ⟨f a, set.mem_range_self a⟩, f.inv_of_mem_range, λ _, by simp, λ _, by simp⟩ @[simp] lemma function.embedding.to_equiv_range_apply (a : α) : f.to_equiv_range a = ⟨f a, set.mem_range_self a⟩ := rfl @[simp] lemma function.embedding.to_equiv_range_symm_apply_self (a : α) : f.to_equiv_range.symm ⟨f a, set.mem_range_self a⟩ = a := by simp [equiv.symm_apply_eq] lemma function.embedding.to_equiv_range_eq_of_injective : f.to_equiv_range = equiv.of_injective f f.injective := by { ext, simp } /-- Extend the domain of `e : equiv.perm α`, mapping it through `f : α ↪ β`. Everything outside of `set.range f` is kept fixed. Has poor computational performance, due to exhaustive searching in constructed inverse due to using `function.embedding.to_equiv_range`. When a better `α ≃ set.range f` is known, use `equiv.perm.via_set_range`. When `[fintype α]` is not available, a noncomputable version is available as `equiv.perm.via_embedding`. -/ def equiv.perm.via_fintype_embedding : equiv.perm β := e.extend_domain f.to_equiv_range @[simp] lemma equiv.perm.via_fintype_embedding_apply_image (a : α) : e.via_fintype_embedding f (f a) = f (e a) := begin rw equiv.perm.via_fintype_embedding, convert equiv.perm.extend_domain_apply_image e _ _ end lemma equiv.perm.via_fintype_embedding_apply_mem_range {b : β} (h : b ∈ set.range f) : e.via_fintype_embedding f b = f (e (f.inv_of_mem_range ⟨b, h⟩)) := by simpa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_subtype, h] lemma equiv.perm.via_fintype_embedding_apply_not_mem_range {b : β} (h : b ∉ set.range f) : e.via_fintype_embedding f b = b := by rwa [equiv.perm.via_fintype_embedding, equiv.perm.extend_domain_apply_not_subtype] @[simp] lemma equiv.perm.via_fintype_embedding_sign [decidable_eq α] [fintype β] : equiv.perm.sign (e.via_fintype_embedding f) = equiv.perm.sign e := by simp [equiv.perm.via_fintype_embedding] namespace equiv variables {p q : α → Prop} [decidable_pred p] [decidable_pred q] /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.to_compl` is an equivalence between the complement of those subtypes. See also `equiv.compl`, for a computable version when a term of type `{e' : α ≃ α // ∀ x : {x // p x}, e' x = e x}` is known. -/ noncomputable def to_compl (e : {x // p x} ≃ {x // q x}) : {x // ¬ p x} ≃ {x // ¬ q x} := classical.choice (fintype.card_eq.mp (fintype.card_compl_eq_card_compl (fintype.card_congr e))) /-- If `e` is an equivalence between two subtypes of a fintype `α`, `e.extend_subtype` is a permutation of `α` acting like `e` on the subtypes and doing something arbitrary outside. Note that when `p = q`, `equiv.perm.subtype_congr e (equiv.refl _)` can be used instead. -/ noncomputable abbreviation extend_subtype (e : {x // p x} ≃ {x // q x}) : perm α := subtype_congr e e.to_compl lemma extend_subtype_apply_of_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : e.extend_subtype x = e ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_pos _ _ hx, sum.map_inl, sum_compl_apply_inl] } lemma extend_subtype_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : p x) : q (e.extend_subtype x) := by { convert (e ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_mem _ hx, subtype.val_eq_coe] } lemma extend_subtype_apply_of_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : e.extend_subtype x = e.to_compl ⟨x, hx⟩ := by { dunfold extend_subtype, simp only [subtype_congr, equiv.trans_apply, equiv.sum_congr_apply], rw [sum_compl_apply_symm_of_neg _ _ hx, sum.map_inr, sum_compl_apply_inr] } lemma extend_subtype_not_mem (e : {x // p x} ≃ {x // q x}) (x) (hx : ¬ p x) : ¬ q (e.extend_subtype x) := by { convert (e.to_compl ⟨x, hx⟩).2, rw [e.extend_subtype_apply_of_not_mem _ hx, subtype.val_eq_coe] } end equiv
2d83a664b8ad596cff68ed6f4e104090bda1448d
367134ba5a65885e863bdc4507601606690974c1
/test/lint.lean
798328351b47c4d953f6a92b344b994ccc0329b5
[ "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
4,563
lean
import tactic.lint import algebra.ring.basic def foo1 (n m : ℕ) : ℕ := n + 1 def foo2 (n m : ℕ) : m = m := by refl lemma foo3 (n m : ℕ) : ℕ := n - m lemma foo.foo (n m : ℕ) : n ≥ n := le_refl n instance bar.bar : has_add ℕ := by apply_instance -- we don't check the name of instances lemma foo.bar (ε > 0) : ε = ε := rfl -- >/≥ is allowed in binders (and in fact, in all hypotheses) -- section -- local attribute [instance, priority 1001] classical.prop_decidable -- lemma foo4 : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) -- end open tactic meta def fold_over_with_cond {α} (l : list declaration) (tac : declaration → tactic (option α)) : tactic (list (declaration × α)) := l.mmap_filter $ λ d, option.map (λ x, (d, x)) <$> tac d run_cmd do let t := name × list ℕ, e ← get_env, let l := e.filter (λ d, e.in_current_file d.to_name ∧ ¬ d.is_auto_or_internal e), l2 ← fold_over_with_cond l (return ∘ check_unused_arguments), guard $ l2.length = 4, let l2 : list t := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ (⟨`foo1, [2]⟩ : t) ∈ l2, guard $ (⟨`foo2, [1]⟩ : t) ∈ l2, guard $ (⟨`foo.foo, [2]⟩ : t) ∈ l2, guard $ (⟨`foo.bar, [2]⟩ : t) ∈ l2, l2 ← fold_over_with_cond l linter.def_lemma.test, guard $ l2.length = 2, let l2 : list (name × _) := l2.map $ λ x, ⟨x.1.to_name, x.2⟩, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo2, guard $ ∃(x ∈ l2), (x : name × _).1 = `foo3, l3 ← fold_over_with_cond l linter.dup_namespace.test, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l linter.ge_or_gt.test, guard $ l4.length = 1, guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo.foo, -- guard $ ∃(x ∈ l4), (x : declaration × _).1.to_name = `foo4, (_, s) ← lint ff, guard $ "/- (slow tests skipped) -/\n".is_suffix_of s.to_string, (_, s2) ← lint tt, guard $ s.to_string ≠ s2.to_string, skip /- check customizability and nolint -/ meta def dummy_check (d : declaration) : tactic (option string) := return $ if d.to_name.last = "foo" then some "gotcha!" else none meta def linter.dummy_linter : linter := { test := dummy_check, auto_decls := ff, no_errors_found := "found nothing", errors_found := "found something" } @[nolint dummy_linter] def bar.foo : (if 3 = 3 then 1 else 2) = 1 := if_pos (by refl) run_cmd do (_, s) ← lint tt lint_verbosity.medium [`linter.dummy_linter] tt, guard $ "/- found something: -/\n#print foo.foo /- gotcha! -/\n".is_suffix_of s.to_string def incorrect_type_class_argument_test {α : Type} (x : α) [x = x] [decidable_eq α] [group α] : unit := () run_cmd do d ← get_decl `incorrect_type_class_argument_test, x ← linter.incorrect_type_class_argument.test d, guard $ x = some "These are not classes. argument 3: [_inst_1 : x = x]" section def impossible_instance_test {α β : Type} [add_group α] : has_add α := infer_instance local attribute [instance] impossible_instance_test run_cmd do d ← get_decl `impossible_instance_test, x ← linter.impossible_instance.test d, guard $ x = some "Impossible to infer argument 2: {β : Type}" def dangerous_instance_test {α β γ : Type} [ring α] [add_comm_group β] [has_coe α β] [has_inv γ] : has_add β := infer_instance local attribute [instance] dangerous_instance_test run_cmd do d ← get_decl `dangerous_instance_test, x ← linter.dangerous_instance.test d, guard $ x = some "The following arguments become metavariables. argument 1: {α : Type}, argument 3: {γ : Type}" end section def foo_has_mul {α} [has_mul α] : has_mul α := infer_instance local attribute [instance, priority 1] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 20 d, guard $ s = "type-class inference timed out" local attribute [instance, priority 10000] foo_has_mul run_cmd do d ← get_decl `has_mul, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end instance beta_redex_test {α} [monoid α] : (λ (X : Type), has_mul X) α := ⟨(*)⟩ run_cmd do d ← get_decl `beta_redex_test, x ← linter.instance_priority.test d, guard $ x = some "set priority below 1000" /- test of `apply_to_fresh_variables` -/ run_cmd do e ← mk_const `id, e2 ← apply_to_fresh_variables e, type_check e2, `(@id %%α %%a) ← instantiate_mvars e2, expr.sort (level.succ $ level.mvar u) ← infer_type α, skip
691dc91e358ae47aefd808eda3080f5145bd8f6a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/analysis/inner_product_space/basic.lean
229bf666872152fb3cae185e239e1e881c7f88dc
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
79,128
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.normed_space.bounded_linear_maps import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form /-! # Inner product space This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the pair of assumptions `[inner_product_space E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`. - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. - The `orthogonal_complement` of a submodule `K` is defined, and basic API established. Some of the more subtle results about the orthogonal complement are delayed to `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators classical topological_space complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_aut /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_equiv.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_equiv.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_equiv.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_equiv.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_equiv.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, ring_equiv.map_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_sq (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_sq], ring, }, rw H, conv begin to_lhs, congr, rw[inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_sq, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := has_abs.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := star_ring_aut export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_sym ℝ _ _ _ x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_equiv.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_equiv.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ @[simps] def sesq_form_of_inner : sesq_form 𝕜 E (conj_to_ring_equiv 𝕜) := { sesq := λ x y, ⟪y, x⟫, -- Note that sesquilinear forms are linear in the first argument sesq_add_left := λ x y z, inner_add_right, sesq_add_right := λ x y z, inner_add_left, sesq_smul_left := λ r x y, inner_smul_right, sesq_smul_right := λ r x y, inner_smul_left } /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := sesq_form.sum_right (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := sesq_form.sum_left (sesq_form_of_inner) _ _ _ /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_equiv.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_equiv.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw[←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_equiv.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw[←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul_eq_neg_mul_symm, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg_eq_neg_mul_symm, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, ring_equiv.map_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw [div_mul_eq_mul_div_comm, ←mul_div_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := by simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := by simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv] /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin rcases zorn.zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs with ⟨b, bi, sb, h⟩, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ∥v i∥ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw[norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_sq ℝ F _ _ x, simpa using h } /-- Expand the square -/ lemma norm_add_sq {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_sq]}, rw[inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_sq]}, rw[inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw[conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_sq], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ∥⟪x, y⟫∥ ≤ ∥x∥ * ∥y∥ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm {x y : E} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [← inner_self_eq_norm_sq], rw[← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end omit 𝕜 lemma parallelogram_law_with_norm_real {x y : F} : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := by { have h := @parallelogram_law_with_norm ℝ F _ _ x y, simpa using h } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end section variables {E' : Type*} [inner_product_space 𝕜 E'] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_sq, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ∥w - v∥ = ∥w + v∥ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp [h, ←inner_self_eq_norm_sq, inner_add_left, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_sq] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_sq] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_sq, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div_eq_div_mul, mul_div_cancel _ hx', ←div_div_eq_div_mul, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, ←neg_mul_eq_neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_sq, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_sq] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_sq, ←inner_self_eq_norm_sq ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], have : x ≠ 0 := λ h, (hx0' $ norm_eq_zero.mpr h), simp [this] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product with a fixed left element, as a continuous linear map. This can be upgraded to a continuous map which is jointly conjugate-linear in the left argument and linear in the right argument, once (TODO) conjugate-linear maps have been defined. -/ def inner_right (v : E) : E →L[𝕜] 𝕜 := linear_map.mk_continuous { to_fun := λ w, ⟪v, w⟫, map_add' := λ x y, inner_add_right, map_smul' := λ c x, inner_smul_right } ∥v∥ (by simpa using norm_inner_le_norm v) @[simp] lemma inner_right_coe (v : E) : (inner_right v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma inner_right_apply (v w : E) : inner_right v w = ⟪v, w⟫ := rfl /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]` and `[is_scalar_tower ℝ 𝕜 E]`. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` we have these instances. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ∥z∥ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ∥x - ∑ i in s, ⟪v i, x⟫ • (v i)∥ ^ 2 = ∥x∥ ^ 2 - ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ∥⟪v i, x⟫∥ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ∥x∥ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. -/ def orthogonal_family (V : ι → submodule 𝕜 E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ {v : E} (hv : v ∈ V i) {w : E} (hw : w ∈ V j), ⟪v, w⟫ = 0 variables {𝕜} {V : ι → submodule 𝕜 E} lemma orthogonal_family.eq_ite (hV : orthogonal_family 𝕜 V) {i j : ι} (v : V i) (w : V j) : ⟪(v:E), w⟫ = ite (i = j) ⟪(v:E), w⟫ 0 := begin split_ifs, { refl }, { exact hV h v.prop w.prop } end lemma orthogonal_family.inner_right_dfinsupp (hV : orthogonal_family 𝕜 V) (l : Π₀ i, V i) (i : ι) (v : V i) : ⟪(v : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) l⟫ = ⟪v, l i⟫ := calc ⟪(v : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) l⟫ = l.sum (λ j, λ w, ⟪(v:E), w⟫) : begin let F : E →+ 𝕜 := (@inner_right 𝕜 E _ _ v).to_linear_map.to_add_monoid_hom, have hF := congr_arg add_monoid_hom.to_fun (dfinsupp.comp_sum_add_hom F (λ j, (V j).subtype.to_add_monoid_hom)), convert congr_fun hF l using 1, simp only [dfinsupp.sum_add_hom_apply, continuous_linear_map.to_linear_map_eq_coe, add_monoid_hom.coe_comp, inner_right_coe, add_monoid_hom.to_fun_eq_coe, linear_map.to_add_monoid_hom_coe, continuous_linear_map.coe_coe], congr end ... = l.sum (λ j, λ w, ite (i=j) ⟪(v:E), w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun, not_not], intros h, simp [h] end lemma orthogonal_family.inner_right_fintype [fintype ι] (hV : orthogonal_family 𝕜 V) (l : Π i, V i) (i : ι) (v : V i) : ⟪(v : E), ∑ j : ι, l j⟫ = ⟪v, l i⟫ := calc ⟪(v : E), ∑ j : ι, l j⟫ = ∑ j : ι, ⟪(v : E), l j⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪(v : E), l j⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent (hV : orthogonal_family 𝕜 V) : complete_lattice.independent V := begin apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, have : ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ = 0, { simp [hv] }, simpa only [submodule.coe_zero, submodule.coe_eq_zero, direct_sum.zero_apply, inner_self_eq_zero, hV.inner_right_dfinsupp] using this, end end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, letI : is_scalar_tower ℝ 𝕜 E := restrict_scalars.is_scalar_tower _ _ _, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section orthogonal variables (K : submodule 𝕜 E) /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (inner_right (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (inner_right (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (order_dual $ submodule 𝕜 E) _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end end orthogonal