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
99c348fc8f1eddc77eb22acdf1f34f061047ddb7
7cef822f3b952965621309e88eadf618da0c8ae9
/src/computability/primrec.lean
ab5a5e86525ff4e9c89da3dfbd3ad85ef8c8cc27
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
50,156
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro The primitive recursive functions are the least collection of functions nat → nat which are closed under projections (using the mkpair pairing function), composition, zero, successor, and primitive recursion (i.e. nat.rec where the motive is C n := nat). We can extend this definition to a large class of basic types by using canonical encodings of types as natural numbers (Gödel numbering), which we implement through the type class `encodable`. (More precisely, we need that the composition of encode with decode yields a primitive recursive function, so we have the `primcodable` type class for this.) -/ import data.equiv.list open denumerable encodable namespace nat def elim {C : Sort*} : C → (ℕ → C → C) → ℕ → C := @nat.rec (λ _, C) @[simp] theorem elim_zero {C} (a f) : @nat.elim C a f 0 = a := rfl @[simp] theorem elim_succ {C} (a f n) : @nat.elim C a f (succ n) = f n (nat.elim a f n) := rfl def cases {C : Sort*} (a : C) (f : ℕ → C) : ℕ → C := nat.elim a (λ n _, f n) @[simp] theorem cases_zero {C} (a f) : @nat.cases C a f 0 = a := rfl @[simp] theorem cases_succ {C} (a f n) : @nat.cases C a f (succ n) = f n := rfl @[simp, reducible] def unpaired {α} (f : ℕ → ℕ → α) (n : ℕ) : α := f n.unpair.1 n.unpair.2 /-- The primitive recursive functions `ℕ → ℕ`. -/ inductive primrec : (ℕ → ℕ) → Prop | zero : primrec (λ n, 0) | succ : primrec succ | left : primrec (λ n, n.unpair.1) | right : primrec (λ n, n.unpair.2) | pair {f g} : primrec f → primrec g → primrec (λ n, mkpair (f n) (g n)) | comp {f g} : primrec f → primrec g → primrec (λ n, f (g n)) | prec {f g} : primrec f → primrec g → primrec (unpaired (λ z n, n.elim (f z) (λ y IH, g $ mkpair z $ mkpair y IH))) namespace primrec theorem of_eq {f g : ℕ → ℕ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const : ∀ (n : ℕ), primrec (λ _, n) | 0 := zero | (n+1) := succ.comp (const n) protected theorem id : primrec id := (left.pair right).of_eq $ λ n, by simp theorem prec1 {f} (m : ℕ) (hf : primrec f) : primrec (λ n, n.elim m (λ y IH, f $ mkpair y IH)) := ((prec (const m) (hf.comp right)).comp (zero.pair primrec.id)).of_eq $ λ n, by simp; dsimp; rw [unpair_mkpair] theorem cases1 {f} (m : ℕ) (hf : primrec f) : primrec (nat.cases m f) := (prec1 m (hf.comp left)).of_eq $ by simp [cases] theorem cases {f g} (hf : primrec f) (hg : primrec g) : primrec (unpaired (λ z n, n.cases (f z) (λ y, g $ mkpair z y))) := (prec hf (hg.comp (pair left (left.comp right)))).of_eq $ by simp [cases] protected theorem swap : primrec (unpaired (function.swap mkpair)) := (pair right left).of_eq $ λ n, by simp theorem swap' {f} (hf : primrec (unpaired f)) : primrec (unpaired (function.swap f)) := (hf.comp primrec.swap).of_eq $ λ n, by simp theorem pred : primrec pred := (cases1 0 primrec.id).of_eq $ λ n, by cases n; simp * theorem add : primrec (unpaired (+)) := (prec primrec.id ((succ.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, add_succ] theorem sub : primrec (unpaired has_sub.sub) := (prec primrec.id ((pred.comp right).comp right)).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, -add_comm, sub_succ] theorem mul : primrec (unpaired (*)) := (prec zero (add.comp (pair left (right.comp right)))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, mul_succ] theorem pow : primrec (unpaired (^)) := (prec (const 1) (mul.comp (pair (right.comp right) left))).of_eq $ λ p, by simp; induction p.unpair.2; simp [*, pow_succ] end primrec end nat section prio set_option default_priority 100 -- see Note [default priority] /-- A `primcodable` type is an `encodable` type for which the encode/decode functions are primitive recursive. -/ class primcodable (α : Type*) extends encodable α := (prim : nat.primrec (λ n, encodable.encode (decode n))) end prio namespace primcodable open nat.primrec @[priority 10] instance of_denumerable (α) [denumerable α] : primcodable α := ⟨succ.of_eq $ by simp⟩ def of_equiv (α) {β} [primcodable α] (e : β ≃ α) : primcodable β := { prim := (primcodable.prim α).of_eq $ λ n, show encode (decode α n) = (option.cases_on (option.map e.symm (decode α n)) 0 (λ a, nat.succ (encode (e a))) : ℕ), by cases decode α n; dsimp; simp, ..encodable.of_equiv α e } instance empty : primcodable empty := ⟨zero⟩ instance unit : primcodable punit := ⟨(cases1 1 zero).of_eq $ λ n, by cases n; simp⟩ instance option {α : Type*} [h : primcodable α] : primcodable (option α) := ⟨(cases1 1 ((cases1 0 (succ.comp succ)).comp (primcodable.prim α))).of_eq $ λ n, by cases n; simp; cases decode α n; refl⟩ instance bool : primcodable bool := ⟨(cases1 1 (cases1 2 zero)).of_eq $ λ n, begin cases n, {refl}, cases n, {refl}, rw decode_ge_two, {refl}, exact dec_trivial end⟩ end primcodable /-- `primrec f` means `f` is primitive recursive (after encoding its input and output as natural numbers). -/ def primrec {α β} [primcodable α] [primcodable β] (f : α → β) : Prop := nat.primrec (λ n, encode ((decode α n).map f)) namespace primrec variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec protected theorem encode : primrec (@encode α _) := (primcodable.prim α).of_eq $ λ n, by cases decode α n; refl protected theorem decode : primrec (decode α) := succ.comp (primcodable.prim α) theorem dom_denumerable {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ nat.primrec (λ n, encode (f (of_nat α n))) := ⟨λ h, (pred.comp h).of_eq $ λ n, by simp; refl, λ h, (succ.comp h).of_eq $ λ n, by simp; refl⟩ theorem nat_iff {f : ℕ → ℕ} : primrec f ↔ nat.primrec f := dom_denumerable theorem encdec : primrec (λ n, encode (decode α n)) := nat_iff.2 (primcodable.prim α) theorem option_some : primrec (@some α) := ((cases1 0 (succ.comp succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp theorem of_eq {f g : α → σ} (hf : primrec f) (H : ∀ n, f n = g n) : primrec g := (funext H : f = g) ▸ hf theorem const (x : σ) : primrec (λ a : α, x) := ((cases1 0 (const (encode x).succ)).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; refl protected theorem id : primrec (@id α) := (primcodable.prim α).of_eq $ by simp theorem comp {f : β → σ} {g : α → β} (hf : primrec f) (hg : primrec g) : primrec (λ a, f (g a)) := ((cases1 0 (hf.comp $ pred.comp hg)).comp (primcodable.prim α)).of_eq $ λ n, begin cases decode α n, {refl}, simp [encodek] end theorem succ : primrec nat.succ := nat_iff.2 nat.primrec.succ theorem pred : primrec nat.pred := nat_iff.2 nat.primrec.pred theorem encode_iff {f : α → σ} : primrec (λ a, encode (f a)) ↔ primrec f := ⟨λ h, nat.primrec.of_eq h $ λ n, by cases decode α n; refl, primrec.encode.comp⟩ theorem of_nat_iff {α β} [denumerable α] [primcodable β] {f : α → β} : primrec f ↔ primrec (λ n, f (of_nat α n)) := dom_denumerable.trans $ nat_iff.symm.trans encode_iff protected theorem of_nat (α) [denumerable α] : primrec (of_nat α) := of_nat_iff.1 primrec.id theorem option_some_iff {f : α → σ} : primrec (λ a, some (f a)) ↔ primrec f := ⟨λ h, encode_iff.1 $ pred.comp $ encode_iff.2 h, option_some.comp⟩ theorem of_equiv {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e := (primcodable.prim α).of_eq $ λ n, show _ = encode (option.map e (option.map _ _)), by cases decode α n; simp theorem of_equiv_symm {β} {e : β ≃ α} : by haveI := primcodable.of_equiv α e; exact primrec e.symm := by letI := primcodable.of_equiv α e; exact encode_iff.1 (show primrec (λ a, encode (e (e.symm a))), by simp [primrec.encode]) theorem of_equiv_iff {β} (e : β ≃ α) {f : σ → β} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv_symm.comp h).of_eq (λ a, by simp), of_equiv.comp⟩ theorem of_equiv_symm_iff {β} (e : β ≃ α) {f : σ → α} : by haveI := primcodable.of_equiv α e; exact primrec (λ a, e.symm (f a)) ↔ primrec f := by letI := primcodable.of_equiv α e; exact ⟨λ h, (of_equiv.comp h).of_eq (λ a, by simp), of_equiv_symm.comp⟩ end primrec namespace primcodable open nat.primrec instance prod {α β} [primcodable α] [primcodable β] : primcodable (α × β) := ⟨((cases zero ((cases zero succ).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp [nat.unpaired], cases decode α n.unpair.1, { simp }, cases decode β n.unpair.2; simp end⟩ end primcodable namespace primrec variables {α : Type*} {σ : Type*} [primcodable α] [primcodable σ] open nat.primrec theorem fst {α β} [primcodable α] [primcodable β] : primrec (@prod.fst α β) := ((cases zero ((cases zero (nat.primrec.succ.comp left)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem snd {α β} [primcodable α] [primcodable β] : primrec (@prod.snd α β) := ((cases zero ((cases zero (nat.primrec.succ.comp right)).comp (pair right ((primcodable.prim β).comp left)))).comp (pair right ((primcodable.prim α).comp left))).of_eq $ λ n, begin simp, cases decode α n.unpair.1; simp, cases decode β n.unpair.2; simp end theorem pair {α β γ} [primcodable α] [primcodable β] [primcodable γ] {f : α → β} {g : α → γ} (hf : primrec f) (hg : primrec g) : primrec (λ a, (f a, g a)) := ((cases1 0 (nat.primrec.succ.comp $ pair (nat.primrec.pred.comp hf) (nat.primrec.pred.comp hg))).comp (primcodable.prim α)).of_eq $ λ n, by cases decode α n; simp [encodek]; refl theorem unpair : primrec nat.unpair := (pair (nat_iff.2 nat.primrec.left) (nat_iff.2 nat.primrec.right)).of_eq $ λ n, by simp theorem list_nth₁ : ∀ (l : list α), primrec l.nth | [] := dom_denumerable.2 zero | (a::l) := dom_denumerable.2 $ (cases1 (encode a).succ $ dom_denumerable.1 $ list_nth₁ l).of_eq $ λ n, by cases n; simp end primrec /-- `primrec₂ f` means `f` is a binary primitive recursive function. This is technically unnecessary since we can always curry all the arguments together, but there are enough natural two-arg functions that it is convenient to express this directly. -/ def primrec₂ {α β σ} [primcodable α] [primcodable β] [primcodable σ] (f : α → β → σ) := primrec (λ p : α × β, f p.1 p.2) /-- `primrec_pred p` means `p : α → Prop` is a (decidable) primitive recursive predicate, which is to say that `to_bool ∘ p : α → bool` is primitive recursive. -/ def primrec_pred {α} [primcodable α] (p : α → Prop) [decidable_pred p] := primrec (λ a, to_bool (p a)) /-- `primrec_rel p` means `p : α → β → Prop` is a (decidable) primitive recursive relation, which is to say that `to_bool ∘ p : α → β → bool` is primitive recursive. -/ def primrec_rel {α β} [primcodable α] [primcodable β] (s : α → β → Prop) [∀ a b, decidable (s a b)] := primrec₂ (λ a b, to_bool (s a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] theorem of_eq {f g : α → β → σ} (hg : primrec₂ f) (H : ∀ a b, f a b = g a b) : primrec₂ g := (by funext a b; apply H : f = g) ▸ hg theorem const (x : σ) : primrec₂ (λ (a : α) (b : β), x) := primrec.const _ protected theorem pair : primrec₂ (@prod.mk α β) := primrec.pair primrec.fst primrec.snd theorem left : primrec₂ (λ (a : α) (b : β), a) := primrec.fst theorem right : primrec₂ (λ (a : α) (b : β), b) := primrec.snd theorem mkpair : primrec₂ nat.mkpair := by simp [primrec₂, primrec]; constructor theorem unpaired {f : ℕ → ℕ → α} : primrec (nat.unpaired f) ↔ primrec₂ f := ⟨λ h, by simpa using h.comp mkpair, λ h, h.comp primrec.unpair⟩ theorem unpaired' {f : ℕ → ℕ → ℕ} : nat.primrec (nat.unpaired f) ↔ primrec₂ f := primrec.nat_iff.symm.trans unpaired theorem encode_iff {f : α → β → σ} : primrec₂ (λ a b, encode (f a b)) ↔ primrec₂ f := primrec.encode_iff theorem option_some_iff {f : α → β → σ} : primrec₂ (λ a b, some (f a b)) ↔ primrec₂ f := primrec.option_some_iff theorem of_nat_iff {α β σ} [denumerable α] [denumerable β] [primcodable σ] {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, f (of_nat α m) (of_nat β n)) := (primrec.of_nat_iff.trans $ by simp).trans unpaired theorem uncurry {f : α → β → σ} : primrec (function.uncurry f) ↔ primrec₂ f := by rw [show function.uncurry f = λ (p : α × β), f p.1 p.2, from funext $ λ ⟨a, b⟩, rfl]; refl theorem curry {f : α × β → σ} : primrec₂ (function.curry f) ↔ primrec f := by rw [← uncurry, function.uncurry_curry] end primrec₂ section comp variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem primrec.comp₂ {f : γ → σ} {g : α → β → γ} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a b, f (g a b)) := hf.comp hg theorem primrec₂.comp {f : β → γ → σ} {g : α → β} {h : α → γ} (hf : primrec₂ f) (hg : primrec g) (hh : primrec h) : primrec (λ a, f (g a) (h a)) := hf.comp (hg.pair hh) theorem primrec₂.comp₂ {f : γ → δ → σ} {g : α → β → γ} {h : α → β → δ} (hf : primrec₂ f) (hg : primrec₂ g) (hh : primrec₂ h) : primrec₂ (λ a b, f (g a b) (h a b)) := hf.comp hg hh theorem primrec_pred.comp {p : β → Prop} [decidable_pred p] {f : α → β} : primrec_pred p → primrec f → primrec_pred (λ a, p (f a)) := primrec.comp theorem primrec_rel.comp {R : β → γ → Prop} [∀ a b, decidable (R a b)] {f : α → β} {g : α → γ} : primrec_rel R → primrec f → primrec g → primrec_pred (λ a, R (f a) (g a)) := primrec₂.comp theorem primrec_rel.comp₂ {R : γ → δ → Prop} [∀ a b, decidable (R a b)] {f : α → β → γ} {g : α → β → δ} : primrec_rel R → primrec₂ f → primrec₂ g → primrec_rel (λ a b, R (f a b) (g a b)) := primrec_rel.comp end comp theorem primrec_pred.of_eq {α} [primcodable α] {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (H : ∀ a, p a ↔ q a) : primrec_pred q := primrec.of_eq hp (λ a, to_bool_congr (H a)) theorem primrec_rel.of_eq {α β} [primcodable α] [primcodable β] {r s : α → β → Prop} [∀ a b, decidable (r a b)] [∀ a b, decidable (s a b)] (hr : primrec_rel r) (H : ∀ a b, r a b ↔ s a b) : primrec_rel s := primrec₂.of_eq hr (λ a b, to_bool_congr (H a b)) namespace primrec₂ variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] open nat.primrec theorem swap {f : α → β → σ} (h : primrec₂ f) : primrec₂ (function.swap f) := h.comp₂ primrec₂.right primrec₂.left theorem nat_iff {f : α → β → σ} : primrec₂ f ↔ nat.primrec (nat.unpaired $ λ m n : ℕ, encode $ (decode α m).bind $ λ a, (decode β n).map (f a)) := have ∀ (a : option α) (b : option β), option.map (λ (p : α × β), f p.1 p.2) (option.bind a (λ (a : α), option.map (prod.mk a) b)) = option.bind a (λ a, option.map (f a) b), by intros; cases a; [refl, {cases b; refl}], by simp [primrec₂, primrec, this] theorem nat_iff' {f : α → β → σ} : primrec₂ f ↔ primrec₂ (λ m n : ℕ, option.bind (decode α m) (λ a, option.map (f a) (decode β n))) := nat_iff.trans $ unpaired'.trans encode_iff end primrec₂ namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable δ] [primcodable σ] theorem to₂ {f : α × β → σ} (hf : primrec f) : primrec₂ (λ a b, f (a, b)) := hf.of_eq $ λ ⟨a, b⟩, rfl theorem nat_elim {f : α → β} {g : α → ℕ × β → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a (n : ℕ), n.elim (f a) (λ n IH, g a (n, IH))) := primrec₂.nat_iff.2 $ ((nat.primrec.cases nat.primrec.zero $ (nat.primrec.prec hf $ nat.primrec.comp hg $ nat.primrec.left.pair $ (nat.primrec.left.comp nat.primrec.right).pair $ nat.primrec.pred.comp $ nat.primrec.right.comp nat.primrec.right).comp $ nat.primrec.right.pair $ nat.primrec.right.comp nat.primrec.left).comp $ nat.primrec.id.pair $ (primcodable.prim α).comp nat.primrec.left).of_eq $ λ n, begin simp, cases decode α n.unpair.1 with a, {refl}, simp [encodek], induction n.unpair.2 with m; simp [encodek], simp [ih, encodek] end theorem nat_elim' {f : α → ℕ} {g : α → β} {h : α → ℕ × β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).elim (g a) (λ n IH, h a (n, IH))) := (nat_elim hg hh).comp primrec.id hf theorem nat_elim₁ {f : ℕ → α → α} (a : α) (hf : primrec₂ f) : primrec (nat.elim a f) := nat_elim' primrec.id (const a) $ comp₂ hf primrec₂.right theorem nat_cases' {f : α → β} {g : α → ℕ → β} (hf : primrec f) (hg : primrec₂ g) : primrec₂ (λ a, nat.cases (f a) (g a)) := nat_elim hf $ hg.comp₂ primrec₂.left $ comp₂ fst primrec₂.right theorem nat_cases {f : α → ℕ} {g : α → β} {h : α → ℕ → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).cases (g a) (h a)) := (nat_cases' hg hh).comp primrec.id hf theorem nat_cases₁ {f : ℕ → α} (a : α) (hf : primrec f) : primrec (nat.cases a f) := nat_cases primrec.id (const a) (comp₂ hf primrec₂.right) theorem nat_iterate {f : α → ℕ} {g : α → β} {h : α → β → β} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (h a)^[f a] (g a)) := (nat_elim' hf hg (hh.comp₂ primrec₂.left $ snd.comp₂ primrec₂.right)).of_eq $ λ a, by induction f a; simp [*, -nat.iterate_succ, nat.iterate_succ'] theorem option_cases {o : α → option β} {f : α → σ} {g : α → β → σ} (ho : primrec o) (hf : primrec f) (hg : primrec₂ g) : @primrec _ σ _ _ (λ a, option.cases_on (o a) (f a) (g a)) := encode_iff.1 $ (nat_cases (encode_iff.2 ho) (encode_iff.2 hf) $ pred.comp₂ $ primrec₂.encode_iff.2 $ (primrec₂.nat_iff'.1 hg).comp₂ ((@primrec.encode α _).comp fst).to₂ primrec₂.right).of_eq $ λ a, by cases o a with b; simp [encodek]; refl theorem option_bind {f : α → option β} {g : α → β → option σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).bind (g a)) := (option_cases hf (const none) hg).of_eq $ λ a, by cases f a; refl theorem option_bind₁ {f : α → option σ} (hf : primrec f) : primrec (λ o, option.bind o f) := option_bind primrec.id (hf.comp snd).to₂ theorem option_map {f : α → option β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := option_bind hf (option_some.comp₂ hg) theorem option_map₁ {f : α → σ} (hf : primrec f) : primrec (option.map f) := option_map primrec.id (hf.comp snd).to₂ theorem option_iget [inhabited α] : primrec (@option.iget α _) := (option_cases primrec.id (const $ default α) primrec₂.right).of_eq $ λ o, by cases o; refl theorem option_is_some : primrec (@option.is_some α) := (option_cases primrec.id (const ff) (const tt).to₂).of_eq $ λ o, by cases o; refl theorem bind_decode_iff {f : α → β → option σ} : primrec₂ (λ a n, (decode β n).bind (f a)) ↔ primrec₂ f := ⟨λ h, by simpa [encodek] using h.comp fst ((@primrec.encode β _).comp snd), λ h, option_bind (primrec.decode.comp snd) $ h.comp (fst.comp fst) snd⟩ theorem map_decode_iff {f : α → β → σ} : primrec₂ (λ a n, (decode β n).map (f a)) ↔ primrec₂ f := bind_decode_iff.trans primrec₂.option_some_iff theorem nat_add : primrec₂ ((+) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.add theorem nat_sub : primrec₂ (has_sub.sub : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.sub theorem nat_mul : primrec₂ ((*) : ℕ → ℕ → ℕ) := primrec₂.unpaired'.1 nat.primrec.mul theorem cond {c : α → bool} {f : α → σ} {g : α → σ} (hc : primrec c) (hf : primrec f) (hg : primrec g) : primrec (λ a, cond (c a) (f a) (g a)) := (nat_cases (encode_iff.2 hc) hg (hf.comp fst).to₂).of_eq $ λ a, by cases c a; refl theorem ite {c : α → Prop} [decidable_pred c] {f : α → σ} {g : α → σ} (hc : primrec_pred c) (hf : primrec f) (hg : primrec g) : primrec (λ a, if c a then f a else g a) := by simpa using cond hc hf hg theorem nat_le : primrec_rel ((≤) : ℕ → ℕ → Prop) := (nat_cases nat_sub (const tt) (const ff).to₂).of_eq $ λ p, begin dsimp [function.swap], cases e : p.1 - p.2 with n, { simp [nat.sub_eq_zero_iff_le.1 e] }, { simp [not_le.2 (nat.lt_of_sub_eq_succ e)] } end theorem nat_min : primrec₂ (@min ℕ _) := ite nat_le fst snd theorem nat_max : primrec₂ (@max ℕ _) := ite nat_le snd fst theorem dom_bool (f : bool → α) : primrec f := (cond primrec.id (const (f tt)) (const (f ff))).of_eq $ λ b, by cases b; refl theorem dom_bool₂ (f : bool → bool → α) : primrec₂ f := (cond fst ((dom_bool (f tt)).comp snd) ((dom_bool (f ff)).comp snd)).of_eq $ λ ⟨a, b⟩, by cases a; refl protected theorem bnot : primrec bnot := dom_bool _ protected theorem band : primrec₂ band := dom_bool₂ _ protected theorem bor : primrec₂ bor := dom_bool₂ _ protected theorem not {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primrec_pred (λ a, ¬ p a) := (primrec.bnot.comp hp).of_eq $ λ n, by simp protected theorem and {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∧ q a) := (primrec.band.comp hp hq).of_eq $ λ n, by simp protected theorem or {p q : α → Prop} [decidable_pred p] [decidable_pred q] (hp : primrec_pred p) (hq : primrec_pred q) : primrec_pred (λ a, p a ∨ q a) := (primrec.bor.comp hp hq).of_eq $ λ n, by simp protected theorem eq [decidable_eq α] : primrec_rel (@eq α) := have primrec_rel (λ a b : ℕ, a = b), from (primrec.and nat_le nat_le.swap).of_eq $ λ a, by simp [le_antisymm_iff], (this.comp₂ (primrec.encode.comp₂ primrec₂.left) (primrec.encode.comp₂ primrec₂.right)).of_eq $ λ a b, encode_injective.eq_iff theorem nat_lt : primrec_rel ((<) : ℕ → ℕ → Prop) := (nat_le.comp snd fst).not.of_eq $ λ p, by simp theorem option_guard {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) {f : α → β} (hf : primrec f) : primrec (λ a, option.guard (p a) (f a)) := ite (hp.comp primrec.id hf) (option_some_iff.2 hf) (const none) theorem option_orelse : primrec₂ ((<|>) : option α → option α → option α) := (option_cases fst snd (fst.comp fst).to₂).of_eq $ λ ⟨o₁, o₂⟩, by cases o₁; cases o₂; refl protected theorem decode2 : primrec (decode2 α) := option_bind primrec.decode $ option_guard ((@primrec.eq _ _ nat.decidable_eq).comp (encode_iff.2 snd) (fst.comp fst)) snd theorem list_find_index₁ {p : α → β → Prop} [∀ a b, decidable (p a b)] (hp : primrec_rel p) : ∀ (l : list β), primrec (λ a, l.find_index (p a)) | [] := const 0 | (a::l) := ite (hp.comp primrec.id (const a)) (const 0) (succ.comp (list_find_index₁ l)) theorem list_index_of₁ [decidable_eq α] (l : list α) : primrec (λ a, l.index_of a) := list_find_index₁ primrec.eq l theorem dom_fintype [fintype α] (f : α → σ) : primrec f := let ⟨l, nd, m⟩ := fintype.exists_univ_list α in option_some_iff.1 $ begin haveI := decidable_eq_of_encodable α, refine ((list_nth₁ (l.map f)).comp (list_index_of₁ l)).of_eq (λ a, _), rw [list.nth_map, list.nth_le_nth (list.index_of_lt_length.2 (m _)), list.index_of_nth_le]; refl end theorem nat_bodd_div2 : primrec nat.bodd_div2 := (nat_elim' primrec.id (const (ff, 0)) (((cond fst (pair (const ff) (succ.comp snd)) (pair (const tt) snd)).comp snd).comp snd).to₂).of_eq $ λ n, begin simp [-nat.bodd_div2_eq], induction n with n IH, {refl}, simp [-nat.bodd_div2_eq, nat.bodd_div2, *], rcases nat.bodd_div2 n with ⟨_|_, m⟩; simp [nat.bodd_div2] end theorem nat_bodd : primrec nat.bodd := fst.comp nat_bodd_div2 theorem nat_div2 : primrec nat.div2 := snd.comp nat_bodd_div2 theorem nat_bit0 : primrec (@bit0 ℕ _) := nat_add.comp primrec.id primrec.id theorem nat_bit1 : primrec (@bit1 ℕ _ _) := nat_add.comp nat_bit0 (const 1) theorem nat_bit : primrec₂ nat.bit := (cond primrec.fst (nat_bit1.comp primrec.snd) (nat_bit0.comp primrec.snd)).of_eq $ λ n, by cases n.1; refl theorem nat_div_mod : primrec₂ (λ n k : ℕ, (n / k, n % k)) := let f (a : ℕ × ℕ) : ℕ × ℕ := a.1.elim (0, 0) (λ _ IH, if nat.succ IH.2 = a.2 then (nat.succ IH.1, 0) else (IH.1, nat.succ IH.2)) in have hf : primrec f, from nat_elim' fst (const (0, 0)) $ ((ite ((@primrec.eq ℕ _ _).comp (succ.comp $ snd.comp snd) fst) (pair (succ.comp $ fst.comp snd) (const 0)) (pair (fst.comp snd) (succ.comp $ snd.comp snd))) .comp (pair (snd.comp fst) (snd.comp snd))).to₂, suffices ∀ k n, (n / k, n % k) = f (n, k), from hf.of_eq $ λ ⟨m, n⟩, by simp [this], λ k n, begin have : (f (n, k)).2 + k * (f (n, k)).1 = n ∧ (0 < k → (f (n, k)).2 < k) ∧ (k = 0 → (f (n, k)).1 = 0), { induction n with n IH, {exact ⟨rfl, id, λ _, rfl⟩}, rw [λ n:ℕ, show f (n.succ, k) = _root_.ite ((f (n, k)).2.succ = k) (nat.succ (f (n, k)).1, 0) ((f (n, k)).1, (f (n, k)).2.succ), from rfl], by_cases h : (f (n, k)).2.succ = k; simp [h], { have := congr_arg nat.succ IH.1, refine ⟨_, λ k0, nat.no_confusion (h.trans k0)⟩, rwa [← nat.succ_add, h, add_comm, ← nat.mul_succ] at this }, { exact ⟨by rw [nat.succ_add, IH.1], λ k0, lt_of_le_of_ne (IH.2.1 k0) h, IH.2.2⟩ } }, revert this, cases f (n, k) with D M, simp, intros h₁ h₂ h₃, cases nat.eq_zero_or_pos k, { simp [h, h₃ h] at h₁ ⊢, simp [h₁] }, { exact (nat.div_mod_unique h).2 ⟨h₁, h₂ h⟩ } end theorem nat_div : primrec₂ ((/) : ℕ → ℕ → ℕ) := fst.comp₂ nat_div_mod theorem nat_mod : primrec₂ ((%) : ℕ → ℕ → ℕ) := snd.comp₂ nat_div_mod end primrec section variables {α : Type*} {β : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable σ] variable (H : nat.primrec (λ n, encodable.encode (decode (list β) n))) include H open primrec private def prim : primcodable (list β) := ⟨H⟩ private lemma list_cases' {f : α → list β} {g : α → σ} {h : α → β × list β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := by letI := prim H; exact have @primrec _ (option σ) _ _ (λ a, (decode (option (β × list β)) (encode (f a))).map (λ o, option.cases_on o (g a) (h a))), from ((@map_decode_iff _ (option (β × list β)) _ _ _ _ _).2 $ to₂ $ option_cases snd (hg.comp fst) (hh.comp₂ (fst.comp₂ primrec₂.left) primrec₂.right)) .comp primrec.id (encode_iff.2 hf), option_some_iff.1 $ this.of_eq $ λ a, by cases f a with b l; simp [encodek]; refl private lemma list_foldl' {f : α → list β} {g : α → σ} {h : α → σ × β → σ} (hf : by haveI := prim H; exact primrec f) (hg : primrec g) (hh : by haveI := prim H; exact primrec₂ h) : primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := by letI := prim H; exact let G (a : α) (IH : σ × list β) : σ × list β := list.cases_on IH.2 IH (λ b l, (h a (IH.1, b), l)) in let F (a : α) (n : ℕ) := nat.iterate (G a) n (g a, f a) in have primrec (λ a, (F a (encode (f a))).1), from fst.comp $ nat_iterate (encode_iff.2 hf) (pair hg hf) $ list_cases' H (snd.comp snd) snd $ to₂ $ pair (hh.comp (fst.comp fst) $ pair ((fst.comp snd).comp fst) (fst.comp snd)) (snd.comp snd), this.of_eq $ λ a, begin have : ∀ n, F a n = ((list.take n (f a)).foldl (λ s b, h a (s, b)) (g a), list.drop n (f a)), { intro, simp [F], generalize : f a = l, generalize : g a = x, induction n with n IH generalizing l x, {refl}, simp, cases l with b l; simp [IH] }, rw [this, list.take_all_of_le (length_le_encode _)] end private lemma list_cons' : by haveI := prim H; exact primrec₂ (@list.cons β) := by letI := prim H; exact encode_iff.1 (succ.comp $ primrec₂.mkpair.comp (encode_iff.2 fst) (encode_iff.2 snd)) private lemma list_reverse' : by haveI := prim H; exact primrec (@list.reverse β) := by letI := prim H; exact (list_foldl' H primrec.id (const []) $ to₂ $ ((list_cons' H).comp snd fst).comp snd).of_eq (suffices ∀ l r, list.foldl (λ (s : list β) (b : β), b :: s) r l = list.reverse_core l r, from λ l, this l [], λ l, by induction l; simp [*, list.reverse_core]) end namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec instance sum : primcodable (α ⊕ β) := ⟨primrec.nat_iff.1 $ (encode_iff.2 (cond nat_bodd (((@primrec.decode β _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const tt) (primrec.encode.comp snd)) (((@primrec.decode α _).comp nat_div2).option_map $ to₂ $ nat_bit.comp (const ff) (primrec.encode.comp snd)))).of_eq $ λ n, show _ = encode (decode_sum n), begin simp [decode_sum], cases nat.bodd n; simp [decode_sum], { cases decode α n.div2; refl }, { cases decode β n.div2; refl } end⟩ instance list : primcodable (list α) := ⟨ by letI H := primcodable.prim (list ℕ); exact have primrec₂ (λ (a : α) (o : option (list ℕ)), o.map (list.cons (encode a))), from option_map snd $ (list_cons' H).comp ((@primrec.encode α _).comp (fst.comp fst)) snd, have primrec (λ n, (of_nat (list ℕ) n).reverse.foldl (λ o m, (decode α m).bind (λ a, o.map (list.cons (encode a)))) (some [])), from list_foldl' H ((list_reverse' H).comp (primrec.of_nat (list ℕ))) (const (some [])) (primrec.comp₂ (bind_decode_iff.2 $ primrec₂.swap this) primrec₂.right), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, begin rw list.foldl_reverse, apply nat.case_strong_induction_on n, {refl}, intros n IH, simp, cases decode α n.unpair.1 with a, {refl}, simp, suffices : ∀ (o : option (list ℕ)) p (_ : encode o = encode p), encode (option.map (list.cons (encode a)) o) = encode (option.map (list.cons a) p), from this _ _ (IH _ (nat.unpair_le_right n)), intros o p IH, cases o; cases p; injection IH with h, exact congr_arg (λ k, (nat.mkpair (encode a) k).succ.succ) h end⟩ end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem sum_inl : primrec (@sum.inl α β) := encode_iff.1 $ nat_bit0.comp primrec.encode theorem sum_inr : primrec (@sum.inr α β) := encode_iff.1 $ nat_bit1.comp primrec.encode theorem sum_cases {f : α → β ⊕ γ} {g : α → β → σ} {h : α → γ → σ} (hf : primrec f) (hg : primrec₂ g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, sum.cases_on (f a) (g a) (h a)) := option_some_iff.1 $ (cond (nat_bodd.comp $ encode_iff.2 hf) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hh) (option_map (primrec.decode.comp $ nat_div2.comp $ encode_iff.2 hf) hg)).of_eq $ λ a, by cases f a with b c; simp [nat.div2_bit, nat.bodd_bit, encodek]; refl theorem list_cons : primrec₂ (@list.cons α) := list_cons' (primcodable.prim _) theorem list_cases {f : α → list β} {g : α → σ} {h : α → β × list β → σ} : primrec f → primrec g → primrec₂ h → @primrec _ σ _ _ (λ a, list.cases_on (f a) (g a) (λ b l, h a (b, l))) := list_cases' (primcodable.prim _) theorem list_foldl {f : α → list β} {g : α → σ} {h : α → σ × β → σ} : primrec f → primrec g → primrec₂ h → primrec (λ a, (f a).foldl (λ s b, h a (s, b)) (g a)) := list_foldl' (primcodable.prim _) theorem list_reverse : primrec (@list.reverse α) := list_reverse' (primcodable.prim _) theorem list_foldr {f : α → list β} {g : α → σ} {h : α → β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : primrec (λ a, (f a).foldr (λ b s, h a (b, s)) (g a)) := (list_foldl (list_reverse.comp hf) hg $ to₂ $ hh.comp fst $ (pair snd fst).comp snd).of_eq $ λ a, by simp [list.foldl_reverse] theorem list_head' : primrec (@list.head' α) := (list_cases primrec.id (const none) (option_some_iff.2 $ (fst.comp snd)).to₂).of_eq $ λ l, by cases l; refl theorem list_head [inhabited α] : primrec (@list.head α _) := (option_iget.comp list_head').of_eq $ λ l, l.head_eq_head'.symm theorem list_tail : primrec (@list.tail α) := (list_cases primrec.id (const []) (snd.comp snd).to₂).of_eq $ λ l, by cases l; refl theorem list_rec {f : α → list β} {g : α → σ} {h : α → β × list β × σ → σ} (hf : primrec f) (hg : primrec g) (hh : primrec₂ h) : @primrec _ σ _ _ (λ a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))) := let F (a : α) := (f a).foldr (λ (b : β) (s : list β × σ), (b :: s.1, h a (b, s))) ([], g a) in have primrec F, from list_foldr hf (pair (const []) hg) $ to₂ $ pair ((list_cons.comp fst (fst.comp snd)).comp snd) hh, (snd.comp this).of_eq $ λ a, begin suffices : F a = (f a, list.rec_on (f a) (g a) (λ b l IH, h a (b, l, IH))), {rw this}, simp [F], induction f a with b l IH; simp * end theorem list_nth : primrec₂ (@list.nth α) := let F (l : list α) (n : ℕ) := l.foldl (λ (s : ℕ ⊕ α) (a : α), sum.cases_on s (@nat.cases (ℕ ⊕ α) (sum.inr a) sum.inl) sum.inr) (sum.inl n) in have hF : primrec₂ F, from list_foldl fst (sum_inl.comp snd) ((sum_cases fst (nat_cases snd (sum_inr.comp $ snd.comp fst) (sum_inl.comp snd).to₂).to₂ (sum_inr.comp snd).to₂).comp snd).to₂, have @primrec _ (option α) _ _ (λ p : list α × ℕ, sum.cases_on (F p.1 p.2) (λ _, none) some), from sum_cases hF (const none).to₂ (option_some.comp snd).to₂, this.to₂.of_eq $ λ l n, begin dsimp, symmetry, induction l with a l IH generalizing n, {refl}, cases n with n, { rw [(_ : F (a :: l) 0 = sum.inr a)], {refl}, clear IH, dsimp [F], induction l with b l IH; simp * }, { apply IH } end theorem list_inth [inhabited α] : primrec₂ (@list.inth α _) := option_iget.comp₂ list_nth theorem list_append : primrec₂ ((++) : list α → list α → list α) := (list_foldr fst snd $ to₂ $ comp (@list_cons α _) snd).to₂.of_eq $ λ l₁ l₂, by induction l₁; simp * theorem list_concat : primrec₂ (λ l (a:α), l ++ [a]) := list_append.comp fst (list_cons.comp snd (const [])) theorem list_map {f : α → list β} {g : α → β → σ} (hf : primrec f) (hg : primrec₂ g) : primrec (λ a, (f a).map (g a)) := (list_foldr hf (const []) $ to₂ $ list_cons.comp (hg.comp fst (fst.comp snd)) (snd.comp snd)).of_eq $ λ a, by induction f a; simp * theorem list_range : primrec list.range := (nat_elim' primrec.id (const []) ((list_concat.comp snd fst).comp snd).to₂).of_eq $ λ n, by simp; induction n; simp [*, list.range_concat]; refl theorem list_join : primrec (@list.join α) := (list_foldr primrec.id (const []) $ to₂ $ comp (@list_append α _) snd).of_eq $ λ l, by dsimp; induction l; simp * theorem list_length : primrec (@list.length α) := (list_foldr (@primrec.id (list α) _) (const 0) $ to₂ $ (succ.comp $ snd.comp snd).to₂).of_eq $ λ l, by dsimp; induction l; simp [*, -add_comm] theorem list_find_index {f : α → list β} {p : α → β → Prop} [∀ a b, decidable (p a b)] (hf : primrec f) (hp : primrec_rel p) : primrec (λ a, (f a).find_index (p a)) := (list_foldr hf (const 0) $ to₂ $ ite (hp.comp fst $ fst.comp snd) (const 0) (succ.comp $ snd.comp snd)).of_eq $ λ a, eq.symm $ by dsimp; induction f a with b l; [refl, { simp [*, list.find_index], congr }] theorem list_index_of [decidable_eq α] : primrec₂ (@list.index_of α _) := to₂ $ list_find_index snd $ primrec.eq.comp₂ (fst.comp fst).to₂ snd.to₂ theorem nat_strong_rec (f : α → ℕ → σ) {g : α → list σ → option σ} (hg : primrec₂ g) (H : ∀ a n, g a ((list.range n).map (f a)) = some (f a n)) : primrec₂ f := suffices primrec₂ (λ a n, (list.range n).map (f a)), from primrec₂.option_some_iff.1 $ (list_nth.comp (this.comp fst (succ.comp snd)) snd).to₂.of_eq $ λ a n, by simp [list.nth_range (nat.lt_succ_self n)]; refl, primrec₂.option_some_iff.1 $ (nat_elim (const (some [])) (to₂ $ option_bind (snd.comp snd) $ to₂ $ option_map (hg.comp (fst.comp fst) snd) (to₂ $ list_concat.comp (snd.comp fst) snd))).of_eq $ λ a n, begin simp, induction n with n IH, {refl}, simp [IH, H, list.range_concat] end end primrec namespace primcodable variables {α : Type*} {β : Type*} variables [primcodable α] [primcodable β] open primrec def subtype {p : α → Prop} [decidable_pred p] (hp : primrec_pred p) : primcodable (subtype p) := ⟨have primrec (λ n, (decode α n).bind (λ a, option.guard p a)), from option_bind primrec.decode (option_guard (hp.comp snd) snd), nat_iff.1 $ (encode_iff.2 this).of_eq $ λ n, show _ = encode ((decode α n).bind (λ a, _)), begin cases decode α n with a, {refl}, dsimp [option.guard], by_cases h : p a; simp [h]; refl end⟩ instance fin {n} : primcodable (fin n) := @of_equiv _ _ (subtype $ nat_lt.comp primrec.id (const n)) (equiv.fin_equiv_subtype _) instance vector {n} : primcodable (vector α n) := subtype ((@primrec.eq _ _ nat.decidable_eq).comp list_length (const _)) instance fin_arrow {n} : primcodable (fin n → α) := of_equiv _ (equiv.vector_equiv_fin _ _).symm instance array {n} : primcodable (array n α) := of_equiv _ (equiv.array_equiv_fin _ _) end primcodable namespace primrec variables {α : Type*} {β : Type*} {γ : Type*} {σ : Type*} variables [primcodable α] [primcodable β] [primcodable γ] [primcodable σ] theorem subtype_val {p : α → Prop} [decidable_pred p] {hp : primrec_pred p} : by haveI := primcodable.subtype hp; exact primrec (@subtype.val α p) := begin letI := primcodable.subtype hp, refine (primcodable.prim (subtype p)).of_eq (λ n, _), rcases decode (subtype p) n with _|⟨a,h⟩; refl end theorem subtype_val_iff {p : β → Prop} [decidable_pred p] {hp : primrec_pred p} {f : α → subtype p} : by haveI := primcodable.subtype hp; exact primrec (λ a, (f a).1) ↔ primrec f := begin letI := primcodable.subtype hp, refine ⟨λ h, _, λ hf, subtype_val.comp hf⟩, refine nat.primrec.of_eq h (λ n, _), cases decode α n with a, {refl}, simp, cases f a; refl end theorem fin_val_iff {n} {f : α → fin n} : primrec (λ a, (f a).1) ↔ primrec f := begin let : primcodable {a//id a<n}, swap, exactI (iff.trans (by refl) subtype_val_iff).trans (of_equiv_iff _) end theorem fin_val {n} : primrec (@fin.val n) := fin_val_iff.2 primrec.id theorem fin_succ {n} : primrec (@fin.succ n) := fin_val_iff.1 $ by simp [succ.comp fin_val] theorem vector_to_list {n} : primrec (@vector.to_list α n) := subtype_val theorem vector_to_list_iff {n} {f : α → vector β n} : primrec (λ a, (f a).to_list) ↔ primrec f := subtype_val_iff theorem vector_cons {n} : primrec₂ (@vector.cons α n) := vector_to_list_iff.1 $ by simp; exact list_cons.comp fst (vector_to_list_iff.2 snd) theorem vector_length {n} : primrec (@vector.length α n) := const _ theorem vector_head {n} : primrec (@vector.head α n) := option_some_iff.1 $ (list_head'.comp vector_to_list).of_eq $ λ ⟨a::l, h⟩, rfl theorem vector_tail {n} : primrec (@vector.tail α n) := vector_to_list_iff.1 $ (list_tail.comp vector_to_list).of_eq $ λ ⟨l, h⟩, by cases l; refl theorem vector_nth {n} : primrec₂ (@vector.nth α n) := option_some_iff.1 $ (list_nth.comp (vector_to_list.comp fst) (fin_val.comp snd)).of_eq $ λ a, by simp [vector.nth_eq_nth_le]; rw [← list.nth_le_nth] theorem list_of_fn : ∀ {n} {f : fin n → α → σ}, (∀ i, primrec (f i)) → primrec (λ a, list.of_fn (λ i, f i a)) | 0 f hf := const [] | (n+1) f hf := by simp [list.of_fn_succ]; exact list_cons.comp (hf 0) (list_of_fn (λ i, hf i.succ)) theorem vector_of_fn {n} {f : fin n → α → σ} (hf : ∀ i, primrec (f i)) : primrec (λ a, vector.of_fn (λ i, f i a)) := vector_to_list_iff.1 $ by simp [list_of_fn hf] theorem vector_nth' {n} : primrec (@vector.nth α n) := of_equiv_symm theorem vector_of_fn' {n} : primrec (@vector.of_fn α n) := of_equiv theorem fin_app {n} : primrec₂ (@id (fin n → σ)) := (vector_nth.comp (vector_of_fn'.comp fst) snd).of_eq $ λ ⟨v, i⟩, by simp theorem fin_curry₁ {n} {f : fin n → α → σ} : primrec₂ f ↔ ∀ i, primrec (f i) := ⟨λ h i, h.comp (const i) primrec.id, λ h, (vector_nth.comp ((vector_of_fn h).comp snd) fst).of_eq $ λ a, by simp⟩ theorem fin_curry {n} {f : α → fin n → σ} : primrec f ↔ primrec₂ f := ⟨λ h, fin_app.comp (h.comp fst) snd, λ h, (vector_nth'.comp (vector_of_fn (λ i, show primrec (λ a, f a i), from h.comp primrec.id (const i)))).of_eq $ λ a, by funext i; simp⟩ end primrec namespace nat open vector /-- An alternative inductive definition of `primrec` which does not use the pairing function on ℕ, and so has to work with n-ary functions on ℕ instead of unary functions. We prove that this is equivalent to the regular notion in `to_prim` and `of_prim`. -/ inductive primrec' : ∀ {n}, (vector ℕ n → ℕ) → Prop | zero : @primrec' 0 (λ _, 0) | succ : @primrec' 1 (λ v, succ v.head) | nth {n} (i : fin n) : primrec' (λ v, v.nth i) | comp {m n f} (g : fin n → vector ℕ m → ℕ) : primrec' f → (∀ i, primrec' (g i)) → primrec' (λ a, f (of_fn (λ i, g i a))) | prec {n f g} : @primrec' n f → @primrec' (n+2) g → primrec' (λ v : vector ℕ (n+1), v.head.elim (f v.tail) (λ y IH, g (y :: IH :: v.tail))) end nat namespace nat.primrec' open vector primrec nat (primrec') nat.primrec' hide ite theorem to_prim {n f} (pf : @primrec' n f) : primrec f := begin induction pf, case nat.primrec'.zero { exact const 0 }, case nat.primrec'.succ { exact primrec.succ.comp vector_head }, case nat.primrec'.nth : n i { exact vector_nth.comp primrec.id (const i) }, case nat.primrec'.comp : m n f g _ _ hf hg { exact hf.comp (vector_of_fn (λ i, hg i)) }, case nat.primrec'.prec : n f g _ _ hf hg { exact nat_elim' vector_head (hf.comp vector_tail) (hg.comp $ vector_cons.comp (fst.comp snd) $ vector_cons.comp (snd.comp snd) $ (@vector_tail _ _ (n+1)).comp fst).to₂ }, end theorem of_eq {n} {f g : vector ℕ n → ℕ} (hf : primrec' f) (H : ∀ i, f i = g i) : primrec' g := (funext H : f = g) ▸ hf theorem const {n} : ∀ m, @primrec' n (λ v, m) | 0 := zero.comp fin.elim0 (λ i, i.elim0) | (m+1) := succ.comp _ (λ i, const m) theorem head {n : ℕ} : @primrec' n.succ head := (nth 0).of_eq $ λ v, by simp [nth_zero] theorem tail {n f} (hf : @primrec' n f) : @primrec' n.succ (λ v, f v.tail) := (hf.comp _ (λ i, @nth _ i.succ)).of_eq $ λ v, by rw [← of_fn_nth v.tail]; congr; funext i; simp def vec {n m} (f : vector ℕ n → vector ℕ m) := ∀ i, primrec' (λ v, (f v).nth i) protected theorem nil {n} : @vec n 0 (λ _, nil) := λ i, i.elim0 protected theorem cons {n m f g} (hf : @primrec' 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 := nth theorem comp' {n m f g} (hf : @primrec' m f) (hg : @vec n m g) : primrec' (λ v, f (g v)) := (hf.comp _ hg).of_eq $ λ v, by simp theorem comp₁ (f : ℕ → ℕ) (hf : @primrec' 1 (λ v, f v.head)) {n g} (hg : @primrec' n g) : primrec' (λ v, f (g v)) := hf.comp _ (λ i, hg) theorem comp₂ (f : ℕ → ℕ → ℕ) (hf : @primrec' 2 (λ v, f v.head v.tail.head)) {n g h} (hg : @primrec' n g) (hh : @primrec' n h) : primrec' (λ v, f (g v) (h v)) := by simpa using hf.comp' (hg.cons $ hh.cons primrec'.nil) theorem prec' {n f g h} (hf : @primrec' n f) (hg : @primrec' n g) (hh : @primrec' (n+2) h) : @primrec' n (λ v, (f v).elim (g v) (λ (y IH : ℕ), h (y :: IH :: v))) := by simpa using comp' (prec hg hh) (hf.cons idv) theorem pred : @primrec' 1 (λ v, v.head.pred) := (prec' head (const 0) head).of_eq $ λ v, by simp; cases v.head; refl theorem add : @primrec' 2 (λ v, v.head + v.tail.head) := (prec head (succ.comp₁ _ (tail head))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_add] theorem sub : @primrec' 2 (λ v, v.head - v.tail.head) := begin suffices, simpa using comp₂ (λ a b, b - a) this (tail head) head, refine (prec head (pred.comp₁ _ (tail head))).of_eq (λ v, _), simp, induction v.head; simp [*, nat.sub_succ] end theorem mul : @primrec' 2 (λ v, v.head * v.tail.head) := (prec (const 0) (tail (add.comp₂ _ (tail head) (head)))).of_eq $ λ v, by simp; induction v.head; simp [*, nat.succ_mul]; rw add_comm theorem if_lt {n a b f g} (ha : @primrec' n a) (hb : @primrec' n b) (hf : @primrec' n f) (hg : @primrec' n g) : @primrec' n (λ v, if a v < b v then f v else g v) := (prec' (sub.comp₂ _ hb ha) hg (tail $ tail hf)).of_eq $ λ v, begin cases e : b v - a v, { simp [not_lt.2 (nat.le_of_sub_eq_zero e)] }, { simp [nat.lt_of_sub_eq_succ e] } end theorem mkpair : @primrec' 2 (λ v, v.head.mkpair v.tail.head) := if_lt head (tail head) (add.comp₂ _ (tail $ mul.comp₂ _ head head) head) (add.comp₂ _ (add.comp₂ _ (mul.comp₂ _ head head) head) (tail head)) protected theorem encode : ∀ {n}, @primrec' n encode | 0 := (const 0).of_eq (λ v, by rw v.eq_nil; refl) | (n+1) := (succ.comp₁ _ (mkpair.comp₂ _ head (tail encode))) .of_eq $ λ ⟨a::l, e⟩, rfl theorem sqrt : @primrec' 1 (λ v, v.head.sqrt) := begin suffices H : ∀ n : ℕ, n.sqrt = n.elim 0 (λ x y, if x.succ < y.succ*y.succ then y else y.succ), { simp [H], have := @prec' 1 _ _ (λ v, by have x := v.head; have y := v.tail.head; from if x.succ < y.succ*y.succ then y else y.succ) head (const 0) _, { convert this, funext, congr, funext x y, congr; simp }, have x1 := succ.comp₁ _ head, have y1 := succ.comp₁ _ (tail head), exact if_lt x1 (mul.comp₂ _ y1 y1) (tail head) y1 }, intro, symmetry, induction n with n IH, {refl}, dsimp, rw IH, split_ifs, { exact le_antisymm (nat.sqrt_le_sqrt (nat.le_succ _)) (nat.lt_succ_iff.1 $ nat.sqrt_lt.2 h) }, { exact nat.eq_sqrt.2 ⟨not_lt.1 h, nat.sqrt_lt.1 $ nat.lt_succ_iff.2 $ nat.sqrt_succ_le_succ_sqrt _⟩ }, end theorem unpair₁ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.1) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s fss s).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem unpair₂ {n f} (hf : @primrec' n f) : @primrec' n (λ v, (f v).unpair.2) := begin have s := sqrt.comp₁ _ hf, have fss := sub.comp₂ _ hf (mul.comp₂ _ s s), refine (if_lt fss s s (sub.comp₂ _ fss s)).of_eq (λ v, _), simp [nat.unpair], split_ifs; refl end theorem of_prim : ∀ {n f}, primrec f → @primrec' n f := suffices ∀ f, nat.primrec f → @primrec' 1 (λ v, f v.head), from λ n f hf, (pred.comp₁ _ $ (this _ hf).comp₁ (λ m, encodable.encode $ (decode (vector ℕ n) m).map f) primrec'.encode).of_eq (λ i, by simp [encodek]), λ f hf, begin induction hf, case nat.primrec.zero { exact const 0 }, case nat.primrec.succ { exact succ }, case nat.primrec.left { exact unpair₁ head }, case nat.primrec.right { exact unpair₂ head }, case nat.primrec.pair : f g _ _ hf hg { exact mkpair.comp₂ _ hf hg }, case nat.primrec.comp : f g _ _ hf hg { exact hf.comp₁ _ hg }, case nat.primrec.prec : f g _ _ hf hg { simpa using prec' (unpair₂ head) (hf.comp₁ _ (unpair₁ head)) (hg.comp₁ _ $ mkpair.comp₂ _ (unpair₁ $ tail $ tail head) (mkpair.comp₂ _ head (tail head))) }, end theorem prim_iff {n f} : @primrec' n f ↔ primrec f := ⟨to_prim, of_prim⟩ theorem prim_iff₁ {f : ℕ → ℕ} : @primrec' 1 (λ v, f v.head) ↔ primrec f := prim_iff.trans ⟨ λ h, (h.comp $ vector_of_fn $ λ i, primrec.id).of_eq (λ v, by simp), λ h, h.comp vector_head⟩ theorem prim_iff₂ {f : ℕ → ℕ → ℕ} : @primrec' 2 (λ v, f v.head v.tail.head) ↔ primrec₂ f := prim_iff.trans ⟨ λ h, (h.comp $ vector_cons.comp fst $ vector_cons.comp snd (primrec.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 ↔ primrec f := ⟨λ h, by simpa using vector_of_fn (λ i, to_prim (h i)), λ h i, of_prim $ vector_nth.comp h (primrec.const i)⟩ end nat.primrec' theorem primrec.nat_sqrt : primrec nat.sqrt := nat.primrec'.prim_iff₁.1 nat.primrec'.sqrt
cf72d13aaf4f62461bc9163c19cb78b595ec67bd
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Lean/Elab/BuiltinNotation.lean
6f27c9ccd4ffe6b3fea0b475882b16f9e3ca1169
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,614
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 Init.Data.ToString import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.Transform import Lean.Elab.Term import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival us => do match ival.ctors with | [ctor] => let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by%$b $tac:tacticSeq) => `(show $type from by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => let mkId (x? : Option Syntax) : Syntax := x?.getD <| mkIdentFrom stx `this match stx with | `(have $[$x :]? $type from $val $[;]? $body) => let x := mkId x; `(let_fun $x : $type := $val; $body) | `(have $[$x :]? $type by%$b $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from by%$b $tac:tacticSeq; $body) | `(have $x:ident : $type:term := $val $[;]? $body) => `(let_fun $x:ident : $type:term := $val; $body) | `(have $x:ident := $val:term $[;]? $body) => `(let_fun $x:ident := $val:term ; $body) | `(have $pattern:term := $val:term $[;]? $body) => `(let_fun $pattern:term := $val:term ; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x :]? $type from $body; $val) | `(suffices $[$x :]? $type by%$b $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from $body; by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported open Lean.Parser in private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := Name.str _ s _, scopes := scps, .. } => let kind := quote declName let s := quote s -- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind let antiquotKind ← if scps == [] then `(some $kind) else `(none) ``(withAntiquot (mkAntiquot $s $antiquotKind) (leadingNode $kind $prec $e)) | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(leading_parser $e) => elabParserMacroAux (quote Parser.maxPrec) e | `(leading_parser : $prec $e) => elabParserMacroAux prec e | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec : Syntax) (e : Syntax) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do let arg := stx[1] let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx => -- TODO: support for disabling runtime assertions let cond := stx[1] let body := stx[3] match cond.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx => let arg := stx[1] let body := stx[3] if arg.getKind == interpolatedStrKind then `(dbgTrace (s! $arg) fun _ => $body) else `(dbgTrace (toString $arg) fun _ => $body) @[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do logWarning "declaration uses 'sorry'" let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do if i > 0 then let i := i - 1 let elem := elems[i] let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ partial def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do if hasCDot stx then let (newStx, binders) ← (go stx).run #[]; `(fun $binders* => $newStx) else pure none where /-- Auxiliary function for expanding the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ go : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope do let id ← `(a) modify fun s => s.push id; pure id else do let args ← args.mapM go pure $ Syntax.node k args | stx => pure stx /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Syntax) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f:ident $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | `(fun $binders* => binop% $f:ident $a $b) => if binders == #[a, b] then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx /-- Try to expand `·` notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ @[builtinMacro Lean.Parser.Term.paren] def expandParen : Macro | `(()) => `(Unit.unit) | `(($e : $type)) => do match ← expandCDot? e with | some e => `(($e : $type)) | none => Macro.throwUnsupported | `(($e)) => return (← expandCDot? e).getD e | `(($e, $es,*)) => do let pairs ← mkPairs (#[e] ++ es) (← expandCDot? pairs).getD pairs | stx => throw <| Macro.Exception.error stx "unexpected parentheses notation" @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do match stx with | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) <| elabType type let e ← elabTerm e type ensureHasType type e | _ => throwUnsupportedSyntax @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation" match stx with | `($heq ▸ $h) => do let mut heq ← elabTerm heq none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (typeWithLooseBVar : Expr) := do withLocalDeclD (← mkFreshUserName `x) α fun x => do mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let h ← withRef h do let h ← elabTerm h hExpectedType try ensureHasType hExpectedType h catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq) mkEqNDRec (← mkMotive expectedAbst) h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut m := stx[2] if m.getKind == `Lean.Parser.Term.macroDollarArg then m := m[1] let m ← elabTerm m (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM `STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM `StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
e1d92a2377cd0d529d77eb1e54d9f8d5d24b5a88
bb31430994044506fa42fd667e2d556327e18dfe
/src/data/set/n_ary.lean
7ebc1528ff099b39d48116e66812615ef4bdf046
[ "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
15,317
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import data.set.prod /-! # N-ary images of sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `finset.image₂`, the binary image of finsets. This is the finset version of `set.image2`. This is mostly useful to define pointwise operations. ## Notes This file is very similar to the n-ary section of `data.set.basic`, to `order.filter.n_ary` and to `data.option.n_ary`. Please keep them in sync. We do not define `finset.image₃` as its only purpose would be to prove properties of `finset.image₂` and `set.image2` already fulfills this task. -/ open function namespace set variables {α α' β β' γ γ' δ δ' ε ε' : Type*} {f f' : α → β → γ} {g g' : α → β → γ → δ} variables {s s' : set α} {t t' : set β} {u u' : set γ} {a a' : α} {b b' : β} {c c' : γ} {d d' : δ} /-- The image of a binary function `f : α → β → γ` as a function `set α → set β → set γ`. Mathematically this should be thought of as the image of the corresponding function `α × β → γ`.-/ def image2 (f : α → β → γ) (s : set α) (t : set β) : set γ := {c | ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c } @[simp] lemma mem_image2 : c ∈ image2 f s t ↔ ∃ a b, a ∈ s ∧ b ∈ t ∧ f a b = c := iff.rfl lemma mem_image2_of_mem (ha : a ∈ s) (hb : b ∈ t) : f a b ∈ image2 f s t := ⟨a, b, ha, hb, rfl⟩ lemma mem_image2_iff (hf : injective2 f) : f a b ∈ image2 f s t ↔ a ∈ s ∧ b ∈ t := ⟨ by { rintro ⟨a', b', ha', hb', h⟩, rcases hf h with ⟨rfl, rfl⟩, exact ⟨ha', hb'⟩ }, λ ⟨ha, hb⟩, mem_image2_of_mem ha hb⟩ /-- image2 is monotone with respect to `⊆`. -/ lemma image2_subset (hs : s ⊆ s') (ht : t ⊆ t') : image2 f s t ⊆ image2 f s' t' := by { rintro _ ⟨a, b, ha, hb, rfl⟩, exact mem_image2_of_mem (hs ha) (ht hb) } lemma image2_subset_left (ht : t ⊆ t') : image2 f s t ⊆ image2 f s t' := image2_subset subset.rfl ht lemma image2_subset_right (hs : s ⊆ s') : image2 f s t ⊆ image2 f s' t := image2_subset hs subset.rfl lemma image_subset_image2_left (hb : b ∈ t) : (λ a, f a b) '' s ⊆ image2 f s t := ball_image_of_ball $ λ a ha, mem_image2_of_mem ha hb lemma image_subset_image2_right (ha : a ∈ s) : f a '' t ⊆ image2 f s t := ball_image_of_ball $ λ b, mem_image2_of_mem ha lemma forall_image2_iff {p : γ → Prop} : (∀ z ∈ image2 f s t, p z) ↔ ∀ (x ∈ s) (y ∈ t), p (f x y) := ⟨λ h x hx y hy, h _ ⟨x, y, hx, hy, rfl⟩, λ h z ⟨x, y, hx, hy, hz⟩, hz ▸ h x hx y hy⟩ @[simp] lemma image2_subset_iff {u : set γ} : image2 f s t ⊆ u ↔ ∀ (x ∈ s) (y ∈ t), f x y ∈ u := forall_image2_iff variables (f) @[simp] lemma image_prod : (λ x : α × β, f x.1 x.2) '' s ×ˢ t = image2 f s t := ext $ λ a, ⟨ by { rintro ⟨_, _, rfl⟩, exact ⟨_, _, (mem_prod.1 ‹_›).1, (mem_prod.1 ‹_›).2, rfl⟩ }, by { rintro ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), ⟨‹_›, ‹_›⟩, rfl⟩ }⟩ @[simp] lemma image_uncurry_prod (s : set α) (t : set β) : uncurry f '' s ×ˢ t = image2 f s t := image_prod _ @[simp] lemma image2_mk_eq_prod : image2 prod.mk s t = s ×ˢ t := ext $ by simp @[simp] lemma image2_curry (f : α × β → γ) (s : set α) (t : set β) : image2 (λ a b, f (a, b)) s t = f '' s ×ˢ t := by simp [←image_uncurry_prod, uncurry] variables {f} lemma image2_union_left : image2 f (s ∪ s') t = image2 f s t ∪ image2 f s' t := begin ext c, split, { rintro ⟨a, b, ha | ha, hb, rfl⟩; [left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, _, ‹_›, rfl⟩; simp [mem_union, *] } end lemma image2_union_right : image2 f s (t ∪ t') = image2 f s t ∪ image2 f s t' := begin ext c, split, { rintro ⟨a, b, ha, h1b|h2b, rfl⟩;[left, right]; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ }, { rintro (⟨_, _, _, _, rfl⟩|⟨_, _, _, _, rfl⟩); refine ⟨_, _, ‹_›, _, rfl⟩; simp [mem_union, *] } end lemma image2_inter_left (hf : injective2 f) : image2 f (s ∩ s') t = image2 f s t ∩ image2 f s' t := by simp_rw [←image_uncurry_prod, inter_prod, image_inter hf.uncurry] lemma image2_inter_right (hf : injective2 f) : image2 f s (t ∩ t') = image2 f s t ∩ image2 f s t' := by simp_rw [←image_uncurry_prod, prod_inter, image_inter hf.uncurry] @[simp] lemma image2_empty_left : image2 f ∅ t = ∅ := ext $ by simp @[simp] lemma image2_empty_right : image2 f s ∅ = ∅ := ext $ by simp lemma nonempty.image2 : s.nonempty → t.nonempty → (image2 f s t).nonempty := λ ⟨a, ha⟩ ⟨b, hb⟩, ⟨_, mem_image2_of_mem ha hb⟩ @[simp] lemma image2_nonempty_iff : (image2 f s t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ ⟨_, a, b, ha, hb, _⟩, ⟨⟨a, ha⟩, b, hb⟩, λ h, h.1.image2 h.2⟩ lemma nonempty.of_image2_left (h : (image2 f s t).nonempty) : s.nonempty := (image2_nonempty_iff.1 h).1 lemma nonempty.of_image2_right (h : (image2 f s t).nonempty) : t.nonempty := (image2_nonempty_iff.1 h).2 @[simp] lemma image2_eq_empty_iff : image2 f s t = ∅ ↔ s = ∅ ∨ t = ∅ := by simp_rw [←not_nonempty_iff_eq_empty, image2_nonempty_iff, not_and_distrib] lemma image2_inter_subset_left : image2 f (s ∩ s') t ⊆ image2 f s t ∩ image2 f s' t := by { rintro _ ⟨a, b, ⟨h1a, h2a⟩, hb, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } lemma image2_inter_subset_right : image2 f s (t ∩ t') ⊆ image2 f s t ∩ image2 f s t' := by { rintro _ ⟨a, b, ha, ⟨h1b, h2b⟩, rfl⟩, split; exact ⟨_, _, ‹_›, ‹_›, rfl⟩ } @[simp] lemma image2_singleton_left : image2 f {a} t = f a '' t := ext $ λ x, by simp @[simp] lemma image2_singleton_right : image2 f s {b} = (λ a, f a b) '' s := ext $ λ x, by simp lemma image2_singleton : image2 f {a} {b} = {f a b} := by simp @[congr] lemma image2_congr (h : ∀ (a ∈ s) (b ∈ t), f a b = f' a b) : image2 f s t = image2 f' s t := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨a, b, ha, hb, by rw h a ha b hb⟩ } /-- A common special case of `image2_congr` -/ lemma image2_congr' (h : ∀ a b, f a b = f' a b) : image2 f s t = image2 f' s t := image2_congr (λ a _ b _, h a b) /-- The image of a ternary function `f : α → β → γ → δ` as a function `set α → set β → set γ → set δ`. Mathematically this should be thought of as the image of the corresponding function `α × β × γ → δ`. -/ def image3 (g : α → β → γ → δ) (s : set α) (t : set β) (u : set γ) : set δ := {d | ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d } @[simp] lemma mem_image3 : d ∈ image3 g s t u ↔ ∃ a b c, a ∈ s ∧ b ∈ t ∧ c ∈ u ∧ g a b c = d := iff.rfl lemma image3_mono (hs : s ⊆ s') (ht : t ⊆ t') (hu : u ⊆ u') : image3 g s t u ⊆ image3 g s' t' u' := λ x, Exists₃.imp $ λ a b c ⟨ha, hb, hc, hx⟩, ⟨hs ha, ht hb, hu hc, hx⟩ @[congr] lemma image3_congr (h : ∀ (a ∈ s) (b ∈ t) (c ∈ u), g a b c = g' a b c) : image3 g s t u = image3 g' s t u := by { ext x, split; rintro ⟨a, b, c, ha, hb, hc, rfl⟩; exact ⟨a, b, c, ha, hb, hc, by rw h a ha b hb c hc⟩ } /-- A common special case of `image3_congr` -/ lemma image3_congr' (h : ∀ a b c, g a b c = g' a b c) : image3 g s t u = image3 g' s t u := image3_congr (λ a _ b _ c _, h a b c) lemma image2_image2_left (f : δ → γ → ε) (g : α → β → δ) : image2 f (image2 g s t) u = image3 (λ a b c, f (g a b) c) s t u := begin ext, split, { rintro ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩ } end lemma image2_image2_right (f : α → δ → ε) (g : β → γ → δ) : image2 f s (image2 g t u) = image3 (λ a b c, f a (g b c)) s t u := begin ext, split, { rintro ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, refine ⟨a, b, c, ha, hb, hc, rfl⟩ }, { rintro ⟨a, b, c, ha, hb, hc, rfl⟩, refine ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩ } end lemma image_image2 (f : α → β → γ) (g : γ → δ) : g '' image2 f s t = image2 (λ a b, g (f a b)) s t := begin ext, split, { rintro ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, ⟨a, b, ha, hb, rfl⟩, rfl⟩ } end lemma image2_image_left (f : γ → β → δ) (g : α → γ) : image2 f (g '' s) t = image2 (λ a b, f (g a) b) s t := begin ext, split, { rintro ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨_, b, ⟨a, ha, rfl⟩, hb, rfl⟩ } end lemma image2_image_right (f : α → γ → δ) (g : β → γ) : image2 f s (g '' t) = image2 (λ a b, f a (g b)) s t := begin ext, split, { rintro ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩, refine ⟨a, b, ha, hb, rfl⟩ }, { rintro ⟨a, b, ha, hb, rfl⟩, refine ⟨a, _, ha, ⟨b, hb, rfl⟩, rfl⟩ } end lemma image2_swap (f : α → β → γ) (s : set α) (t : set β) : image2 f s t = image2 (λ a b, f b a) t s := by { ext, split; rintro ⟨a, b, ha, hb, rfl⟩; refine ⟨b, a, hb, ha, rfl⟩ } @[simp] lemma image2_left (h : t.nonempty) : image2 (λ x y, x) s t = s := by simp [nonempty_def.mp h, ext_iff] @[simp] lemma image2_right (h : s.nonempty) : image2 (λ x y, y) s t = t := by simp [nonempty_def.mp h, ext_iff] lemma image2_assoc {f : δ → γ → ε} {g : α → β → δ} {f' : α → ε' → ε} {g' : β → γ → ε'} (h_assoc : ∀ a b c, f (g a b) c = f' a (g' b c)) : image2 f (image2 g s t) u = image2 f' s (image2 g' t u) := by simp only [image2_image2_left, image2_image2_right, h_assoc] lemma image2_comm {g : β → α → γ} (h_comm : ∀ a b, f a b = g b a) : image2 f s t = image2 g t s := (image2_swap _ _ _).trans $ by simp_rw h_comm lemma image2_left_comm {f : α → δ → ε} {g : β → γ → δ} {f' : α → γ → δ'} {g' : β → δ' → ε} (h_left_comm : ∀ a b c, f a (g b c) = g' b (f' a c)) : image2 f s (image2 g t u) = image2 g' t (image2 f' s u) := by { rw [image2_swap f', image2_swap f], exact image2_assoc (λ _ _ _, h_left_comm _ _ _) } lemma image2_right_comm {f : δ → γ → ε} {g : α → β → δ} {f' : α → γ → δ'} {g' : δ' → β → ε} (h_right_comm : ∀ a b c, f (g a b) c = g' (f' a c) b) : image2 f (image2 g s t) u = image2 g' (image2 f' s u) t := by { rw [image2_swap g, image2_swap g'], exact image2_assoc (λ _ _ _, h_right_comm _ _ _) } lemma image_image2_distrib {g : γ → δ} {f' : α' → β' → δ} {g₁ : α → α'} {g₂ : β → β'} (h_distrib : ∀ a b, g (f a b) = f' (g₁ a) (g₂ b)) : (image2 f s t).image g = image2 f' (s.image g₁) (t.image g₂) := by simp_rw [image_image2, image2_image_left, image2_image_right, h_distrib] /-- Symmetric statement to `set.image2_image_left_comm`. -/ lemma image_image2_distrib_left {g : γ → δ} {f' : α' → β → δ} {g' : α → α'} (h_distrib : ∀ a b, g (f a b) = f' (g' a) b) : (image2 f s t).image g = image2 f' (s.image g') t := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric statement to `set.image_image2_right_comm`. -/ lemma image_image2_distrib_right {g : γ → δ} {f' : α → β' → δ} {g' : β → β'} (h_distrib : ∀ a b, g (f a b) = f' a (g' b)) : (image2 f s t).image g = image2 f' s (t.image g') := (image_image2_distrib h_distrib).trans $ by rw image_id' /-- Symmetric statement to `set.image_image2_distrib_left`. -/ lemma image2_image_left_comm {f : α' → β → γ} {g : α → α'} {f' : α → β → δ} {g' : δ → γ} (h_left_comm : ∀ a b, f (g a) b = g' (f' a b)) : image2 f (s.image g) t = (image2 f' s t).image g' := (image_image2_distrib_left $ λ a b, (h_left_comm a b).symm).symm /-- Symmetric statement to `set.image_image2_distrib_right`. -/ lemma image_image2_right_comm {f : α → β' → γ} {g : β → β'} {f' : α → β → δ} {g' : δ → γ} (h_right_comm : ∀ a b, f a (g b) = g' (f' a b)) : image2 f s (t.image g) = (image2 f' s t).image g' := (image_image2_distrib_right $ λ a b, (h_right_comm a b).symm).symm /-- The other direction does not hold because of the `s`-`s` cross terms on the RHS. -/ lemma image2_distrib_subset_left {f : α → δ → ε} {g : β → γ → δ} {f₁ : α → β → β'} {f₂ : α → γ → γ'} {g' : β' → γ' → ε} (h_distrib : ∀ a b c, f a (g b c) = g' (f₁ a b) (f₂ a c)) : image2 f s (image2 g t u) ⊆ image2 g' (image2 f₁ s t) (image2 f₂ s u) := begin rintro _ ⟨a, _, ha, ⟨b, c, hb, hc, rfl⟩, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hb) (mem_image2_of_mem ha hc), end /-- The other direction does not hold because of the `u`-`u` cross terms on the RHS. -/ lemma image2_distrib_subset_right {f : δ → γ → ε} {g : α → β → δ} {f₁ : α → γ → α'} {f₂ : β → γ → β'} {g' : α' → β' → ε} (h_distrib : ∀ a b c, f (g a b) c = g' (f₁ a c) (f₂ b c)) : image2 f (image2 g s t) u ⊆ image2 g' (image2 f₁ s u) (image2 f₂ t u) := begin rintro _ ⟨_, c, ⟨a, b, ha, hb, rfl⟩, hc, rfl⟩, rw h_distrib, exact mem_image2_of_mem (mem_image2_of_mem ha hc) (mem_image2_of_mem hb hc), end lemma image_image2_antidistrib {g : γ → δ} {f' : β' → α' → δ} {g₁ : β → β'} {g₂ : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' (g₁ b) (g₂ a)) : (image2 f s t).image g = image2 f' (t.image g₁) (s.image g₂) := by { rw image2_swap f, exact image_image2_distrib (λ _ _, h_antidistrib _ _) } /-- Symmetric statement to `set.image2_image_left_anticomm`. -/ lemma image_image2_antidistrib_left {g : γ → δ} {f' : β' → α → δ} {g' : β → β'} (h_antidistrib : ∀ a b, g (f a b) = f' (g' b) a) : (image2 f s t).image g = image2 f' (t.image g') s := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric statement to `set.image_image2_right_anticomm`. -/ lemma image_image2_antidistrib_right {g : γ → δ} {f' : β → α' → δ} {g' : α → α'} (h_antidistrib : ∀ a b, g (f a b) = f' b (g' a)) : (image2 f s t).image g = image2 f' t (s.image g') := (image_image2_antidistrib h_antidistrib).trans $ by rw image_id' /-- Symmetric statement to `set.image_image2_antidistrib_left`. -/ lemma image2_image_left_anticomm {f : α' → β → γ} {g : α → α'} {f' : β → α → δ} {g' : δ → γ} (h_left_anticomm : ∀ a b, f (g a) b = g' (f' b a)) : image2 f (s.image g) t = (image2 f' t s).image g' := (image_image2_antidistrib_left $ λ a b, (h_left_anticomm b a).symm).symm /-- Symmetric statement to `set.image_image2_antidistrib_right`. -/ lemma image_image2_right_anticomm {f : α → β' → γ} {g : β → β'} {f' : β → α → δ} {g' : δ → γ} (h_right_anticomm : ∀ a b, f a (g b) = g' (f' b a)) : image2 f s (t.image g) = (image2 f' t s).image g' := (image_image2_antidistrib_right $ λ a b, (h_right_anticomm b a).symm).symm end set
d8f2222cac007a785f41f13841c335b5632724e5
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/group_representation.lean
2fe38372e1422306b5a393544901c63b05205503
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
12,297
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: ... -/ import linear_algebra.basic import algebra.group.hom /- we will probably need to import other files soon too, like `linear_algebra.finite_dimensional`. -/ -- set_option trace.simplify true run_cmd mk_simp_attr `RW_REP meta def rw_simp : tactic unit := `[ try {simp only with RW_REP}, try {exact rfl}] run_cmd add_interactive [`rw_simp] universe variables u v w w' open group open linear_map open linear_equiv open submodule open linear_map.general_linear_group /- I thinck i add three lemma into mathlib line 1922 at the file linear_algebra.bassic def to_linear_map (f : general_linear_group R M) : M →ₗ[R] M :=(to_linear_equiv f).to_linear_map def to_linear_map_inv (f : general_linear_group R M) : M →ₗ[R] M := (to_linear_equiv f⁻¹).to_linear_map def to_fun (f : general_linear_group R M) : M → M := f.val -/ attribute [RW_REP] coe_add coe_neg coe_smul coe_mk subtype.eta eq.symm namespace NOTATION notation `GL` := general_linear_group notation `L`:80 f :80 := general_linear_group.to_linear_map f notation `F`:80 f :82 := general_linear_group.to_fun f --- add in mathlib notation a` ⊚ `:80 b:80 := linear_map.comp a b end NOTATION /- maybe needs a shorter name -/ /-- A representation of a group `G` is an `R`-module `M` with a group homomorphisme from `G` to `GL(M)`. Normally `M` is a vector space, but we don't need that for the definition. -/ def group_representation (G R M : Type*) [group G] [ring R] [add_comm_group M] [module R M] : Type* := G →* GL R M -- open NOTATION variables {G : Type u} {R : Type v} {M : Type w} {M' : Type w'} [group G] [ring R] [add_comm_group M] [module R M] [add_comm_group M'] [module R M'] instance : has_coe_to_fun (group_representation G R M) := ⟨_, λ g, g.to_fun⟩ --- def has_coe_to (ρ : group_representation G R M) : G → (M →ₗ[R] M ) := λ g, L ρ g notation `⟦` ρ `⟧` := has_coe_to ρ namespace MY_TEST variables (f : M →ₗ[R] M) ( x y : M) variables (ρ : group_representation G R M) include ρ example : f (x+ y) = f(x)+f(y) := f.add x y @[RW_REP] theorem linearity (g : G ) (x y : M): ⟦ ρ ⟧ g (x+y) = ⟦ρ⟧ g (x) + ⟦ρ⟧ g (y) := begin exact (⟦ρ⟧ g).add x y end @[RW_REP] theorem smul' (g : G) (r : R)(m : M) : (⟦ ρ⟧ g) (r • m) = r • ((⟦ ρ ⟧ g) m) := begin exact ( ⟦ ρ ⟧ g).smul r m, end variables (g g' : G) variables (p : submodule R M) @[RW_REP]lemma F_linearity (x y : M) (g : G) : (F ρ g) (x+y) = (F ρ g) x + (F ρ g) y := begin exact (L ρ g).add x y, --- the same for L ! end variables (h : ∀ x : M, ∀ g : G, (L ρ g) x ∈ p) --- le mécanisme est le suivant : --- ρ : G →* GL R M --- le problème étant que :: c'est un morphsime de groupe mais c'est une structure --- GL R M donc convertion merdique via L --- Il y a ⇑ theorem L_to_F (g : G) : (F ρ g) = ⟦ρ⟧ g := rfl example (ρ : group_representation G R M) ( g g' : G) : ρ (g * g') = ρ g * ρ g' := ρ.map_mul g g' @[RW_REP]lemma rmap_mul (ρ : group_representation G R M) ( g g' : G) : ⟦ ρ ⟧ (g * g') = ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' := begin ext, rw comp_apply, iterate 3{rw ← L_to_F}, rw ρ.map_mul,exact rfl, end -- @[RW_REP]lemma rmap_mul' (ρ : group_representation G R M) ( g g' : G) : -- ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' = ⟦ ρ ⟧ (g * g') := -- begin -- ext, rw comp_apply, iterate 3{rw ← L_to_F}, rw ρ.map_mul,exact rfl, -- end @[RW_REP] lemma rmap_one (ρ : group_representation G R M) : ⟦ ρ ⟧ (1) = linear_map.id := begin ext,rw ← L_to_F,rw ρ.map_one,exact rfl, end @[RW_REP] lemma rmap_inv_mul (ρ : group_representation G R M)(g: G) : ⟦ ρ ⟧ (g * g⁻¹ ) = linear_map.id := begin rw mul_inv_self,exact rmap_one ρ, end @[RW_REP] lemma rmap_mul_inv (ρ : group_representation G R M)(g: G) : ⟦ ρ ⟧ (g⁻¹ * g ) = linear_map.id := begin rw inv_mul_self,exact rmap_one ρ, end @[RW_REP] lemma rmap_inv' (ρ : group_representation G R M) (g : G) : ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g⁻¹ = linear_map.id := begin rw ← rmap_mul,exact rmap_inv_mul ρ g, end @[RW_REP] lemma rmap_inv''(ρ : group_representation G R M) (g : G) : ⟦ρ⟧ g⁻¹ ⊚ ⟦ ρ ⟧ g = linear_map.id := begin rw ← rmap_mul,exact rmap_mul_inv ρ g , end @[RW_REP] lemma rmap_inv_apply'' (ρ : group_representation G R M) (g : G)(x : M) : (⟦ρ⟧ g⁻¹ ⊚ ⟦ ρ ⟧ g ) x = x := begin rw rmap_inv'',exact rfl, end @[RW_REP] lemma rmap_inv_apply' (ρ : group_representation G R M) (g : G)(x : M) : (⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g⁻¹ ) x = x := begin rw rmap_inv',exact rfl, end def has_inv (ρ : group_representation G R M)(g : G) : M ≃ₗ[R] M := { to_fun := ⟦ ρ ⟧ g , add := linearity ρ g , smul := smul' ρ g, inv_fun := ⟦ ρ ⟧ g⁻¹, left_inv := rmap_inv_apply'' ρ g, right_inv := rmap_inv_apply' ρ g } -- @[RW_REP] lemma rmap_inv (ρ : group_representation G R M)(g : G) : -- 207 -- ⟦ ρ ⟧ g⁻¹ = to_linear_map_inv (has_inv' ρ g ) := begin -- ext, -- sorry, -- end @[RW_REP]lemma star_is_oo (ρ : group_representation G R M) ( g g' : G) : ⟦ρ⟧ g ⊚ ⟦ ρ ⟧ g' = ⟦ρ⟧ g * ⟦ ρ ⟧ g' := by rw_simp @[RW_REP]lemma rmap_map_assoc (ρ : group_representation G R M)( g1 g2 g3 : G) : ⟦ρ⟧ (g1 * g2 *g3) = ⟦ρ⟧ (g1) ⊚ (⟦ρ⟧ g2 ⊚ ⟦ρ⟧ g3) := begin rw group.mul_assoc,rw rmap_mul,rw rmap_mul, -- rw_simp, end example (ρ : group_representation G R M)( g1 g2 g3 g4 : G) : ⟦ρ⟧ (g1 * (g2 *g3 * g4)) = ⟦ρ⟧ (g1) ⊚ (⟦ρ⟧ g2 ⊚ ⟦ρ⟧ g3) * ⟦ ρ ⟧ g4 := begin rw_simp, end @[RW_REP]lemma times_to_oo (ρ : group_representation G R M)( g g' : G) : ⟦ ρ ⟧ (g * g') = ⟦ρ⟧ g * ⟦ ρ ⟧ g' := begin rw_simp, end example (ρ : group_representation G R M)( g1 g2 g3 : G) : ⟦ρ⟧ (g1 * g2 *g3) = ⟦ρ⟧ (g1) ⊚ ⟦ρ⟧ g2 * ⟦ρ⟧ g3 := begin rw_simp, end @[RW_REP]lemma mul_to_composition_of_function (ρ : group_representation G R M) ( g g' : G) : ⟦ ρ⟧ (g * g') = ( ⟦ ρ⟧ g ) * (⟦ ρ ⟧ g') := begin rw_simp, end @[RW_REP]lemma mixte_linearity (ρ : group_representation G R M) ( g g' : G) (x y : M) (r : R): ⟦ ρ⟧ (g * g') (x+r • y) = ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' x )+ r • ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' y ) := begin iterate 2 {rw ← comp_apply},rw_simp, rw ← rmap_mul, end -- @[RW_REP]lemma L_to_F (g : G) : (L ρ g).to_fun = (F ρ g) := rfl example : ⟦ ρ ⟧ (g * g') = ( ⟦ ρ⟧ g) ⊚ ( ⟦ρ⟧ g') := by rw_simp lemma mul_one (ρ : group_representation G R M) : (L ρ 1) = 1 := begin rw ρ.map_one, exact rfl, end end MY_TEST namespace group_representation /- do we want this instance? Then we don't have to write `(ρ g).1 x` instead of `ρ g x`. -/ instance : has_coe (general_linear_group R M) (M →ₗ[R] M) := ⟨λ x, x.1⟩ protected structure morphism (ρ : group_representation G R M) (π : group_representation G R M') : Type (max w w') := (linear_map : M →ₗ[R] M') (commute : ∀(g : G), linear_map ∘ ρ g = π g ∘ linear_map) protected structure equiv (ρ : group_representation G R M) (π : group_representation G R M') : Type (max w w') := (f : M ≃ₗ[R] M') (commute : ∀(g : G), f ∘ ρ g = π g ∘ f) variables (ρ : group_representation G R M) variables (g g' : G)(x : M) -- example (x y : M) (g : G) : ρ g (x+y)= ρ g x + ρ g y := begin rw (L ρ g).add x y, end namespace stability /- We define the notion of stable submodule. We make a sub-representation. ligne 384 algebra module submodule (conduit) il y a des lemmes de convertions. -/ variables {ρ1 : group_representation G R M}{p : submodule R M} /- Strategy maths : We have ρ g x ∈ p for x ∈ p so you have a map : ρ' g : p → p ... linear_map, invertible (restriction of ρ g⁻¹ ) and trivial trivial trivial For lean : this is not trivial. We have to verify some stuff. Lemma to try to deal with convertion -/ @[RW_REP]lemma sub_module.eq_trans (x y : M) (hx : x ∈ p)(hy : y ∈ p) : (x : M) = (y : M) → (⟨x,hx⟩ : p) = (⟨ y,hy⟩ : p ) := begin intros,congr ; try { assumption }, end @[RW_REP] lemma sub_module.eq_trans' (x y : p) : (x : M) = (y : M) → x = y := begin intros,rcases x,rcases y,congr; try {assumption}, end -- lemma sub_module_val (x : M) (hx : x ∈ p) : (⟨x,hx ⟩ : p).val = (x : M) := rfl def stable_sub_module (ρ : group_representation G R M)(p : submodule R M) := ∀ g : G, ∀ x : p, (⟦ρ⟧ ρ g) x ∈ p /- First Step : we define G → (p →ₗ[R] p) -/ def restriction (h : stable_sub_module ρ p) : G → (p →ₗ[R] p) := λ g, begin exact { to_fun := λ x, ⟨( ⟦ ρ⟧ g ) x, h g x⟩, add := begin intros x y, rw_simp, end, smul := begin intro c, intros x, rw_simp, end }, end open MY_TEST @[RW_REP]lemma restriction_ext (h : stable_sub_module ρ p) (y : p) : (( ⟦ρ⟧ g) y : M ) = (restriction ρ h g y : M) := rfl @[RW_REP]lemma restriction_ext' (h : stable_sub_module ρ p) (y : p) : (restriction ρ h g y : M) = (( ⟦ρ⟧ g) y : M ) := rfl def restriction_equiv (h : stable_sub_module ρ p) (g : G) : (p ≃ p) := { to_fun := (restriction ρ h g), inv_fun := (restriction ρ h g⁻¹), left_inv := begin intros x, apply sub_module.eq_trans', iterate 2 {rw ← restriction_ext}, rw ← comp_apply, apply rmap_inv_apply'', -- rw [← comp_apply,← mul_to_composition_of_linear_map, inv_mul_self, ρ.map_one], -- exact rfl,end, end , right_inv := begin intros x, apply sub_module.eq_trans', iterate 2 {rw ← restriction_ext}, rw ← comp_apply, apply rmap_inv_apply', end } def Restriction (h : stable_sub_module ρ p) (g : G) : p ≃ₗ[R] p := { .. restriction ρ h g, .. restriction_equiv ρ h g} def sub_representation (h : stable_sub_module ρ p) : group_representation G R p := { to_fun := λ g, of_linear_equiv (Restriction ρ h g), map_one' := begin rw units.ext_iff, --- Creer un helper pour la sous structure car c'est chiant ext,rcases x, apply sub_module.eq_trans, rw rmap_one,exact rfl, end, map_mul' := begin intros g1 g2,rw units.ext_iff, ext, rcases x, apply sub_module.eq_trans,rw_simp,rw of_linear_equiv_val, rw rmap_mul, rw comp_apply, exact rfl, end } variables (h : stable_sub_module ρ p) #check sub_representation ρ h notation ρ `/`h := sub_representation ρ h #check ⟦ ρ / h⟧ g @[RW_REP]lemma sub_representation.val (ρ : group_representation G R M) (h : stable_sub_module ρ p)( x : p) : (⟦ρ⟧ g ) x.val = ( ⟦ ρ / h ⟧ g) x := rfl @[RW_REP] lemma rw_sub_module_action_to (ρ : group_representation G R M) (h : stable_sub_module ρ p) (x : p) : (⟦ρ ⟧ g) x = ⟦ρ / h⟧ g x := begin -- rw_simp, --- joke :D exact rfl, end example (ρ : group_representation G R M) (h : stable_sub_module ρ p) (x y : p)(r : R) (g g' : G): true := begin have R : ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' x )+ r • ⟦ ρ ⟧ g ( ⟦ ρ ⟧ g' y ) = ⟦ ρ / h ⟧ (g * g') (x+ r • y), swap, trivial, iterate 2 {rw ← comp_apply}, rw ← rmap_mul,rw ← smul',rw ← linearity,rw_simp, end end stability end group_representation
788a1e3bfc1b61529de19953b831e2b90773daa2
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/nonarchimedean/bases.lean
30d6c47d1dbeb4484b6acb151aaf21be05f4a38d
[ "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
12,529
lean
/- Copyright (c) 2021 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import linear_algebra.bilinear_map import topology.algebra.nonarchimedean.basic import topology.algebra.filter_basis import algebra.module.submodule_pointwise /-! # Neighborhood bases for non-archimedean rings and modules This files contains special families of filter bases on rings and modules that give rise to non-archimedean topologies. The main definition is `ring_subgroups_basis` which is a predicate on a family of additive subgroups of a ring. The predicate ensures there is a topology `ring_subgroups_basis.topology` which is compatible with a ring structure and admits the given family as a basis of neighborhoods of zero. In particular the given subgroups become open subgroups (bundled in `ring_subgroups_basis.open_add_subgroup`) and we get a non-archimedean topological ring (`ring_subgroups_basis.nonarchimedean`). A special case of this construction is given by `submodules_basis` where the subgroups are sub-modules in a commutative algebra. This important example gives rises to the adic topology (studied in its own file). -/ open set filter function lattice add_group_with_zero_nhd open_locale topological_space filter pointwise /-- A family of additive subgroups on a ring `A` is a subgroups basis if it satisfies some axioms ensuring there is a topology on `A` which is compatible with the ring structure and admits this family as a basis of neighborhoods of zero. -/ structure ring_subgroups_basis {A ι : Type*} [ring A] (B : ι → add_subgroup A) : Prop := (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (mul : ∀ i, ∃ j, (B j : set A) * B j ⊆ B i) (left_mul : ∀ x : A, ∀ i, ∃ j, (B j : set A) ⊆ (λ y : A, x*y) ⁻¹' (B i)) (right_mul : ∀ x : A, ∀ i, ∃ j, (B j : set A) ⊆ (λ y : A, y*x) ⁻¹' (B i)) namespace ring_subgroups_basis variables {A ι : Type*} [ring A] lemma of_comm {A ι : Type*} [comm_ring A] (B : ι → add_subgroup A) (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (mul : ∀ i, ∃ j, (B j : set A) * B j ⊆ B i) (left_mul : ∀ x : A, ∀ i, ∃ j, (B j : set A) ⊆ (λ y : A, x*y) ⁻¹' (B i)) : ring_subgroups_basis B := { inter := inter, mul := mul, left_mul := left_mul, right_mul := begin intros x i, cases left_mul x i with j hj, use j, simpa [mul_comm] using hj end } /-- Every subgroups basis on a ring leads to a ring filter basis. -/ def to_ring_filter_basis [nonempty ι] {B : ι → add_subgroup A} (hB : ring_subgroups_basis B) : ring_filter_basis A := { sets := {U | ∃ i, U = B i}, nonempty := by { inhabit ι, exact ⟨B (default ι), default ι, rfl⟩ }, inter_sets := begin rintros _ _ ⟨i, rfl⟩ ⟨j, rfl⟩, cases hB.inter i j with k hk, use [B k, k, rfl, hk] end, zero' := by { rintros _ ⟨i, rfl⟩, exact (B i).zero_mem }, add' := begin rintros _ ⟨i, rfl⟩, use [B i, i, rfl], rintros x ⟨y, z, y_in, z_in, rfl⟩, exact (B i).add_mem y_in z_in end, neg' := begin rintros _ ⟨i, rfl⟩, use [B i, i, rfl], intros x x_in, exact (B i).neg_mem x_in end, conj' := begin rintros x₀ _ ⟨i, rfl⟩, use [B i, i, rfl], simp end, mul' := begin rintros _ ⟨i, rfl⟩, cases hB.mul i with k hk, use [B k, k, rfl, hk] end, mul_left' := begin rintros x₀ _ ⟨i, rfl⟩, cases hB.left_mul x₀ i with k hk, use [B k, k, rfl, hk] end, mul_right' := begin rintros x₀ _ ⟨i, rfl⟩, cases hB.right_mul x₀ i with k hk, use [B k, k, rfl, hk] end } variables [nonempty ι] {B : ι → add_subgroup A} (hB : ring_subgroups_basis B) lemma mem_add_group_filter_basis_iff {V : set A} : V ∈ hB.to_ring_filter_basis.to_add_group_filter_basis ↔ ∃ i, V = B i := iff.rfl lemma mem_add_group_filter_basis (i) : (B i : set A) ∈ hB.to_ring_filter_basis.to_add_group_filter_basis := ⟨i, rfl⟩ /-- The topology defined from a subgroups basis, admitting the given subgroups as a basis of neighborhoods of zero. -/ def topology : topological_space A := hB.to_ring_filter_basis.to_add_group_filter_basis.topology lemma has_basis_nhds_zero : has_basis (@nhds A hB.topology 0) (λ _, true) (λ i, B i) := ⟨begin intros s, rw hB.to_ring_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff, split, { rintro ⟨-, ⟨i, rfl⟩, hi⟩, exact ⟨i, trivial, hi⟩ }, { rintro ⟨i, -, hi⟩, exact ⟨B i, ⟨i, rfl⟩, hi⟩ } end⟩ lemma has_basis_nhds (a : A) : has_basis (@nhds A hB.topology a) (λ _, true) (λ i, {b | b - a ∈ B i}) := ⟨begin intros s, rw (hB.to_ring_filter_basis.to_add_group_filter_basis.nhds_has_basis a).mem_iff, simp only [exists_prop, exists_true_left], split, { rintro ⟨-, ⟨i, rfl⟩, hi⟩, use i, convert hi, ext b, split, { intros h, use [b - a, h], abel }, { rintros ⟨c, hc, rfl⟩, simpa using hc } }, { rintros ⟨i, hi⟩, use [B i, i, rfl], rw image_subset_iff, rintro b b_in, apply hi, simpa using b_in } end⟩ /-- Given a subgroups basis, the basis elements as open additive subgroups in the associated topology. -/ def open_add_subgroup (i : ι) : @open_add_subgroup A _ hB.topology:= { is_open' := begin letI := hB.topology, rw is_open_iff_mem_nhds, intros a a_in, rw (hB.has_basis_nhds a).mem_iff, use [i, trivial], rintros b b_in, simpa using (B i).add_mem a_in b_in end, ..B i } -- see Note [nonarchimedean non instances] lemma nonarchimedean : @nonarchimedean_ring A _ hB.topology := begin letI := hB.topology, constructor, intros U hU, obtain ⟨i, -, hi : (B i : set A) ⊆ U⟩ := hB.has_basis_nhds_zero.mem_iff.mp hU, exact ⟨hB.open_add_subgroup i, hi⟩ end end ring_subgroups_basis variables {ι R A : Type*} [comm_ring R] [comm_ring A] [algebra R A] /-- A family of submodules in a commutative `R`-algebra `A` is a submodules basis if it satisfies some axioms ensuring there is a topology on `A` which is compatible with the ring structure and admits this family as a basis of neighborhoods of zero. -/ structure submodules_ring_basis (B : ι → submodule R A) : Prop := (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (left_mul : ∀ (a : A) i, ∃ j, a • B j ≤ B i) (mul : ∀ i, ∃ j, (B j : set A) * B j ⊆ B i) namespace submodules_ring_basis variables {B : ι → submodule R A} (hB : submodules_ring_basis B) lemma to_ring_subgroups_basis (hB : submodules_ring_basis B) : ring_subgroups_basis (λ i, (B i).to_add_subgroup) := begin apply ring_subgroups_basis.of_comm (λ i, (B i).to_add_subgroup) hB.inter hB.mul, intros a i, rcases hB.left_mul a i with ⟨j, hj⟩, use j, rintros b (b_in : b ∈ B j), exact hj ⟨b, b_in, rfl⟩ end /-- The topology associated to a basis of submodules in an algebra. -/ def topology [nonempty ι] (hB : submodules_ring_basis B) : topological_space A := hB.to_ring_subgroups_basis.topology end submodules_ring_basis variables {M : Type*} [add_comm_group M] [module R M] /-- A family of submodules in an `R`-module `M` is a submodules basis if it satisfies some axioms ensuring there is a topology on `M` which is compatible with the module structure and admits this family as a basis of neighborhoods of zero. -/ structure submodules_basis [topological_space R] (B : ι → submodule R M) : Prop := (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (smul : ∀ (m : M) (i : ι), ∀ᶠ a in 𝓝 (0 : R), a • m ∈ B i) namespace submodules_basis variables [topological_space R] [nonempty ι] {B : ι → submodule R M} (hB : submodules_basis B) include hB /-- The image of a submodules basis is a module filter basis. -/ def to_module_filter_basis : module_filter_basis R M := { sets := {U | ∃ i, U = B i}, nonempty := by { inhabit ι, exact ⟨B (default ι), default ι, rfl⟩ }, inter_sets := begin rintros _ _ ⟨i, rfl⟩ ⟨j, rfl⟩, cases hB.inter i j with k hk, use [B k, k, rfl, hk] end, zero' := by { rintros _ ⟨i, rfl⟩, exact (B i).zero_mem }, add' := begin rintros _ ⟨i, rfl⟩, use [B i, i, rfl], rintros x ⟨y, z, y_in, z_in, rfl⟩, exact (B i).add_mem y_in z_in end, neg' := begin rintros _ ⟨i, rfl⟩, use [B i, i, rfl], intros x x_in, exact (B i).neg_mem x_in end, conj' := begin rintros x₀ _ ⟨i, rfl⟩, use [B i, i, rfl], simp end, smul' := begin rintros _ ⟨i, rfl⟩, use [univ, univ_mem, B i, i, rfl], rintros _ ⟨a, m, -, hm, rfl⟩, exact (B i).smul_mem _ hm end, smul_left' := begin rintros x₀ _ ⟨i, rfl⟩, use [B i, i, rfl], intros m, exact (B i).smul_mem _ end, smul_right' := begin rintros m₀ _ ⟨i, rfl⟩, exact hB.smul m₀ i end } /-- The topology associated to a basis of submodules in a module. -/ def topology : topological_space M := hB.to_module_filter_basis.to_add_group_filter_basis.topology /-- Given a submodules basis, the basis elements as open additive subgroups in the associated topology. -/ def open_add_subgroup (i : ι) : @open_add_subgroup M _ hB.topology := { is_open' := begin letI := hB.topology, rw is_open_iff_mem_nhds, intros a a_in, rw (hB.to_module_filter_basis.to_add_group_filter_basis.nhds_has_basis a).mem_iff, use [B i, i, rfl], rintros - ⟨b, b_in, rfl⟩, exact (B i).add_mem a_in b_in end, ..(B i).to_add_subgroup } -- see Note [nonarchimedean non instances] lemma nonarchimedean (hB : submodules_basis B) : @nonarchimedean_add_group M _ hB.topology:= begin letI := hB.topology, constructor, intros U hU, obtain ⟨-, ⟨i, rfl⟩, hi : (B i : set M) ⊆ U⟩ := hB.to_module_filter_basis.to_add_group_filter_basis.nhds_zero_has_basis.mem_iff.mp hU, exact ⟨hB.open_add_subgroup i, hi⟩ end /-- The non archimedean subgroup basis lemmas cannot be instances because some instances (such as `measure_theory.ae_eq_fun.add_monoid ` or `topological_add_group.to_has_continuous_add`) cause the search for `@topological_add_group β ?m1 ?m2`, i.e. a search for a topological group where the topology/group structure are unknown. -/ library_note "nonarchimedean non instances" end submodules_basis section /- In this section, we check that, in a `R`-algebra `A` over a ring equipped with a topology, a basis of `R`-submodules which is compatible with the topology on `R` is also a submodule basis in the sense of `R`-modules (forgetting about the ring structure on `A`) and those two points of view definitionaly gives the same topology on `A`. -/ variables [topological_space R] {B : ι → submodule R A} (hB : submodules_ring_basis B) (hsmul : ∀ (m : A) (i : ι), ∀ᶠ (a : R) in 𝓝 0, a • m ∈ B i) lemma submodules_ring_basis.to_submodules_basis : submodules_basis B := { inter := hB.inter, smul := hsmul } example [nonempty ι] : hB.topology = (hB.to_submodules_basis hsmul).topology := rfl end /-- Given a ring filter basis on a commutative ring `R`, define a compatibility condition on a family of submodules of a `R`-module `M`. This compatibility condition allows to get a topological module structure. -/ structure ring_filter_basis.submodules_basis (BR : ring_filter_basis R) (B : ι → submodule R M) : Prop := (inter : ∀ i j, ∃ k, B k ≤ B i ⊓ B j) (smul : ∀ (m : M) (i : ι), ∃ U ∈ BR, U ⊆ (λ a, a • m) ⁻¹' B i) lemma ring_filter_basis.submodules_basis_is_basis (BR : ring_filter_basis R) {B : ι → submodule R M} (hB : BR.submodules_basis B) : @submodules_basis ι R _ M _ _ BR.topology B := { inter := hB.inter, smul := begin letI := BR.topology, intros m i, rcases hB.smul m i with ⟨V, V_in, hV⟩, exact mem_of_superset (BR.to_add_group_filter_basis.mem_nhds_zero V_in) hV end } /-- The module filter basis associated to a ring filter basis and a compatible submodule basis. This allows to build a topological module structure compatible with the given module structure and the topology associated to the given ring filter basis. -/ def ring_filter_basis.module_filter_basis [nonempty ι] (BR : ring_filter_basis R) {B : ι → submodule R M} (hB : BR.submodules_basis B) : @module_filter_basis R M _ BR.topology _ _ := @submodules_basis.to_module_filter_basis ι R _ M _ _ BR.topology _ _ (BR.submodules_basis_is_basis hB)
a5e78af85c24c55cb6c5d0c94e34e9b750cc178a
fd3506535396cef3d1bdcf4ae5b87c8ed9ff2c2e
/group_theory/perm.lean
f683d0aa6c44052605b3e60e5f8c8c0b1c9cd803
[ "Apache-2.0" ]
permissive
williamdemeo/leanproved
77933dbcb8bfbae61a753ae31fa669b3ed8cda9d
d8c2e2ca0002b252fce049c4ff9be0e9e83a6374
refs/heads/master
1,598,674,802,432
1,437,528,488,000
1,437,528,488,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,159
lean
/- Copyright (c) 2015 Haitao Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author : Haitao Zhang -/ import algebra.group data data.fintype.function open nat list algebra function namespace group open fintype section perm variable {A : Type} variable [finA : fintype A] include finA variable [deceqA : decidable_eq A] include deceqA variable {f : A → A} lemma perm_surj : injective f → surjective f := surj_of_inj_eq_card (eq.refl (card A)) variable (perm : injective f) definition perm_inv : A → A := right_inv (perm_surj perm) lemma perm_inv_right : f ∘ (perm_inv perm) = id := right_inv_of_surj (perm_surj perm) lemma perm_inv_left : (perm_inv perm) ∘ f = id := have H : left_inverse f (perm_inv perm), from congr_fun (perm_inv_right perm), funext (take x, right_inverse_of_injective_of_left_inverse perm H x) lemma perm_inv_inj : injective (perm_inv perm) := injective_of_has_left_inverse (exists.intro f (congr_fun (perm_inv_right perm))) end perm structure perm (A : Type) [h : fintype A] : Type := (f : A → A) (inj : injective f) local attribute perm.f [coercion] check perm.mk section perm variable {A : Type} variable [finA : fintype A] include finA lemma eq_of_feq : ∀ {p₁ p₂ : perm A}, (perm.f p₁) = p₂ → p₁ = p₂ | (perm.mk f₁ P₁) (perm.mk f₂ P₂) := assume (feq : f₁ = f₂), by congruence; assumption lemma feq_of_eq : ∀ {p₁ p₂ : perm A}, p₁ = p₂ → (perm.f p₁) = p₂ | (perm.mk f₁ P₁) (perm.mk f₂ P₂) := assume Peq, have feq : f₁ = f₂, from perm.no_confusion Peq (λ Pe Pqe, Pe), feq lemma eq_iff_feq {p₁ p₂ : perm A} : (perm.f p₁) = p₂ ↔ p₁ = p₂ := iff.intro eq_of_feq feq_of_eq lemma perm.f_mk {f : A → A} {Pinj : injective f} : perm.f (perm.mk f Pinj) = f := rfl definition move_by [reducible] (a : A) (f : perm A) : A := f a variable [deceqA : decidable_eq A] include deceqA lemma perm.has_decidable_eq [instance] : decidable_eq (perm A) := take f g, perm.destruct f (λ ff finj, perm.destruct g (λ gf ginj, decidable.rec_on (decidable_eq_fun ff gf) (λ Peq, decidable.inl (by substvars)) (λ Pne, decidable.inr begin intro P, injection P, contradiction end))) lemma dinj_perm_mk : dinj (@injective A A) perm.mk := take a₁ a₂ Pa₁ Pa₂ Pmkeq, perm.no_confusion Pmkeq (λ Pe Pqe, Pe) definition all_perms : list (perm A) := dmap injective perm.mk (all_injs A) lemma nodup_all_perms : nodup (@all_perms A _ _) := dmap_nodup_of_dinj dinj_perm_mk nodup_all_injs lemma all_perms_complete : ∀ p : perm A, p ∈ all_perms := take p, perm.destruct p (take f Pinj, assert Pin : f ∈ all_injs A, from all_injs_complete Pinj, mem_dmap Pinj Pin) definition perm_is_fintype [instance] : fintype (perm A) := fintype.mk all_perms nodup_all_perms all_perms_complete definition perm.mul (f g : perm A) := perm.mk (f∘g) (injective_compose (perm.inj f) (perm.inj g)) definition perm.one [reducible] : perm A := perm.mk id injective_id definition perm.inv (f : perm A) := let inj := perm.inj f in perm.mk (perm_inv inj) (perm_inv_inj inj) local infix `^` := perm.mul lemma perm.assoc (f g h : perm A) : f ^ g ^ h = f ^ (g ^ h) := rfl lemma perm.one_mul (p : perm A) : perm.one ^ p = p := perm.cases_on p (λ f inj, rfl) lemma perm.mul_one (p : perm A) : p ^ perm.one = p := perm.cases_on p (λ f inj, rfl) lemma perm.left_inv (p : perm A) : (perm.inv p) ^ p = perm.one := begin rewrite [↑perm.one], generalize @injective_id A, rewrite [-perm_inv_left (perm.inj p)], intros, exact rfl end lemma perm.right_inv (p : perm A) : p ^ (perm.inv p) = perm.one := begin rewrite [↑perm.one], generalize @injective_id A, rewrite [-perm_inv_right (perm.inj p)], intros, exact rfl end definition perm_group [instance] : group (perm A) := group.mk perm.mul perm.assoc perm.one perm.one_mul perm.mul_one perm.inv perm.left_inv lemma perm_one : (1 : perm A) = perm.one := rfl end perm end group
466ab7cd724666d8a372a2859168f4aa77dcd7ac
e4d500be102d7cc2cf7c341f360db71d9125c19b
/src/order/bounds.lean
19d1abe329c988c4ea33d6edc2f478816c1d1c43
[ "Apache-2.0" ]
permissive
mgrabovsky/mathlib
3cbc6c54dab5f277f0abf4195a1b0e6e39b9971f
e397b4c1266ee241e9412e17b1dd8724f56fba09
refs/heads/master
1,664,687,987,155
1,591,255,329,000
1,591,255,329,000
269,361,264
0
0
Apache-2.0
1,591,275,784,000
1,591,275,783,000
null
UTF-8
Lean
false
false
25,612
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, Yury Kudryashov -/ import data.set.intervals.basic /-! # Upper / lower bounds In this file we define: * `upper_bounds`, `lower_bounds` : the set of upper bounds (resp., lower bounds) of a set; * `bdd_above s`, `bdd_below s` : the set `s` is bounded above (resp., below), i.e., the set of upper (resp., lower) bounds of `s` is nonempty; * `is_least s a`, `is_greatest s a` : `a` is a least (resp., greatest) element of `s`; for a partial order, it is unique if exists; * `is_lub s a`, `is_glb s a` : `a` is a least upper bound (resp., a greatest lower bound) of `s`; for a partial order, it is unique if exists. We also prove various lemmas about monotonicity, behaviour under `∪`, `∩`, `insert`, and provide formulas for `∅`, `univ`, and intervals. -/ open set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section variables [preorder α] [preorder β] {s t : set α} {a b : α} /-! ### Definitions -/ /-- The set of upper bounds of a set. -/ def upper_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → a ≤ x } /-- The set of lower bounds of a set. -/ def lower_bounds (s : set α) : set α := { x | ∀ ⦃a⦄, a ∈ s → x ≤ a } /-- A set is bounded above if there exists an upper bound. -/ def bdd_above (s : set α) := (upper_bounds s).nonempty /-- A set is bounded below if there exists a lower bound. -/ def bdd_below (s : set α) := (lower_bounds s).nonempty /-- `a` is a least element of a set `s`; for a partial order, it is unique if exists. -/ def is_least (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ lower_bounds s /-- `a` is a greatest element of a set `s`; for a partial order, it is unique if exists -/ def is_greatest (s : set α) (a : α) : Prop := a ∈ s ∧ a ∈ upper_bounds s /-- `a` is a least upper bound of a set `s`; for a partial order, it is unique if exists. -/ def is_lub (s : set α) : α → Prop := is_least (upper_bounds s) /-- `a` is a greatest lower bound of a set `s`; for a partial order, it is unique if exists. -/ def is_glb (s : set α) : α → Prop := is_greatest (lower_bounds s) lemma mem_upper_bounds : a ∈ upper_bounds s ↔ ∀ x ∈ s, x ≤ a := iff.rfl lemma mem_lower_bounds : a ∈ lower_bounds s ↔ ∀ x ∈ s, a ≤ x := iff.rfl /-! ### Monotonicity -/ lemma upper_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : upper_bounds t ⊆ upper_bounds s := λ b hb x h, hb $ hst h lemma lower_bounds_mono_set ⦃s t : set α⦄ (hst : s ⊆ t) : lower_bounds t ⊆ lower_bounds s := λ b hb x h, hb $ hst h lemma upper_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds s → b ∈ upper_bounds s := λ ha x h, le_trans (ha h) hab lemma lower_bounds_mono_mem ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds s → a ∈ lower_bounds s := λ hb x h, le_trans hab (hb h) lemma upper_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : a ∈ upper_bounds t → b ∈ upper_bounds s := λ ha, upper_bounds_mono_set hst $ upper_bounds_mono_mem hab ha lemma lower_bounds_mono ⦃s t : set α⦄ (hst : s ⊆ t) ⦃a b⦄ (hab : a ≤ b) : b ∈ lower_bounds t → a ∈ lower_bounds s := λ hb, lower_bounds_mono_set hst $ lower_bounds_mono_mem hab hb /-- If `s ⊆ t` and `t` is bounded above, then so is `s`. -/ lemma bdd_above.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_above t → bdd_above s := nonempty.mono $ upper_bounds_mono_set h /-- If `s ⊆ t` and `t` is bounded below, then so is `s`. -/ lemma bdd_below.mono ⦃s t : set α⦄ (h : s ⊆ t) : bdd_below t → bdd_below s := nonempty.mono $ lower_bounds_mono_set h /-- If `a` is a least upper bound for sets `s` and `p`, then it is a least upper bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_lub.of_subset_of_superset {s t p : set α} (hs : is_lub s a) (hp : is_lub p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_lub t a := ⟨upper_bounds_mono_set htp hp.1, lower_bounds_mono_set (upper_bounds_mono_set hst) hs.2⟩ /-- If `a` is a greatest lower bound for sets `s` and `p`, then it is a greater lower bound for any set `t`, `s ⊆ t ⊆ p`. -/ lemma is_glb.of_subset_of_superset {s t p : set α} (hs : is_glb s a) (hp : is_glb p a) (hst : s ⊆ t) (htp : t ⊆ p) : is_glb t a := @is_lub.of_subset_of_superset (order_dual α) _ a s t p hs hp hst htp lemma is_least.mono (ha : is_least s a) (hb : is_least t b) (hst : s ⊆ t) : b ≤ a := hb.2 (hst ha.1) lemma is_greatest.mono (ha : is_greatest s a) (hb : is_greatest t b) (hst : s ⊆ t) : a ≤ b := hb.2 (hst ha.1) lemma is_lub.mono (ha : is_lub s a) (hb : is_lub t b) (hst : s ⊆ t) : a ≤ b := hb.mono ha $ upper_bounds_mono_set hst lemma is_glb.mono (ha : is_glb s a) (hb : is_glb t b) (hst : s ⊆ t) : b ≤ a := hb.mono ha $ lower_bounds_mono_set hst /-! ### Conversions -/ lemma is_least.is_glb (h : is_least s a) : is_glb s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_greatest.is_lub (h : is_greatest s a) : is_lub s a := ⟨h.2, λ b hb, hb h.1⟩ lemma is_lub.upper_bounds_eq (h : is_lub s a) : upper_bounds s = Ici a := set.ext $ λ b, ⟨λ hb, h.2 hb, λ hb, upper_bounds_mono_mem hb h.1⟩ lemma is_glb.lower_bounds_eq (h : is_glb s a) : lower_bounds s = Iic a := @is_lub.upper_bounds_eq (order_dual α) _ _ _ h lemma is_least.lower_bounds_eq (h : is_least s a) : lower_bounds s = Iic a := h.is_glb.lower_bounds_eq lemma is_greatest.upper_bounds_eq (h : is_greatest s a) : upper_bounds s = Ici a := h.is_lub.upper_bounds_eq lemma is_lub_le_iff (h : is_lub s a) : a ≤ b ↔ b ∈ upper_bounds s := by { rw h.upper_bounds_eq, refl } lemma le_is_glb_iff (h : is_glb s a) : b ≤ a ↔ b ∈ lower_bounds s := by { rw h.lower_bounds_eq, refl } /-- If `s` has a least upper bound, then it is bounded above. -/ lemma is_lub.bdd_above (h : is_lub s a) : bdd_above s := ⟨a, h.1⟩ /-- If `s` has a greatest lower bound, then it is bounded below. -/ lemma is_glb.bdd_below (h : is_glb s a) : bdd_below s := ⟨a, h.1⟩ /-- If `s` has a greatest element, then it is bounded above. -/ lemma is_greatest.bdd_above (h : is_greatest s a) : bdd_above s := ⟨a, h.2⟩ /-- If `s` has a least element, then it is bounded below. -/ lemma is_least.bdd_below (h : is_least s a) : bdd_below s := ⟨a, h.2⟩ lemma is_least.nonempty (h : is_least s a) : s.nonempty := ⟨a, h.1⟩ lemma is_greatest.nonempty (h : is_greatest s a) : s.nonempty := ⟨a, h.1⟩ /-! ### Union and intersection -/ @[simp] lemma upper_bounds_union : upper_bounds (s ∪ t) = upper_bounds s ∩ upper_bounds t := subset.antisymm (λ b hb, ⟨λ x hx, hb (or.inl hx), λ x hx, hb (or.inr hx)⟩) (λ b hb x hx, hx.elim (λ hs, hb.1 hs) (λ ht, hb.2 ht)) @[simp] lemma lower_bounds_union : lower_bounds (s ∪ t) = lower_bounds s ∩ lower_bounds t := @upper_bounds_union (order_dual α) _ s t lemma union_upper_bounds_subset_upper_bounds_inter : upper_bounds s ∪ upper_bounds t ⊆ upper_bounds (s ∩ t) := union_subset (upper_bounds_mono_set $ inter_subset_left _ _) (upper_bounds_mono_set $ inter_subset_right _ _) lemma union_lower_bounds_subset_lower_bounds_inter : lower_bounds s ∪ lower_bounds t ⊆ lower_bounds (s ∩ t) := @union_upper_bounds_subset_upper_bounds_inter (order_dual α) _ s t lemma is_least_union_iff {a : α} {s t : set α} : is_least (s ∪ t) a ↔ (is_least s a ∧ a ∈ lower_bounds t ∨ a ∈ lower_bounds s ∧ is_least t a) := by simp [is_least, lower_bounds_union, or_and_distrib_right, and_comm (a ∈ t), and_assoc] lemma is_greatest_union_iff : is_greatest (s ∪ t) a ↔ (is_greatest s a ∧ a ∈ upper_bounds t ∨ a ∈ upper_bounds s ∧ is_greatest t a) := @is_least_union_iff (order_dual α) _ a s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_left (h : bdd_above s) : bdd_above (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_above.inter_of_right (h : bdd_above t) : bdd_above (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_left (h : bdd_below s) : bdd_below (s ∩ t) := h.mono $ inter_subset_left s t /-- If `t` is bounded, then so is `s ∩ t` -/ lemma bdd_below.inter_of_right (h : bdd_below t) : bdd_below (s ∩ t) := h.mono $ inter_subset_right s t /-- If `s` and `t` are bounded above sets in a `semilattice_sup`, then so is `s ∪ t`. -/ lemma bdd_above.union [semilattice_sup γ] {s t : set γ} : bdd_above s → bdd_above t → bdd_above (s ∪ t) := begin rintros ⟨bs, hs⟩ ⟨bt, ht⟩, use bs ⊔ bt, rw upper_bounds_union, exact ⟨upper_bounds_mono_mem le_sup_left hs, upper_bounds_mono_mem le_sup_right ht⟩ end /-- The union of two sets is bounded above if and only if each of the sets is. -/ lemma bdd_above_union [semilattice_sup γ] {s t : set γ} : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t := ⟨λ h, ⟨h.mono $ subset_union_left s t, h.mono $ subset_union_right s t⟩, λ h, h.1.union h.2⟩ lemma bdd_below.union [semilattice_inf γ] {s t : set γ} : bdd_below s → bdd_below t → bdd_below (s ∪ t) := @bdd_above.union (order_dual γ) _ s t /--The union of two sets is bounded above if and only if each of the sets is.-/ lemma bdd_below_union [semilattice_inf γ] {s t : set γ} : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t := @bdd_above_union (order_dual γ) _ s t /-- If `a` is the least upper bound of `s` and `b` is the least upper bound of `t`, then `a ⊔ b` is the least upper bound of `s ∪ t`. -/ lemma is_lub.union [semilattice_sup γ] {a b : γ} {s t : set γ} (hs : is_lub s a) (ht : is_lub t b) : is_lub (s ∪ t) (a ⊔ b) := ⟨assume c h, h.cases_on (λ h, le_sup_left_of_le $ hs.left h) (λ h, le_sup_right_of_le $ ht.left h), assume c hc, sup_le (hs.right $ assume d hd, hc $ or.inl hd) (ht.right $ assume d hd, hc $ or.inr hd)⟩ /-- If `a` is the greatest lower bound of `s` and `b` is the greatest lower bound of `t`, then `a ⊓ b` is the greatest lower bound of `s ∪ t`. -/ lemma is_glb.union [semilattice_inf γ] {a₁ a₂ : γ} {s t : set γ} (hs : is_glb s a₁) (ht : is_glb t a₂) : is_glb (s ∪ t) (a₁ ⊓ a₂) := @is_lub.union (order_dual γ) _ _ _ _ _ hs ht /-- If `a` is the least element of `s` and `b` is the least element of `t`, then `min a b` is the least element of `s ∪ t`. -/ lemma is_least.union [decidable_linear_order γ] {a b : γ} {s t : set γ} (ha : is_least s a) (hb : is_least t b) : is_least (s ∪ t) (min a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_glb.union hb.is_glb).1⟩ /-- If `a` is the greatest element of `s` and `b` is the greatest element of `t`, then `max a b` is the greatest element of `s ∪ t`. -/ lemma is_greatest.union [decidable_linear_order γ] {a b : γ} {s t : set γ} (ha : is_greatest s a) (hb : is_greatest t b) : is_greatest (s ∪ t) (max a b) := ⟨by cases (le_total a b) with h h; simp [h, ha.1, hb.1], (ha.is_lub.union hb.is_lub).1⟩ /-! ### Specific sets #### Unbounded intervals -/ lemma is_least_Ici : is_least (Ici a) a := ⟨left_mem_Ici, λ x, id⟩ lemma is_greatest_Iic : is_greatest (Iic a) a := ⟨right_mem_Iic, λ x, id⟩ lemma is_lub_Iic : is_lub (Iic a) a := is_greatest_Iic.is_lub lemma is_glb_Ici : is_glb (Ici a) a := is_least_Ici.is_glb lemma upper_bounds_Iic : upper_bounds (Iic a) = Ici a := is_lub_Iic.upper_bounds_eq lemma lower_bounds_Ici : lower_bounds (Ici a) = Iic a := is_glb_Ici.lower_bounds_eq lemma bdd_above_Iic : bdd_above (Iic a) := is_lub_Iic.bdd_above lemma bdd_below_Ici : bdd_below (Ici a) := is_glb_Ici.bdd_below lemma bdd_above_Iio : bdd_above (Iio a) := ⟨a, λ x hx, le_of_lt hx⟩ lemma bdd_below_Ioi : bdd_below (Ioi a) := ⟨a, λ x hx, le_of_lt hx⟩ section variables [linear_order γ] [densely_ordered γ] lemma is_lub_Iio {a : γ} : is_lub (Iio a) a := ⟨λ x hx, le_of_lt hx, λ y hy, le_of_forall_ge_of_dense hy⟩ lemma is_glb_Ioi {a : γ} : is_glb (Ioi a) a := @is_lub_Iio (order_dual γ) _ _ a lemma upper_bounds_Iio {a : γ} : upper_bounds (Iio a) = Ici a := is_lub_Iio.upper_bounds_eq lemma lower_bounds_Ioi {a : γ} : lower_bounds (Ioi a) = Iic a := is_glb_Ioi.lower_bounds_eq end /-! #### Singleton -/ lemma is_greatest_singleton : is_greatest {a} a := ⟨mem_singleton a, λ x hx, le_of_eq $ eq_of_mem_singleton hx⟩ lemma is_least_singleton : is_least {a} a := @is_greatest_singleton (order_dual α) _ a lemma is_lub_singleton : is_lub {a} a := is_greatest_singleton.is_lub lemma is_glb_singleton : is_glb {a} a := is_least_singleton.is_glb lemma bdd_above_singleton : bdd_above ({a} : set α) := is_lub_singleton.bdd_above lemma bdd_below_singleton : bdd_below ({a} : set α) := is_glb_singleton.bdd_below @[simp] lemma upper_bounds_singleton : upper_bounds {a} = Ici a := is_lub_singleton.upper_bounds_eq @[simp] lemma lower_bounds_singleton : lower_bounds {a} = Iic a := is_glb_singleton.lower_bounds_eq /-! #### Bounded intervals -/ lemma bdd_above_Icc : bdd_above (Icc a b) := ⟨b, λ _, and.right⟩ lemma bdd_above_Ico : bdd_above (Ico a b) := bdd_above_Icc.mono Ico_subset_Icc_self lemma bdd_above_Ioc : bdd_above (Ioc a b) := bdd_above_Icc.mono Ioc_subset_Icc_self lemma bdd_above_Ioo : bdd_above (Ioo a b) := bdd_above_Icc.mono Ioo_subset_Icc_self lemma is_greatest_Icc (h : a ≤ b) : is_greatest (Icc a b) b := ⟨right_mem_Icc.2 h, λ x, and.right⟩ lemma is_lub_Icc (h : a ≤ b) : is_lub (Icc a b) b := (is_greatest_Icc h).is_lub lemma upper_bounds_Icc (h : a ≤ b) : upper_bounds (Icc a b) = Ici b := (is_lub_Icc h).upper_bounds_eq lemma is_least_Icc (h : a ≤ b) : is_least (Icc a b) a := ⟨left_mem_Icc.2 h, λ x, and.left⟩ lemma is_glb_Icc (h : a ≤ b) : is_glb (Icc a b) a := (is_least_Icc h).is_glb lemma lower_bounds_Icc (h : a ≤ b) : lower_bounds (Icc a b) = Iic a := (is_glb_Icc h).lower_bounds_eq lemma is_greatest_Ioc (h : a < b) : is_greatest (Ioc a b) b := ⟨right_mem_Ioc.2 h, λ x, and.right⟩ lemma is_lub_Ioc (h : a < b) : is_lub (Ioc a b) b := (is_greatest_Ioc h).is_lub lemma upper_bounds_Ioc (h : a < b) : upper_bounds (Ioc a b) = Ici b := (is_lub_Ioc h).upper_bounds_eq lemma is_least_Ico (h : a < b) : is_least (Ico a b) a := ⟨left_mem_Ico.2 h, λ x, and.left⟩ lemma is_glb_Ico (h : a < b) : is_glb (Ico a b) a := (is_least_Ico h).is_glb lemma lower_bounds_Ico (h : a < b) : lower_bounds (Ico a b) = Iic a := (is_glb_Ico h).lower_bounds_eq section variables [linear_order γ] [densely_ordered γ] lemma is_glb_Ioo {a b : γ} (hab : a < b) : is_glb (Ioo a b) a := begin refine ⟨λx hx, le_of_lt hx.1, λy hy, le_of_not_lt $ λ h, _⟩, letI := classical.DLO γ, have : a < min b y, by { rw lt_min_iff, exact ⟨hab, h⟩ }, rcases dense this with ⟨z, az, zy⟩, rw lt_min_iff at zy, exact lt_irrefl _ (lt_of_le_of_lt (hy ⟨az, zy.1⟩) zy.2) end lemma lower_bounds_Ioo {a b : γ} (hab : a < b) : lower_bounds (Ioo a b) = Iic a := (is_glb_Ioo hab).lower_bounds_eq lemma is_glb_Ioc {a b : γ} (hab : a < b) : is_glb (Ioc a b) a := (is_glb_Ioo hab).of_subset_of_superset (is_glb_Icc $ le_of_lt hab) Ioo_subset_Ioc_self Ioc_subset_Icc_self lemma lower_bound_Ioc {a b : γ} (hab : a < b) : lower_bounds (Ioc a b) = Iic a := (is_glb_Ioc hab).lower_bounds_eq lemma is_lub_Ioo {a b : γ} (hab : a < b) : is_lub (Ioo a b) b := by simpa only [dual_Ioo] using @is_glb_Ioo (order_dual γ) _ _ b a hab lemma upper_bounds_Ioo {a b : γ} (hab : a < b) : upper_bounds (Ioo a b) = Ici b := (is_lub_Ioo hab).upper_bounds_eq lemma is_lub_Ico {a b : γ} (hab : a < b) : is_lub (Ico a b) b := by simpa only [dual_Ioc] using @is_glb_Ioc (order_dual γ) _ _ b a hab lemma upper_bounds_Ico {a b : γ} (hab : a < b) : upper_bounds (Ico a b) = Ici b := (is_lub_Ico hab).upper_bounds_eq end lemma bdd_below_iff_subset_Ici : bdd_below s ↔ ∃ a, s ⊆ Ici a := iff.rfl lemma bdd_above_iff_subset_Iic : bdd_above s ↔ ∃ a, s ⊆ Iic a := iff.rfl lemma bdd_below_bdd_above_iff_subset_Icc : bdd_below s ∧ bdd_above s ↔ ∃ a b, s ⊆ Icc a b := by simp only [Ici_inter_Iic.symm, subset_inter_iff, bdd_below_iff_subset_Ici, bdd_above_iff_subset_Iic, exists_and_distrib_left, exists_and_distrib_right] /-! ### Univ -/ lemma order_top.upper_bounds_univ [order_top γ] : upper_bounds (univ : set γ) = {⊤} := set.ext $ λ b, iff.trans ⟨λ hb, top_unique $ hb trivial, λ hb x hx, hb.symm ▸ le_top⟩ mem_singleton_iff.symm lemma is_greatest_univ [order_top γ] : is_greatest (univ : set γ) ⊤ := by simp only [is_greatest, order_top.upper_bounds_univ, mem_univ, mem_singleton, true_and] lemma is_lub_univ [order_top γ] : is_lub (univ : set γ) ⊤ := is_greatest_univ.is_lub lemma order_bot.lower_bounds_univ [order_bot γ] : lower_bounds (univ : set γ) = {⊥} := @order_top.upper_bounds_univ (order_dual γ) _ lemma is_least_univ [order_bot γ] : is_least (univ : set γ) ⊥ := @is_greatest_univ (order_dual γ) _ lemma is_glb_univ [order_bot γ] : is_glb (univ : set γ) ⊥ := is_least_univ.is_glb lemma no_top_order.upper_bounds_univ [no_top_order α] : upper_bounds (univ : set α) = ∅ := eq_empty_of_subset_empty $ λ b hb, let ⟨x, hx⟩ := no_top b in not_le_of_lt hx (hb trivial) lemma no_bot_order.lower_bounds_univ [no_bot_order α] : lower_bounds (univ : set α) = ∅ := @no_top_order.upper_bounds_univ (order_dual α) _ _ /-! ### Empty set -/ @[simp] lemma upper_bounds_empty : upper_bounds (∅ : set α) = univ := by simp only [upper_bounds, eq_univ_iff_forall, mem_set_of_eq, ball_empty_iff, forall_true_iff] @[simp] lemma lower_bounds_empty : lower_bounds (∅ : set α) = univ := @upper_bounds_empty (order_dual α) _ @[simp] lemma bdd_above_empty [nonempty α] : bdd_above (∅ : set α) := by simp only [bdd_above, upper_bounds_empty, univ_nonempty] @[simp] lemma bdd_below_empty [nonempty α] : bdd_below (∅ : set α) := by simp only [bdd_below, lower_bounds_empty, univ_nonempty] lemma is_glb_empty [order_top γ] : is_glb ∅ (⊤:γ) := by simp only [is_glb, lower_bounds_empty, is_greatest_univ] lemma is_lub_empty [order_bot γ] : is_lub ∅ (⊥:γ) := @is_glb_empty (order_dual γ) _ lemma is_lub.nonempty [no_bot_order α] (hs : is_lub s a) : s.nonempty := let ⟨a', ha'⟩ := no_bot a in ne_empty_iff_nonempty.1 $ assume h, have a ≤ a', from hs.right $ by simp only [h, upper_bounds_empty], not_le_of_lt ha' this lemma is_glb.nonempty [no_top_order α] (hs : is_glb s a) : s.nonempty := @is_lub.nonempty (order_dual α) _ _ _ _ hs /-! ### insert -/ /-- Adding a point to a set preserves its boundedness above. -/ @[simp] lemma bdd_above_insert [semilattice_sup γ] (a : γ) {s : set γ} : bdd_above (insert a s) ↔ bdd_above s := by simp only [insert_eq, bdd_above_union, bdd_above_singleton, true_and] lemma bdd_above.insert [semilattice_sup γ] (a : γ) {s : set γ} (hs : bdd_above s) : bdd_above (insert a s) := (bdd_above_insert a).2 hs /--Adding a point to a set preserves its boundedness below.-/ @[simp] lemma bdd_below_insert [semilattice_inf γ] (a : γ) {s : set γ} : bdd_below (insert a s) ↔ bdd_below s := by simp only [insert_eq, bdd_below_union, bdd_below_singleton, true_and] lemma bdd_below.insert [semilattice_inf γ] (a : γ) {s : set γ} (hs : bdd_below s) : bdd_below (insert a s) := (bdd_below_insert a).2 hs lemma is_lub.insert [semilattice_sup γ] (a) {b} {s : set γ} (hs : is_lub s b) : is_lub (insert a s) (a ⊔ b) := by { rw insert_eq, exact is_lub_singleton.union hs } lemma is_glb.insert [semilattice_inf γ] (a) {b} {s : set γ} (hs : is_glb s b) : is_glb (insert a s) (a ⊓ b) := by { rw insert_eq, exact is_glb_singleton.union hs } lemma is_greatest.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_greatest s b) : is_greatest (insert a s) (max a b) := by { rw insert_eq, exact is_greatest_singleton.union hs } lemma is_least.insert [decidable_linear_order γ] (a) {b} {s : set γ} (hs : is_least s b) : is_least (insert a s) (min a b) := by { rw insert_eq, exact is_least_singleton.union hs } @[simp] lemma upper_bounds_insert (a : α) (s : set α) : upper_bounds (insert a s) = Ici a ∩ upper_bounds s := by rw [insert_eq, upper_bounds_union, upper_bounds_singleton] @[simp] lemma lower_bounds_insert (a : α) (s : set α) : lower_bounds (insert a s) = Iic a ∩ lower_bounds s := by rw [insert_eq, lower_bounds_union, lower_bounds_singleton] /-- When there is a global maximum, every set is bounded above. -/ @[simp] protected lemma order_top.bdd_above [order_top γ] (s : set γ) : bdd_above s := ⟨⊤, assume a ha, order_top.le_top a⟩ /-- When there is a global minimum, every set is bounded below. -/ @[simp] protected lemma order_bot.bdd_below [order_bot γ] (s : set γ) : bdd_below s := ⟨⊥, assume a ha, order_bot.bot_le a⟩ /-! ### Pair -/ lemma is_lub_pair [semilattice_sup γ] {a b : γ} : is_lub {a, b} (a ⊔ b) := is_lub_singleton.insert _ lemma is_glb_pair [semilattice_inf γ] {a b : γ} : is_glb {a, b} (a ⊓ b) := is_glb_singleton.insert _ lemma is_least_pair [decidable_linear_order γ] {a b : γ} : is_least {a, b} (min a b) := is_least_singleton.insert _ lemma is_greatest_pair [decidable_linear_order γ] {a b : γ} : is_greatest {a, b} (max a b) := is_greatest_singleton.insert _ end /-! ### (In)equalities with the least upper bound and the greatest lower bound -/ section preorder variables [preorder α] {s : set α} {a b : α} lemma lower_bounds_le_upper_bounds (ha : a ∈ lower_bounds s) (hb : b ∈ upper_bounds s) : s.nonempty → a ≤ b | ⟨c, hc⟩ := le_trans (ha hc) (hb hc) lemma is_glb_le_is_lub (ha : is_glb s a) (hb : is_lub s b) (hs : s.nonempty) : a ≤ b := lower_bounds_le_upper_bounds ha.1 hb.1 hs lemma is_lub_lt_iff (ha : is_lub s a) : a < b ↔ ∃ c ∈ upper_bounds s, c < b := ⟨λ hb, ⟨a, ha.1, hb⟩, λ ⟨c, hcs, hcb⟩, lt_of_le_of_lt (ha.2 hcs) hcb⟩ lemma lt_is_glb_iff (ha : is_glb s a) : b < a ↔ ∃ c ∈ lower_bounds s, b < c := @is_lub_lt_iff (order_dual α) _ s _ _ ha end preorder section partial_order variables [partial_order α] {s : set α} {a b : α} lemma is_least.unique (Ha : is_least s a) (Hb : is_least s b) : a = b := le_antisymm (Ha.right Hb.left) (Hb.right Ha.left) lemma is_least.is_least_iff_eq (Ha : is_least s a) : is_least s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_greatest.unique (Ha : is_greatest s a) (Hb : is_greatest s b) : a = b := le_antisymm (Hb.right Ha.left) (Ha.right Hb.left) lemma is_greatest.is_greatest_iff_eq (Ha : is_greatest s a) : is_greatest s b ↔ a = b := iff.intro Ha.unique (assume h, h ▸ Ha) lemma is_lub.unique (Ha : is_lub s a) (Hb : is_lub s b) : a = b := Ha.unique Hb lemma is_glb.unique (Ha : is_glb s a) (Hb : is_glb s b) : a = b := Ha.unique Hb end partial_order section linear_order variables [linear_order α] {s : set α} {a b : α} lemma lt_is_lub_iff (h : is_lub s a) : b < a ↔ ∃ c ∈ s, b < c := by haveI := classical.dec; simpa [upper_bounds, not_ball] using not_congr (@is_lub_le_iff _ _ _ _ b h) lemma is_glb_lt_iff (h : is_glb s a) : a < b ↔ ∃ c ∈ s, c < b := @lt_is_lub_iff (order_dual α) _ _ _ _ h end linear_order /-! ### Images of upper/lower bounds under monotone functions -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} (Hf : monotone f) {a : α} {s : set α} lemma mem_upper_bounds_image (Ha : a ∈ upper_bounds s) : f a ∈ upper_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) lemma mem_lower_bounds_image (Ha : a ∈ lower_bounds s) : f a ∈ lower_bounds (f '' s) := ball_image_of_ball (assume x H, Hf (Ha ‹x ∈ s›)) /-- The image under a monotone function of a set which is bounded above is bounded above. -/ lemma map_bdd_above (hf : monotone f) : bdd_above s → bdd_above (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_upper_bounds_image hC⟩ /-- The image under a monotone function of a set which is bounded below is bounded below. -/ lemma map_bdd_below (hf : monotone f) : bdd_below s → bdd_below (f '' s) | ⟨C, hC⟩ := ⟨f C, hf.mem_lower_bounds_image hC⟩ /-- A monotone map sends a least element of a set to a least element of its image. -/ lemma map_is_least (Ha : is_least s a) : is_least (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_lower_bounds_image Ha.2⟩ /-- A monotone map sends a greatest element of a set to a greatest element of its image. -/ lemma map_is_greatest (Ha : is_greatest s a) : is_greatest (f '' s) (f a) := ⟨mem_image_of_mem _ Ha.1, Hf.mem_upper_bounds_image Ha.2⟩ lemma is_lub_image_le (Ha : is_lub s a) {b : β} (Hb : is_lub (f '' s) b) : b ≤ f a := Hb.2 (Hf.mem_upper_bounds_image Ha.1) lemma le_is_glb_image (Ha : is_glb s a) {b : β} (Hb : is_glb (f '' s) b) : f a ≤ b := Hb.2 (Hf.mem_lower_bounds_image Ha.1) end monotone lemma is_glb.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_glb (f '' s) (f x)) : is_glb s x := ⟨λ y hy, hf.1 $ hx.1 $ mem_image_of_mem _ hy, λ y hy, hf.1 $ hx.2 $ monotone.mem_lower_bounds_image (λ x y, hf.2) hy⟩ lemma is_lub.of_image [preorder α] [preorder β] {f : α → β} (hf : ∀ {x y}, f x ≤ f y ↔ x ≤ y) {s : set α} {x : α} (hx : is_lub (f '' s) (f x)) : is_lub s x := @is_glb.of_image (order_dual α) (order_dual β) _ _ f (λ x y, hf) _ _ hx
d9a024eb514be446e255aadd73a1040d22fbaed3
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/init/equiv.hlean
0c9158419a882ea890f130a7001ed0877df7ea26
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
16,870
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [reducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing_only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B} -- The variant of mk' where f is explicit. protected abbreviation mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) abstract (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) end abstract (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) end abstract (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹) end -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) private definition adjointify_left_inv' (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a private theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, show ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ := adjointify f⁻¹ f (left_inv f) (right_inv f) definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y theorem ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := begin rewrite [↑eq_of_fn_eq_fn',+ap_con,ap_inv,-+adj,-ap_compose,con.assoc, ap_con_eq_con_ap (right_inv f) q,inv_con_cancel_left,ap_id], end definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) abstract (λq, !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) end abstract (λp, whisker_right (whisker_left _ (ap_compose f⁻¹ f _)⁻¹) _ ⬝ con_ap_con_eq_con_con (left_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) end -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (λa, eq.cancel_right (left_inv f (id a)) (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b end section variables {A B C : Type} {f : A → B} [Hf : is_equiv f] {a : A} {b : B} {g : B → C} {h : A → C} include Hf --Rewrite rules definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ variable (f) definition homotopy_of_homotopy_inv' (p : g ~ h ∘ f⁻¹) : g ∘ f ~ h := λa, p (f a) ⬝ ap h (left_inv f a) definition homotopy_of_inv_homotopy' (p : h ∘ f⁻¹ ~ g) : h ~ g ∘ f := λa, ap h (left_inv f a)⁻¹ ⬝ p (f a) definition inv_homotopy_of_homotopy' (p : h ~ g ∘ f) : h ∘ f⁻¹ ~ g := λb, p (f⁻¹ b) ⬝ ap g (right_inv f b) definition homotopy_inv_of_homotopy' (p : g ∘ f ~ h) : g ~ h ∘ f⁻¹ := λb, ap g (right_inv f b)⁻¹ ⬝ p (f⁻¹ b) end --Transporting is an equivalence definition is_equiv_tr [constructor] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) section variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' end end is_equiv open is_equiv namespace eq local attribute is_equiv_tr [instance] definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq infix ` ≃ `:25 := equiv attribute equiv.to_is_equiv [instance] namespace equiv attribute to_fun [coercion] section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition refl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition symm [symm] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl ` ⬝e `:75 := equiv.trans postfix `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.refl definition to_inv_trans [reducible] [unfold_full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : P a ≃ P b := equiv.mk (transport P p) !is_equiv_tr definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A ≃ B := equiv.mk (cast p) !is_equiv_tr definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := equiv_of_eq p ⬝e q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := p ⬝e equiv_of_eq q definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) end section variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a) {g : A → A} {g' : A → A} (h : Π{a}, B (g' a) → B (g a)) (h' : Π{a}, C (g' a) → C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B (g' a)), f (h b) = h' (f b)) {a : A} (c : C (g' a)) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C (g' a)), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B (g' a)) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b end section variables {A B C : Type} (f : A ≃ B) {a : A} {b : B} {g : B → C} {h : A → C} definition homotopy_of_homotopy_inv (p : g ~ h ∘ f⁻¹) : g ∘ f ~ h := homotopy_of_homotopy_inv' f p definition homotopy_of_inv_homotopy (p : h ∘ f⁻¹ ~ g) : h ~ g ∘ f := homotopy_of_inv_homotopy' f p definition inv_homotopy_of_homotopy (p : h ~ g ∘ f) : h ∘ f⁻¹ ~ g := inv_homotopy_of_homotopy' f p definition homotopy_inv_of_homotopy (p : g ∘ f ~ h) : g ~ h ∘ f⁻¹ := homotopy_inv_of_homotopy' f p end infixl ` ⬝pe `:75 := equiv_of_equiv_of_eq infixl ` ⬝ep `:75 := equiv_of_eq_of_equiv end equiv open equiv namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := homotopy_closed f Hty end is_equiv export [unfold] equiv export [unfold] is_equiv
62d66bd9d4dac3749602865313ea8c110a9d3002
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/ring_theory/power_series.lean
cf91c24219064a89c3ca0564f51d4913d0b595ed
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
58,300
lean
/- Copyright (c) 2019 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Kenny Lau -/ import data.finsupp order.complete_lattice algebra.ordered_group data.mv_polynomial import algebra.order_functions import ring_theory.ideal_operations /-! # Formal power series This file defines (multivariate) formal power series and develops the basic properties of these objects. A formal power series is to a polynomial like an infinite sum is to a finite sum. We provide the natural inclusion from polynomials to formal power series. ## Generalities The file starts with setting up the (semi)ring structure on multivariate power series. `trunc n φ` truncates a formal power series to the polynomial that has the same coefficients as φ, for all m ≤ n, and 0 otherwise. If the constant coefficient of a formal power series is invertible, then this formal power series is invertible. Formal power series over a local ring form a local ring. ## Formal power series in one variable We prove that if the ring of coefficients is an integral domain, then formal power series in one variable form an integral domain. The `order` of a formal power series `φ` is the multiplicity of the variable `X` in `φ`. If the coefficients form an integral domain, then `order` is a valuation (`order_mul`, `order_add_ge`). ## Implementation notes In this file we define multivariate formal power series with variables indexed by `σ` and coefficients in `α` as mv_power_series σ α := (σ →₀ ℕ) → α. Unfortunately there is not yet enough API to show that they are the completion of the ring of multivariate polynomials. However, we provide most of the infrastructure that is needed to do this. Once I-adic completion (topological or algebraic) is available it should not be hard to fill in the details. Formal power series in one variable are defined as power_series α := mv_power_series unit α. This allows us to port a lot of proofs and properties from the multivariate case to the single variable case. However, it means that formal power series are indexed by (unit →₀ ℕ), which is of course canonically isomorphic to ℕ. We then build some glue to treat formal power series as if they are indexed by ℕ. Occasionally this leads to proofs that are uglier than expected. -/ noncomputable theory open_locale classical /-- Multivariate formal power series, where `σ` is the index set of the variables and `α` is the coefficient ring.-/ def mv_power_series (σ : Type*) (α : Type*) := (σ →₀ ℕ) → α namespace mv_power_series open finsupp variables {σ : Type*} {α : Type*} instance [inhabited α] : inhabited (mv_power_series σ α) := ⟨λ _, default _⟩ instance [has_zero α] : has_zero (mv_power_series σ α) := pi.has_zero instance [add_monoid α] : add_monoid (mv_power_series σ α) := pi.add_monoid instance [add_group α] : add_group (mv_power_series σ α) := pi.add_group instance [add_comm_monoid α] : add_comm_monoid (mv_power_series σ α) := pi.add_comm_monoid instance [add_comm_group α] : add_comm_group (mv_power_series σ α) := pi.add_comm_group section add_monoid variables [add_monoid α] variables (α) /-- The `n`th monomial with coefficient `a` as multivariate formal power series.-/ def monomial (n : σ →₀ ℕ) : α →+ mv_power_series σ α := { to_fun := λ a m, if m = n then a else 0, map_zero' := funext $ λ m, by { split_ifs; refl }, map_add' := λ a b, funext $ λ m, show (if m = n then a + b else 0) = (if m = n then a else 0) + (if m = n then b else 0), from if h : m = n then by simp only [if_pos h] else by simp only [if_neg h, add_zero] } /-- The `n`th coefficient of a multivariate formal power series.-/ def coeff (n : σ →₀ ℕ) : (mv_power_series σ α) →+ α := { to_fun := λ φ, φ n, map_zero' := rfl, map_add' := λ _ _, rfl } variables {α} /-- Two multivariate formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ} (h : ∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) : φ = ψ := funext h /-- Two multivariate formal power series are equal if and only if all their coefficients are equal.-/ lemma ext_iff {φ ψ : mv_power_series σ α} : φ = ψ ↔ (∀ (n : σ →₀ ℕ), coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ lemma coeff_monomial (m n : σ →₀ ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := rfl @[simp] lemma coeff_monomial' (n : σ →₀ ℕ) (a : α) : coeff α n (monomial α n a) = a := if_pos rfl @[simp] lemma coeff_comp_monomial (n : σ →₀ ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n @[simp] lemma coeff_zero (n : σ →₀ ℕ) : coeff α n (0 : mv_power_series σ α) = 0 := rfl end add_monoid section semiring variables [semiring α] (n : σ →₀ ℕ) (φ ψ : mv_power_series σ α) instance : has_one (mv_power_series σ α) := ⟨monomial α (0 : σ →₀ ℕ) 1⟩ lemma coeff_one : coeff α n (1 : mv_power_series σ α) = if n = 0 then 1 else 0 := rfl @[simp, priority 1100] lemma coeff_zero_one : coeff α (0 : σ →₀ ℕ) 1 = 1 := coeff_monomial' 0 1 instance : has_mul (mv_power_series σ α) := ⟨λ φ ψ n, (finsupp.antidiagonal n).support.sum (λ p, φ p.1 * ψ p.2)⟩ lemma coeff_mul : coeff α n (φ * ψ) = (finsupp.antidiagonal n).support.sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := rfl protected lemma zero_mul : (0 : mv_power_series σ α) * φ = 0 := ext $ λ n, by simp [coeff_mul] protected lemma mul_zero : φ * 0 = 0 := ext $ λ n, by simp [coeff_mul] protected lemma one_mul : (1 : mv_power_series σ α) * φ = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single ((0 : σ →₀ ℕ), n)]; simp [mem_antidiagonal_support, coeff_one], show ∀ (i j : σ →₀ ℕ), i + j = n → (i = 0 → j ≠ n) → (if i = 0 then coeff α j φ else 0) = 0, intros i j hij h, rw [if_neg], contrapose! h, simpa [h] using hij, end protected lemma mul_one : φ * 1 = φ := ext $ λ n, begin rw [coeff_mul, finset.sum_eq_single (n, (0 : σ →₀ ℕ))], rotate, { rintros ⟨i, j⟩ hij h, rw [coeff_one, if_neg, mul_zero], rw mem_antidiagonal_support at hij, contrapose! h, simpa [h] using hij }, all_goals { simp [mem_antidiagonal_support, coeff_one] } end protected lemma mul_add (φ₁ φ₂ φ₃ : mv_power_series σ α) : φ₁ * (φ₂ + φ₃) = φ₁ * φ₂ + φ₁ * φ₃ := ext $ λ n, by simp only [coeff_mul, mul_add, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma add_mul (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ + φ₂) * φ₃ = φ₁ * φ₃ + φ₂ * φ₃ := ext $ λ n, by simp only [coeff_mul, add_mul, finset.sum_add_distrib, add_monoid_hom.map_add] protected lemma mul_assoc (φ₁ φ₂ φ₃ : mv_power_series σ α) : (φ₁ * φ₂) * φ₃ = φ₁ * (φ₂ * φ₃) := ext $ λ n, begin simp only [coeff_mul], have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.1)).support) (λ x, coeff α x.2.1 φ₁ * coeff α x.2.2 φ₂ * coeff α x.1.2 φ₃), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, exact finset.sum_mul }, have := @finset.sum_sigma ((σ →₀ ℕ) × (σ →₀ ℕ)) α _ _ (antidiagonal n).support (λ p, (antidiagonal (p.2)).support) (λ x, coeff α x.1.1 φ₁ * (coeff α x.2.1 φ₂ * coeff α x.2.2 φ₃)), convert this.symm using 1; clear this, { apply finset.sum_congr rfl, intros p hp, rw finset.mul_sum }, apply finset.sum_bij, swap 5, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, exact ⟨(k, l+j), (l, j)⟩ }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, rw mul_assoc }, { rintros ⟨⟨a,b⟩, ⟨c,d⟩⟩ ⟨⟨i,j⟩, ⟨k,l⟩⟩ H₁ H₂, simp only [finset.mem_sigma, mem_antidiagonal_support, and_imp, prod.mk.inj_iff, add_comm, heq_iff_eq] at H₁ H₂ ⊢, finish }, { rintros ⟨⟨i,j⟩, ⟨k,l⟩⟩ H, refine ⟨⟨(i+k, l), (i, k)⟩, _, _⟩; { simp only [finset.mem_sigma, mem_antidiagonal_support] at H ⊢, finish } } end instance : semiring (mv_power_series σ α) := { mul_one := mv_power_series.mul_one, one_mul := mv_power_series.one_mul, mul_assoc := mv_power_series.mul_assoc, mul_zero := mv_power_series.mul_zero, zero_mul := mv_power_series.zero_mul, left_distrib := mv_power_series.mul_add, right_distrib := mv_power_series.add_mul, .. mv_power_series.has_one, .. mv_power_series.has_mul, .. mv_power_series.add_comm_monoid } end semiring instance [comm_semiring α] : comm_semiring (mv_power_series σ α) := { mul_comm := λ φ ψ, ext $ λ n, finset.sum_bij (λ p hp, p.swap) (λ p hp, swap_mem_antidiagonal_support hp) (λ p hp, mul_comm _ _) (λ p q hp hq H, by simpa using congr_arg prod.swap H) (λ p hp, ⟨p.swap, swap_mem_antidiagonal_support hp, p.swap_swap.symm⟩), .. mv_power_series.semiring } instance [ring α] : ring (mv_power_series σ α) := { .. mv_power_series.semiring, .. mv_power_series.add_comm_group } instance [comm_ring α] : comm_ring (mv_power_series σ α) := { .. mv_power_series.comm_semiring, .. mv_power_series.add_comm_group } section semiring variables [semiring α] lemma monomial_mul_monomial (m n : σ →₀ ℕ) (a b : α) : monomial α m a * monomial α n b = monomial α (m + n) (a * b) := begin ext k, rw [coeff_mul, coeff_monomial], split_ifs with h, { rw [h, finset.sum_eq_single (m,n)], { rw [coeff_monomial', coeff_monomial'] }, { rintros ⟨i,j⟩ hij hne, rw [ne.def, prod.mk.inj_iff, not_and] at hne, by_cases H : i = m, { rw [coeff_monomial j n b, if_neg (hne H), mul_zero] }, { rw [coeff_monomial, if_neg H, zero_mul] } }, { intro H, rw finsupp.mem_antidiagonal_support at H, exfalso, exact H rfl } }, { rw [finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, by_cases H : i = m, { subst i, have : j ≠ n, { rintro rfl, exact h hij.symm }, { rw [coeff_monomial j n b, if_neg this, mul_zero] } }, { rw [coeff_monomial, if_neg H, zero_mul] } } end variables (σ) (α) /-- The constant multivariate formal power series.-/ def C : α →+* mv_power_series σ α := { map_one' := rfl, map_mul' := λ a b, (monomial_mul_monomial 0 0 a b).symm, .. monomial α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma monomial_zero_eq_C : monomial α (0 : σ →₀ ℕ) = C σ α := rfl @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α (0 : σ →₀ ℕ) a = C σ α a := rfl lemma coeff_C (n : σ →₀ ℕ) (a : α) : coeff α n (C σ α a) = if n = 0 then a else 0 := rfl @[simp, priority 1100] lemma coeff_zero_C (a : α) : coeff α (0 : σ →₀ℕ) (C σ α a) = a := coeff_monomial' 0 a /-- The variables of the multivariate formal power series ring.-/ def X (s : σ) : mv_power_series σ α := monomial α (single s 1) 1 lemma coeff_X (n : σ →₀ ℕ) (s : σ) : coeff α n (X s : mv_power_series σ α) = if n = (single s 1) then 1 else 0 := rfl lemma coeff_index_single_X (s t : σ) : coeff α (single t 1) (X s : mv_power_series σ α) = if t = s then 1 else 0 := by { simp only [coeff_X, single_right_inj one_ne_zero], split_ifs; refl } @[simp] lemma coeff_index_single_self_X (s : σ) : coeff α (single s 1) (X s : mv_power_series σ α) = 1 := if_pos rfl @[simp, priority 1100] lemma coeff_zero_X (s : σ) : coeff α (0 : σ →₀ ℕ) (X s : mv_power_series σ α) = 0 := by { rw [coeff_X, if_neg], intro h, exact one_ne_zero (single_eq_zero.mp h.symm) } lemma X_def (s : σ) : X s = monomial α (single s 1) 1 := rfl lemma X_pow_eq (s : σ) (n : ℕ) : (X s : mv_power_series σ α)^n = monomial α (single s n) 1 := begin induction n with n ih, { rw [pow_zero, finsupp.single_zero], refl }, { rw [pow_succ', ih, nat.succ_eq_add_one, finsupp.single_add, X, monomial_mul_monomial, one_mul] } end lemma coeff_X_pow (m : σ →₀ ℕ) (s : σ) (n : ℕ) : coeff α m ((X s : mv_power_series σ α)^n) = if m = single s n then 1 else 0 := by rw [X_pow_eq s n, coeff_monomial] @[simp] lemma coeff_mul_C (n : σ →₀ ℕ) (φ : mv_power_series σ α) (a : α) : coeff α n (φ * (C σ α a)) = (coeff α n φ) * a := begin rw [coeff_mul n φ], rw [finset.sum_eq_single (n,(0 : σ →₀ ℕ))], { rw [coeff_C, if_pos rfl] }, { rintro ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, by_cases hj : j = 0, { subst hj, simp at *, contradiction }, { rw [coeff_C, if_neg hj, mul_zero] } }, { intro h, exfalso, apply h, rw finsupp.mem_antidiagonal_support, apply add_zero } end lemma coeff_zero_mul_X (φ : mv_power_series σ α) (s : σ) : coeff α (0 : σ →₀ ℕ) (φ * X s) = 0 := begin rw [coeff_mul _ φ, finset.sum_eq_zero], rintro ⟨i,j⟩ hij, obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { rw finsupp.mem_antidiagonal_support at hij, simpa using hij }, simp, end variables (σ) (α) /-- The constant coefficient of a formal power series.-/ def constant_coeff : (mv_power_series σ α) →+* α := { to_fun := coeff α (0 : σ →₀ ℕ), map_one' := coeff_zero_one, map_mul' := λ φ ψ, by simp [coeff_mul, support_single_ne_zero], .. coeff α (0 : σ →₀ ℕ) } variables {σ} {α} @[simp] lemma coeff_zero_eq_constant_coeff : coeff α (0 : σ →₀ ℕ) = constant_coeff σ α := rfl @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : mv_power_series σ α) : coeff α (0 : σ →₀ ℕ) φ = constant_coeff σ α φ := rfl @[simp] lemma constant_coeff_C (a : α) : constant_coeff σ α (C σ α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff σ α).comp (C σ α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff σ α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff σ α 1 = 1 := rfl @[simp] lemma constant_coeff_X (s : σ) : constant_coeff σ α (X s) = 0 := coeff_zero_X s /-- If a multivariate formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : mv_power_series σ α) (h : is_unit φ) : is_unit (constant_coeff σ α φ) := h.map' (constant_coeff σ α) instance : semimodule α (mv_power_series σ α) := { smul := λ a φ, C σ α a * φ, one_smul := λ φ, one_mul _, mul_smul := λ a b φ, by simp [ring_hom.map_mul, mul_assoc], smul_add := λ a φ ψ, mul_add _ _ _, smul_zero := λ a, mul_zero _, add_smul := λ a b φ, by simp only [ring_hom.map_add, add_mul], zero_smul := λ φ, by simp only [zero_mul, ring_hom.map_zero] } end semiring instance [ring α] : module α (mv_power_series σ α) := { ..mv_power_series.semimodule } instance [comm_ring α] : algebra α (mv_power_series σ α) := { commutes' := λ _ _, mul_comm _ _, smul_def' := λ c p, rfl, .. C σ α, .. mv_power_series.module } section map variables {β : Type*} {γ : Type*} [semiring α] [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) variable (σ) /-- The map between multivariate formal power series induced by a map on the coefficients.-/ def map : mv_power_series σ α →+* mv_power_series σ β := { to_fun := λ φ n, f $ coeff α n φ, map_zero' := ext $ λ n, f.map_zero, map_one' := ext $ λ n, show f ((coeff α n) 1) = (coeff β n) 1, by { rw [coeff_one, coeff_one], split_ifs; simp [f.map_one, f.map_zero] }, map_add' := λ φ ψ, ext $ λ n, show f ((coeff α n) (φ + ψ)) = f ((coeff α n) φ) + f ((coeff α n) ψ), by simp, map_mul' := λ φ ψ, ext $ λ n, show f _ = _, begin rw [coeff_mul, ← finset.sum_hom _ f, coeff_mul, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [f.map_mul], refl, end } variable {σ} @[simp] lemma map_id : map σ (ring_hom.id α) = ring_hom.id _ := rfl lemma map_comp : map σ (g.comp f) = (map σ g).comp (map σ f) := rfl @[simp] lemma coeff_map (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff β n (map σ f φ) = f (coeff α n φ) := rfl @[simp] lemma constant_coeff_map (φ : mv_power_series σ α) : constant_coeff σ β (map σ f φ) = f (constant_coeff σ α φ) := rfl end map section trunc variables [comm_semiring α] (n : σ →₀ ℕ) -- Auxiliary definition for the truncation function. def trunc_fun (φ : mv_power_series σ α) : mv_polynomial σ α := { support := (n.antidiagonal.support.image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ finset.image prod.fst ((antidiagonal n).support) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩ s, rw finsupp.mem_antidiagonal_support at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finsupp.mem_antidiagonal_support, ext s, exact nat.add_sub_of_le (h s) } end } variable (α) /-- The `n`th truncation of a multivariate formal power series to a multivariate polynomial -/ def trunc : mv_power_series σ α →+ mv_polynomial σ α := { to_fun := trunc_fun n, map_zero' := mv_polynomial.ext _ _ $ λ m, by { change ite _ _ _ = _, split_ifs; refl }, map_add' := λ φ ψ, mv_polynomial.ext _ _ $ λ m, begin rw mv_polynomial.coeff_add, change ite _ _ _ = ite _ _ _ + ite _ _ _, split_ifs with H, {refl}, {rw [zero_add]} end } variable {α} lemma coeff_trunc (m : σ →₀ ℕ) (φ : mv_power_series σ α) : mv_polynomial.coeff m (trunc α n φ) = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_one : trunc α n 1 = 1 := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H', { subst m, erw mv_polynomial.coeff_C 0, simp }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg (ne.elim (ne.symm H')), }, { symmetry, erw mv_polynomial.coeff_monomial, convert if_neg _, intro H', apply H, subst m, intro s, exact nat.zero_le _ } end @[simp] lemma trunc_C (a : α) : trunc α n (C σ α a) = mv_polynomial.C a := mv_polynomial.ext _ _ $ λ m, begin rw [coeff_trunc, coeff_C, mv_polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *}, exfalso, apply H, subst m, intro s, exact nat.zero_le _ end end trunc section comm_semiring variable [comm_semiring α] lemma X_pow_dvd_iff {s : σ} {n : ℕ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α)^n ∣ φ ↔ ∀ m : σ →₀ ℕ, m s < n → coeff α m φ = 0 := begin split, { rintros ⟨φ, rfl⟩ m h, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, rw [coeff_X_pow, if_neg, zero_mul], contrapose! h, subst i, rw finsupp.mem_antidiagonal_support at hij, rw [← hij, finsupp.add_apply, finsupp.single_eq_same], exact nat.le_add_right n _ }, { intro h, refine ⟨λ m, coeff α (m + (single s n)) φ, _⟩, ext m, by_cases H : m - single s n + single s n = m, { rw [coeff_mul, finset.sum_eq_single (single s n, m - single s n)], { rw [coeff_X_pow, if_pos rfl, one_mul], simpa using congr_arg (λ (m : σ →₀ ℕ), coeff α m φ) H.symm }, { rintros ⟨i,j⟩ hij hne, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply hne, rw [← hij, ← hi, prod.mk.inj_iff], refine ⟨rfl, _⟩, ext t, simp only [nat.add_sub_cancel_left, finsupp.add_apply, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { intro hni, exfalso, apply hni, rwa [finsupp.mem_antidiagonal_support, add_comm] } }, { rw [h, coeff_mul, finset.sum_eq_zero], { rintros ⟨i,j⟩ hij, rw finsupp.mem_antidiagonal_support at hij, rw coeff_X_pow, split_ifs with hi, { exfalso, apply H, rw [← hij, hi], ext t, simp only [nat.add_sub_cancel_left, add_comm, finsupp.add_apply, add_right_inj, finsupp.nat_sub_apply] }, { exact zero_mul _ } }, { classical, contrapose! H, ext t, by_cases hst : s = t, { subst t, simpa using nat.sub_add_cancel H }, { simp [finsupp.single_apply, hst] } } } } end lemma X_dvd_iff {s : σ} {φ : mv_power_series σ α} : (X s : mv_power_series σ α) ∣ φ ↔ ∀ m : σ →₀ ℕ, m s = 0 → coeff α m φ = 0 := begin rw [← pow_one (X s : mv_power_series σ α), X_pow_dvd_iff], split; intros h m hm, { exact h m (hm.symm ▸ zero_lt_one) }, { exact h m (nat.eq_zero_of_le_zero $ nat.le_of_succ_le_succ hm) } end end comm_semiring section ring variables [ring α] /- The inverse of a multivariate formal power series is defined by well-founded recursion on the coeffients of the inverse. -/ /-- Auxiliary definition that unifies the totalised inverse formal power series `(_)⁻¹` and the inverse formal power series that depends on an inverse of the constant coefficient `inv_of_unit`.-/ protected noncomputable def inv.aux (a : α) (φ : mv_power_series σ α) : mv_power_series σ α | n := if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if h : x.2 < n then coeff α x.1 φ * inv.aux x.2 else 0) using_well_founded { rel_tac := λ _ _, `[exact ⟨_, finsupp.lt_wf σ⟩], dec_tac := tactic.assumption } lemma coeff_inv_aux (n : σ →₀ ℕ) (a : α) (φ : mv_power_series σ α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := show inv.aux a φ n = _, by { rw inv.aux, refl } /-- A multivariate formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : mv_power_series σ α) (u : units α) : mv_power_series σ α := inv.aux (↑u⁻¹) φ lemma coeff_inv_of_unit (n : σ →₀ ℕ) (φ : mv_power_series σ α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n (↑u⁻¹) φ @[simp] lemma constant_coeff_inv_of_unit (φ : mv_power_series σ α) (u : units α) : constant_coeff σ α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : φ * inv_of_unit φ u = 1 := ext $ λ n, if H : n = 0 then by { rw H, simp [coeff_mul, support_single_ne_zero, h], } else begin have : ((0 : σ →₀ ℕ), n) ∈ n.antidiagonal.support, { rw [finsupp.mem_antidiagonal_support, zero_add] }, rw [coeff_one, if_neg H, coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), coeff_zero_eq_constant_coeff_apply, h, coeff_inv_of_unit, if_neg H, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, units.mul_inv_cancel_left, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.insert_erase this, if_neg (not_lt_of_ge $ le_refl _), zero_add, add_comm, ← sub_eq_add_neg, sub_eq_zero, finset.sum_congr rfl], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, finsupp.mem_antidiagonal_support] at hij, cases hij with h₁ h₂, subst n, rw if_pos, suffices : (0 : _) + j < i + j, {simpa}, apply add_lt_add_right, split, { intro s, exact nat.zero_le _ }, { intro H, apply h₁, suffices : i = 0, {simp [this]}, ext1 s, exact nat.eq_zero_of_le_zero (H s) } end end ring section comm_ring variable [comm_ring α] /-- Multivariate formal power series over a local ring form a local ring.-/ lemma is_local_ring (h : is_local_ring α) : is_local_ring (mv_power_series σ α) := begin split, { have H : (0:α) ≠ 1 := ‹is_local_ring α›.1, contrapose! H, simpa using congr_arg (constant_coeff σ α) H }, { intro φ, rcases ‹is_local_ring α›.2 (constant_coeff σ α φ) with ⟨u,h⟩|⟨u,h⟩; [left, right]; { refine is_unit_of_mul_eq_one _ _ (mul_inv_of_unit _ u _), simpa using h } } end -- TODO(jmc): once adic topology lands, show that this is complete end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] instance : nonzero_comm_ring (mv_power_series σ α) := { zero_ne_one := assume h, zero_ne_one $ show (0:α) = 1, from congr_arg (constant_coeff σ α) h, .. mv_power_series.comm_ring } lemma X_inj {s t : σ} : (X s : mv_power_series σ α) = X t ↔ s = t := ⟨begin intro h, replace h := congr_arg (coeff α (single s 1)) h, rw [coeff_X, if_pos rfl, coeff_X] at h, split_ifs at h with H, { rw finsupp.single_eq_single_iff at H, cases H, { exact H.1 }, { exfalso, exact one_ne_zero H.1 } }, { exfalso, exact one_ne_zero h } end, congr_arg X⟩ end nonzero_comm_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (mv_power_series σ α) := local_of_is_local_ring $ is_local_ring ⟨zero_ne_one, local_ring.is_local⟩ instance map.is_local_ring_hom : is_local_ring_hom (map σ f) := ⟨begin rintros φ ⟨ψ, h⟩, replace h := congr_arg (constant_coeff σ β) h, rw constant_coeff_map at h, have : is_unit (constant_coeff σ β ↑ψ) := @is_unit_constant_coeff σ β _ (↑ψ) (is_unit_unit ψ), rw ← h at this, rcases is_unit_of_map_unit f _ this with ⟨c, hc⟩, exact is_unit_of_mul_eq_one φ (inv_of_unit φ c) (mul_inv_of_unit φ c hc) end⟩ end local_ring section field variables [field α] protected def inv (φ : mv_power_series σ α) : mv_power_series σ α := inv.aux (constant_coeff σ α φ)⁻¹ φ instance : has_inv (mv_power_series σ α) := ⟨mv_power_series.inv⟩ lemma coeff_inv (n : σ →₀ ℕ) (φ : mv_power_series σ α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff σ α φ)⁻¹ else - (constant_coeff σ α φ)⁻¹ * n.antidiagonal.support.sum (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := coeff_inv_aux n _ φ @[simp] lemma constant_coeff_inv (φ : mv_power_series σ α) : constant_coeff σ α (φ⁻¹) = (constant_coeff σ α φ)⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv, if_pos rfl] lemma inv_eq_zero {φ : mv_power_series σ α} : φ⁻¹ = 0 ↔ constant_coeff σ α φ = 0 := ⟨λ h, by simpa using congr_arg (constant_coeff σ α) h, λ h, ext $ λ n, by { rw coeff_inv, split_ifs; simp only [h, mv_power_series.coeff_zero, zero_mul, inv_zero, neg_zero] }⟩ @[simp, priority 1100] lemma inv_of_unit_eq (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := rfl @[simp] lemma inv_of_unit_eq' (φ : mv_power_series σ α) (u : units α) (h : constant_coeff σ α φ = u) : inv_of_unit φ u = φ⁻¹ := begin rw ← inv_of_unit_eq φ (h.symm ▸ u.ne_zero), congr' 1, rw [units.ext_iff], exact h.symm, end @[simp] protected lemma mul_inv (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ * φ⁻¹ = 1 := by rw [← inv_of_unit_eq φ h, mul_inv_of_unit φ (units.mk0 _ h) rfl] @[simp] protected lemma inv_mul (φ : mv_power_series σ α) (h : constant_coeff σ α φ ≠ 0) : φ⁻¹ * φ = 1 := by rw [mul_comm, φ.mul_inv h] end field end mv_power_series namespace mv_polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from multivariate polynomials into multivariate formal power series.-/ instance coe_to_mv_power_series : has_coe (mv_polynomial σ α) (mv_power_series σ α) := ⟨λ φ n, coeff n φ⟩ @[simp, elim_cast] lemma coeff_coe (φ : mv_polynomial σ α) (n : σ →₀ ℕ) : mv_power_series.coeff α n ↑φ = coeff n φ := rfl @[simp, elim_cast] lemma coe_monomial (n : σ →₀ ℕ) (a : α) : (monomial n a : mv_power_series σ α) = mv_power_series.monomial α n a := mv_power_series.ext $ λ m, begin rw [coeff_coe, coeff_monomial, mv_power_series.coeff_monomial], split_ifs with h₁ h₂; refl <|> subst m; contradiction end @[simp, elim_cast] lemma coe_zero : ((0 : mv_polynomial σ α) : mv_power_series σ α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : mv_polynomial σ α) : mv_power_series σ α) = 1 := coe_monomial _ _ @[simp, elim_cast] lemma coe_add (φ ψ : mv_polynomial σ α) : ((φ + ψ : mv_polynomial σ α) : mv_power_series σ α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : mv_polynomial σ α) : ((φ * ψ : mv_polynomial σ α) : mv_power_series σ α) = φ * ψ := mv_power_series.ext $ λ n, by simp only [coeff_coe, mv_power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.C σ α a := coe_monomial _ _ @[simp, elim_cast] lemma coe_X (s : σ) : ((X s : mv_polynomial σ α) : mv_power_series σ α) = mv_power_series.X s := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : mv_polynomial σ α → mv_power_series σ α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end mv_polynomial /-- Formal power series over the coefficient ring `α`.-/ def power_series (α : Type*) := mv_power_series unit α namespace power_series open finsupp (single) variable {α : Type*} instance [inhabited α] : inhabited (power_series α) := by delta power_series; apply_instance instance [add_monoid α] : add_monoid (power_series α) := by delta power_series; apply_instance instance [add_group α] : add_group (power_series α) := by delta power_series; apply_instance instance [add_comm_monoid α] : add_comm_monoid (power_series α) := by delta power_series; apply_instance instance [add_comm_group α] : add_comm_group (power_series α) := by delta power_series; apply_instance instance [semiring α] : semiring (power_series α) := by delta power_series; apply_instance instance [comm_semiring α] : comm_semiring (power_series α) := by delta power_series; apply_instance instance [ring α] : ring (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : comm_ring (power_series α) := by delta power_series; apply_instance instance [nonzero_comm_ring α] : nonzero_comm_ring (power_series α) := by delta power_series; apply_instance instance [semiring α] : semimodule α (power_series α) := by delta power_series; apply_instance instance [ring α] : module α (power_series α) := by delta power_series; apply_instance instance [comm_ring α] : algebra α (power_series α) := by delta power_series; apply_instance section add_monoid variables (α) [add_monoid α] /-- The `n`th coefficient of a formal power series.-/ def coeff (n : ℕ) : power_series α →+ α := mv_power_series.coeff α (single () n) /-- The `n`th monomial with coefficient `a` as formal power series.-/ def monomial (n : ℕ) : α →+ power_series α := mv_power_series.monomial α (single () n) variables {α} lemma coeff_def {s : unit →₀ ℕ} {n : ℕ} (h : s () = n) : coeff α n = mv_power_series.coeff α s := by erw [coeff, ← h, ← finsupp.unique_single s] /-- Two formal power series are equal if all their coefficients are equal.-/ @[ext] lemma ext {φ ψ : power_series α} (h : ∀ n, coeff α n φ = coeff α n ψ) : φ = ψ := mv_power_series.ext $ λ n, by { rw ← coeff_def, { apply h }, refl } /-- Two formal power series are equal if all their coefficients are equal.-/ lemma ext_iff {φ ψ : power_series α} : φ = ψ ↔ (∀ n, coeff α n φ = coeff α n ψ) := ⟨λ h n, congr_arg (coeff α n) h, ext⟩ /-- Constructor for formal power series.-/ def mk (f : ℕ → α) : power_series α := λ s, f (s ()) @[simp] lemma coeff_mk (n : ℕ) (f : ℕ → α) : coeff α n (mk f) = f n := congr_arg f finsupp.single_eq_same lemma coeff_monomial (m n : ℕ) (a : α) : coeff α m (monomial α n a) = if m = n then a else 0 := calc coeff α m (monomial α n a) = _ : mv_power_series.coeff_monomial _ _ _ ... = if m = n then a else 0 : by { simp only [finsupp.unique_single_eq_iff], split_ifs; refl } lemma monomial_eq_mk (n : ℕ) (a : α) : monomial α n a = mk (λ m, if m = n then a else 0) := ext $ λ m, by { rw [coeff_monomial, coeff_mk] } @[simp] lemma coeff_monomial' (n : ℕ) (a : α) : coeff α n (monomial α n a) = a := by convert if_pos rfl @[simp] lemma coeff_comp_monomial (n : ℕ) : (coeff α n).comp (monomial α n) = add_monoid_hom.id α := add_monoid_hom.ext $ coeff_monomial' n end add_monoid section semiring variable [semiring α] variable (α) /--The constant coefficient of a formal power series. -/ def constant_coeff : power_series α →+* α := mv_power_series.constant_coeff unit α /-- The constant formal power series.-/ def C : α →+* power_series α := mv_power_series.C unit α variable {α} /-- The variable of the formal power series ring.-/ def X : power_series α := mv_power_series.X () @[simp] lemma coeff_zero_eq_constant_coeff : coeff α 0 = constant_coeff α := begin rw [constant_coeff, ← mv_power_series.coeff_zero_eq_constant_coeff, coeff_def], refl end @[simp] lemma coeff_zero_eq_constant_coeff_apply (φ : power_series α) : coeff α 0 φ = constant_coeff α φ := by rw [coeff_zero_eq_constant_coeff]; refl @[simp] lemma monomial_zero_eq_C : monomial α 0 = C α := by rw [monomial, finsupp.single_zero, mv_power_series.monomial_zero_eq_C, C] @[simp] lemma monomial_zero_eq_C_apply (a : α) : monomial α 0 a = C α a := by rw [monomial_zero_eq_C]; refl lemma coeff_C (n : ℕ) (a : α) : coeff α n (C α a : power_series α) = if n = 0 then a else 0 := by rw [← monomial_zero_eq_C_apply, coeff_monomial] @[simp] lemma coeff_zero_C (a : α) : coeff α 0 (C α a) = a := by rw [← monomial_zero_eq_C_apply, coeff_monomial' 0 a] lemma X_eq : (X : power_series α) = monomial α 1 1 := rfl lemma coeff_X (n : ℕ) : coeff α n (X : power_series α) = if n = 1 then 1 else 0 := by rw [X_eq, coeff_monomial] @[simp] lemma coeff_zero_X : coeff α 0 (X : power_series α) = 0 := by rw [coeff, finsupp.single_zero, X, mv_power_series.coeff_zero_X] @[simp] lemma coeff_one_X : coeff α 1 (X : power_series α) = 1 := by rw [coeff_X, if_pos rfl] lemma X_pow_eq (n : ℕ) : (X : power_series α)^n = monomial α n 1 := mv_power_series.X_pow_eq _ n lemma coeff_X_pow (m n : ℕ) : coeff α m ((X : power_series α)^n) = if m = n then 1 else 0 := by rw [X_pow_eq, coeff_monomial] @[simp] lemma coeff_X_pow_self (n : ℕ) : coeff α n ((X : power_series α)^n) = 1 := by rw [coeff_X_pow, if_pos rfl] @[simp] lemma coeff_one (n : ℕ) : coeff α n (1 : power_series α) = if n = 0 then 1 else 0 := calc coeff α n (1 : power_series α) = _ : mv_power_series.coeff_one _ ... = if n = 0 then 1 else 0 : by { simp only [finsupp.single_eq_zero], split_ifs; refl } @[simp] lemma coeff_zero_one : coeff α 0 (1 : power_series α) = 1 := coeff_zero_C 1 lemma coeff_mul (n : ℕ) (φ ψ : power_series α) : coeff α n (φ * ψ) = (finset.nat.antidiagonal n).sum (λ p, coeff α p.1 φ * coeff α p.2 ψ) := begin symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, refl }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end @[simp] lemma coeff_mul_C (n : ℕ) (φ : power_series α) (a : α) : coeff α n (φ * (C α a)) = (coeff α n φ) * a := mv_power_series.coeff_mul_C _ φ a @[simp] lemma coeff_succ_mul_X (n : ℕ) (φ : power_series α) : coeff α (n+1) (φ * X) = coeff α n φ := begin rw [coeff_mul _ φ, finset.sum_eq_single (n,1)], { rw [coeff_X, if_pos rfl, mul_one] }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j = 1, { subst hj, simp at *, contradiction }, { simp [coeff_X, hj] } }, { intro h, exfalso, apply h, simp }, end @[simp] lemma coeff_zero_mul_X (φ : power_series α) : coeff α 0 (φ * X) = 0 := begin rw [coeff_mul _ φ, finset.sum_eq_zero], rintro ⟨i,j⟩ hij, obtain ⟨rfl, rfl⟩ : i = 0 ∧ j = 0, { simpa using hij }, simp, end @[simp] lemma constant_coeff_C (a : α) : constant_coeff α (C α a) = a := rfl @[simp] lemma constant_coeff_comp_C : (constant_coeff α).comp (C α) = ring_hom.id α := rfl @[simp] lemma constant_coeff_zero : constant_coeff α 0 = 0 := rfl @[simp] lemma constant_coeff_one : constant_coeff α 1 = 1 := rfl @[simp] lemma constant_coeff_X : constant_coeff α X = 0 := mv_power_series.coeff_zero_X _ /-- If a formal power series is invertible, then so is its constant coefficient.-/ lemma is_unit_constant_coeff (φ : power_series α) (h : is_unit φ) : is_unit (constant_coeff α φ) := mv_power_series.is_unit_constant_coeff φ h section map variables {β : Type*} {γ : Type*} [semiring β] [semiring γ] variables (f : α →+* β) (g : β →+* γ) /-- The map between formal power series induced by a map on the coefficients.-/ def map : power_series α →+* power_series β := mv_power_series.map _ f @[simp] lemma map_id : (map (ring_hom.id α) : power_series α → power_series α) = id := rfl lemma map_comp : map (g.comp f) = (map g).comp (map f) := rfl @[simp] lemma coeff_map (n : ℕ) (φ : power_series α) : coeff β n (map f φ) = f (coeff α n φ) := rfl end map end semiring section comm_semiring variables [comm_semiring α] lemma X_pow_dvd_iff {n : ℕ} {φ : power_series α} : (X : power_series α)^n ∣ φ ↔ ∀ m, m < n → coeff α m φ = 0 := begin convert @mv_power_series.X_pow_dvd_iff unit α _ () n φ, apply propext, classical, split; intros h m hm, { rw finsupp.unique_single m, convert h _ hm }, { apply h, simpa only [finsupp.single_eq_same] using hm } end lemma X_dvd_iff {φ : power_series α} : (X : power_series α) ∣ φ ↔ constant_coeff α φ = 0 := begin rw [← pow_one (X : power_series α), X_pow_dvd_iff, ← coeff_zero_eq_constant_coeff_apply], split; intro h, { exact h 0 zero_lt_one }, { intros m hm, rwa nat.eq_zero_of_le_zero (nat.le_of_succ_le_succ hm) } end section trunc /-- The `n`th truncation of a formal power series to a polynomial -/ def trunc (n : ℕ) (φ : power_series α) : polynomial α := { support := ((finset.nat.antidiagonal n).image prod.fst).filter (λ m, coeff α m φ ≠ 0), to_fun := λ m, if m ≤ n then coeff α m φ else 0, mem_support_to_fun := λ m, begin suffices : m ∈ ((finset.nat.antidiagonal n).image prod.fst) ↔ m ≤ n, { rw [finset.mem_filter, this], split, { intro h, rw [if_pos h.1], exact h.2 }, { intro h, split_ifs at h with H H, { exact ⟨H, h⟩ }, { exfalso, exact h rfl } } }, rw finset.mem_image, split, { rintros ⟨⟨i,j⟩, h, rfl⟩, rw finset.nat.mem_antidiagonal at h, rw ← h, exact nat.le_add_right _ _ }, { intro h, refine ⟨(m, n-m), _, rfl⟩, rw finset.nat.mem_antidiagonal, exact nat.add_sub_of_le h } end } lemma coeff_trunc (m) (n) (φ : power_series α) : polynomial.coeff (trunc n φ) m = if m ≤ n then coeff α m φ else 0 := rfl @[simp] lemma trunc_zero (n) : trunc n (0 : power_series α) = 0 := polynomial.ext $ λ m, begin rw [coeff_trunc, add_monoid_hom.map_zero, polynomial.coeff_zero], split_ifs; refl end @[simp] lemma trunc_one (n) : trunc n (1 : power_series α) = 1 := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_one], split_ifs with H H' H'; rw [polynomial.coeff_one], { subst m, rw [if_pos rfl] }, { symmetry, exact if_neg (ne.elim (ne.symm H')) }, { symmetry, refine if_neg _, intro H', apply H, subst m, exact nat.zero_le _ } end @[simp] lemma trunc_C (n) (a : α) : trunc n (C α a) = polynomial.C a := polynomial.ext $ λ m, begin rw [coeff_trunc, coeff_C, polynomial.coeff_C], split_ifs with H; refl <|> try {simp * at *} end @[simp] lemma trunc_add (n) (φ ψ : power_series α) : trunc n (φ + ψ) = trunc n φ + trunc n ψ := polynomial.ext $ λ m, begin simp only [coeff_trunc, add_monoid_hom.map_add, polynomial.coeff_add], split_ifs with H, {refl}, {rw [zero_add]} end end trunc end comm_semiring section ring variables [ring α] protected def inv.aux : α → power_series α → power_series α := mv_power_series.inv.aux lemma coeff_inv_aux (n : ℕ) (a : α) (φ : power_series α) : coeff α n (inv.aux a φ) = if n = 0 then a else - a * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv.aux a φ) else 0) := begin rw [coeff, inv.aux, mv_power_series.coeff_inv_aux], simp only [finsupp.single_eq_zero], split_ifs, {refl}, congr' 1, symmetry, apply finset.sum_bij (λ (p : ℕ × ℕ) h, (single () p.1, single () p.2)), { rintros ⟨i,j⟩ hij, rw finset.nat.mem_antidiagonal at hij, rw [finsupp.mem_antidiagonal_support, ← finsupp.single_add, hij], }, { rintros ⟨i,j⟩ hij, by_cases H : j < n, { rw [if_pos H, if_pos], {refl}, split, { rintro ⟨⟩, simpa [finsupp.single_eq_same] using le_of_lt H }, { intro hh, rw lt_iff_not_ge at H, apply H, simpa [finsupp.single_eq_same] using hh () } }, { rw [if_neg H, if_neg], rintro ⟨h₁, h₂⟩, apply h₂, rintro ⟨⟩, simpa [finsupp.single_eq_same] using not_lt.1 H } }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa only [prod.mk.inj_iff, finsupp.unique_single_eq_iff] using id }, { rintros ⟨f,g⟩ hfg, refine ⟨(f (), g ()), _, _⟩, { rw finsupp.mem_antidiagonal_support at hfg, rw [finset.nat.mem_antidiagonal, ← finsupp.add_apply, hfg, finsupp.single_eq_same] }, { rw prod.mk.inj_iff, dsimp, exact ⟨finsupp.unique_single f, finsupp.unique_single g⟩ } } end /-- A formal power series is invertible if the constant coefficient is invertible.-/ def inv_of_unit (φ : power_series α) (u : units α) : power_series α := mv_power_series.inv_of_unit φ u lemma coeff_inv_of_unit (n : ℕ) (φ : power_series α) (u : units α) : coeff α n (inv_of_unit φ u) = if n = 0 then ↑u⁻¹ else - ↑u⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (inv_of_unit φ u) else 0) := coeff_inv_aux n ↑u⁻¹ φ @[simp] lemma constant_coeff_inv_of_unit (φ : power_series α) (u : units α) : constant_coeff α (inv_of_unit φ u) = ↑u⁻¹ := by rw [← coeff_zero_eq_constant_coeff_apply, coeff_inv_of_unit, if_pos rfl] lemma mul_inv_of_unit (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : φ * inv_of_unit φ u = 1 := mv_power_series.mul_inv_of_unit φ u $ h end ring section integral_domain variable [integral_domain α] lemma eq_zero_or_eq_zero_of_mul_eq_zero (φ ψ : power_series α) (h : φ * ψ = 0) : φ = 0 ∨ ψ = 0 := begin rw classical.or_iff_not_imp_left, intro H, have ex : ∃ m, coeff α m φ ≠ 0, { contrapose! H, exact ext H }, let P : ℕ → Prop := λ k, coeff α k φ ≠ 0, let m := nat.find ex, have hm₁ : coeff α m φ ≠ 0 := nat.find_spec ex, have hm₂ : ∀ k < m, ¬coeff α k φ ≠ 0 := λ k, nat.find_min ex, ext n, rw (coeff α n).map_zero, apply nat.strong_induction_on n, clear n, intros n ih, replace h := congr_arg (coeff α (m + n)) h, rw [add_monoid_hom.map_zero, coeff_mul, finset.sum_eq_single (m,n)] at h, { replace h := eq_zero_or_eq_zero_of_mul_eq_zero h, rw or_iff_not_imp_left at h, exact h hm₁ }, { rintro ⟨i,j⟩ hij hne, by_cases hj : j < n, { rw [ih j hj, mul_zero] }, by_cases hi : i < m, { specialize hm₂ _ hi, push_neg at hm₂, rw [hm₂, zero_mul] }, rw finset.nat.mem_antidiagonal at hij, push_neg at hi hj, suffices : m < i, { have : m + n < i + j := add_lt_add_of_lt_of_le this hj, exfalso, exact ne_of_lt this hij.symm }, contrapose! hne, have : i = m := le_antisymm hne hi, subst i, clear hi hne, simpa [ne.def, prod.mk.inj_iff] using (add_left_inj m).mp hij }, { contrapose!, intro h, rw finset.nat.mem_antidiagonal } end instance : integral_domain (power_series α) := { eq_zero_or_eq_zero_of_mul_eq_zero := eq_zero_or_eq_zero_of_mul_eq_zero, .. power_series.nonzero_comm_ring } /-- The ideal spanned by the variable in the power series ring over an integral domain is a prime ideal.-/ lemma span_X_is_prime : (ideal.span ({X} : set (power_series α))).is_prime := begin suffices : ideal.span ({X} : set (power_series α)) = (constant_coeff α).ker, { rw this, exact ring_hom.ker_is_prime _ }, apply ideal.ext, intro φ, rw [ring_hom.mem_ker, ideal.mem_span_singleton, X_dvd_iff] end /-- The variable of the power series ring over an integral domain is prime.-/ lemma X_prime : prime (X : power_series α) := begin rw ← ideal.span_singleton_prime, { exact span_X_is_prime }, { intro h, simpa using congr_arg (coeff α 1) h } end end integral_domain section local_ring variables [comm_ring α] lemma is_local_ring (h : is_local_ring α) : is_local_ring (power_series α) := mv_power_series.is_local_ring h end local_ring section local_ring variables {β : Type*} [local_ring α] [local_ring β] (f : α →+* β) [is_local_ring_hom f] instance : local_ring (power_series α) := mv_power_series.local_ring instance map.is_local_ring_hom : is_local_ring_hom (map f) := mv_power_series.map.is_local_ring_hom f end local_ring section field variables [field α] protected def inv : power_series α → power_series α := mv_power_series.inv instance : has_inv (power_series α) := ⟨power_series.inv⟩ lemma inv_eq_inv_aux (φ : power_series α) : φ⁻¹ = inv.aux (constant_coeff α φ)⁻¹ φ := rfl lemma coeff_inv (n) (φ : power_series α) : coeff α n (φ⁻¹) = if n = 0 then (constant_coeff α φ)⁻¹ else - (constant_coeff α φ)⁻¹ * (finset.nat.antidiagonal n).sum (λ (x : ℕ × ℕ), if x.2 < n then coeff α x.1 φ * coeff α x.2 (φ⁻¹) else 0) := by rw [inv_eq_inv_aux, coeff_inv_aux n (constant_coeff α φ)⁻¹ φ] @[simp] lemma constant_coeff_inv (φ : power_series α) : constant_coeff α (φ⁻¹) = (constant_coeff α φ)⁻¹ := mv_power_series.constant_coeff_inv φ lemma inv_eq_zero {φ : power_series α} : φ⁻¹ = 0 ↔ constant_coeff α φ = 0 := mv_power_series.inv_eq_zero @[simp, priority 1100] lemma inv_of_unit_eq (φ : power_series α) (h : constant_coeff α φ ≠ 0) : inv_of_unit φ (units.mk0 _ h) = φ⁻¹ := mv_power_series.inv_of_unit_eq _ _ @[simp] lemma inv_of_unit_eq' (φ : power_series α) (u : units α) (h : constant_coeff α φ = u) : inv_of_unit φ u = φ⁻¹ := mv_power_series.inv_of_unit_eq' φ _ h @[simp] protected lemma mul_inv (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ * φ⁻¹ = 1 := mv_power_series.mul_inv φ h @[simp] protected lemma inv_mul (φ : power_series α) (h : constant_coeff α φ ≠ 0) : φ⁻¹ * φ = 1 := mv_power_series.inv_mul φ h end field end power_series namespace power_series variable {α : Type*} local attribute [instance, priority 1] classical.prop_decidable noncomputable theory section order_basic open multiplicity variables [comm_semiring α] /-- The order of a formal power series `φ` is the smallest `n : enat` such that `X^n` divides `φ`. The order is `⊤` if and only if `φ = 0`. -/ @[reducible] def order (φ : power_series α) : enat := multiplicity X φ lemma order_finite_of_coeff_ne_zero (φ : power_series α) (h : ∃ n, coeff α n φ ≠ 0) : (order φ).dom := begin cases h with n h, refine ⟨n, _⟩, rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ end /-- If the order of a formal power series is finite, then the coefficient indexed by the order is nonzero.-/ lemma coeff_order (φ : power_series α) (h : (order φ).dom) : coeff α (φ.order.get h) φ ≠ 0 := begin have H := nat.find_spec h, contrapose! H, rw X_pow_dvd_iff, intros m hm, by_cases Hm : m < nat.find h, { have := nat.find_min h Hm, push_neg at this, rw X_pow_dvd_iff at this, exact this m (lt_add_one m) }, have : m = nat.find h, {linarith}, {rwa this} end /-- If the `n`th coefficient of a formal power series is nonzero, then the order of the power series is less than or equal to `n`.-/ lemma order_le (φ : power_series α) (n : ℕ) (h : coeff α n φ ≠ 0) : order φ ≤ n := begin have h : ¬ X^(n+1) ∣ φ, { rw X_pow_dvd_iff, push_neg, exact ⟨n, lt_add_one n, h⟩ }, have : (order φ).dom := ⟨n, h⟩, rw [← enat.coe_get this, enat.coe_le_coe], refine nat.find_min' this h end /-- The `n`th coefficient of a formal power series is `0` if `n` is strictly smaller than the order of the power series.-/ lemma coeff_of_lt_order (φ : power_series α) (n : ℕ) (h: ↑n < order φ) : coeff α n φ = 0 := by { contrapose! h, exact order_le _ _ h } /-- The `0` power series is the unique power series with infinite order.-/ lemma order_eq_top {φ : power_series α} : φ.order = ⊤ ↔ φ = 0 := begin rw multiplicity.eq_top_iff, split, { intro h, ext n, specialize h (n+1), rw X_pow_dvd_iff at h, exact h n (lt_add_one _) }, { rintros rfl n, exact dvd_zero _ } end /-- The order of the `0` power series is infinite.-/ @[simp] lemma order_zero : order (0 : power_series α) = ⊤ := multiplicity.zero _ /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge_nat (φ : power_series α) (n : ℕ) (h : ∀ i < n, coeff α i φ = 0) : order φ ≥ n := begin by_contra H, rw not_le at H, have : (order φ).dom := enat.dom_of_le_some (le_of_lt H), rw [← enat.coe_get this, enat.coe_lt_coe] at H, exact coeff_order _ this (h _ H) end /-- The order of a formal power series is at least `n` if the `i`th coefficient is `0` for all `i < n`.-/ lemma order_ge (φ : power_series α) (n : enat) (h : ∀ i : ℕ, ↑i < n → coeff α i φ = 0) : order φ ≥ n := begin induction n using enat.cases_on, { show _ ≤ _, rw [top_le_iff, order_eq_top], ext i, exact h _ (enat.coe_lt_top i) }, { apply order_ge_nat, simpa only [enat.coe_lt_coe] using h } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq_nat {φ : power_series α} {n : ℕ} : order φ = n ↔ (coeff α n φ ≠ 0) ∧ (∀ i, i < n → coeff α i φ = 0) := begin simp only [eq_some_iff, X_pow_dvd_iff], push_neg, split, { rintros ⟨h₁, m, hm₁, hm₂⟩, refine ⟨_, h₁⟩, suffices : n = m, { rwa this }, suffices : m ≥ n, { linarith }, contrapose! hm₂, exact h₁ _ hm₂ }, { rintros ⟨h₁, h₂⟩, exact ⟨h₂, n, lt_add_one n, h₁⟩ } end /-- The order of a formal power series is exactly `n` if the `n`th coefficient is nonzero, and the `i`th coefficient is `0` for all `i < n`.-/ lemma order_eq {φ : power_series α} {n : enat} : order φ = n ↔ (∀ i:ℕ, ↑i = n → coeff α i φ ≠ 0) ∧ (∀ i:ℕ, ↑i < n → coeff α i φ = 0) := begin induction n using enat.cases_on, { rw order_eq_top, split, { rintro rfl, split; intros, { exfalso, exact enat.coe_ne_top ‹_› ‹_› }, { exact (coeff _ _).map_zero } }, { rintro ⟨h₁, h₂⟩, ext i, exact h₂ i (enat.coe_lt_top i) } }, { simpa [enat.coe_inj] using order_eq_nat } end /-- The order of the sum of two formal power series is at least the minimum of their orders.-/ lemma order_add_ge (φ ψ : power_series α) : order (φ + ψ) ≥ min (order φ) (order ψ) := multiplicity.min_le_multiplicity_add private lemma order_add_of_order_eq.aux (φ ψ : power_series α) (h : order φ ≠ order ψ) (H : order φ < order ψ) : order (φ + ψ) ≤ order φ ⊓ order ψ := begin suffices : order (φ + ψ) = order φ, { rw [le_inf_iff, this], exact ⟨le_refl _, le_of_lt H⟩ }, { rw order_eq, split, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order ψ i (hi.symm ▸ H), add_zero], exact (order_eq_nat.1 hi.symm).1 }, { intros i hi, rw [(coeff _ _).map_add, coeff_of_lt_order φ i hi, coeff_of_lt_order ψ i (lt_trans hi H), zero_add] } } end /-- The order of the sum of two formal power series is the minimum of their orders if their orders differ.-/ lemma order_add_of_order_eq (φ ψ : power_series α) (h : order φ ≠ order ψ) : order (φ + ψ) = order φ ⊓ order ψ := begin refine le_antisymm _ (order_add_ge _ _), by_cases H₁ : order φ < order ψ, { apply order_add_of_order_eq.aux _ _ h H₁ }, by_cases H₂ : order ψ < order φ, { simpa only [add_comm, inf_comm] using order_add_of_order_eq.aux _ _ h.symm H₂ }, exfalso, exact h (le_antisymm (not_lt.1 H₂) (not_lt.1 H₁)) end /-- The order of the product of two formal power series is at least the sum of their orders.-/ lemma order_mul_ge (φ ψ : power_series α) : order (φ * ψ) ≥ order φ + order ψ := begin apply order_ge, intros n hn, rw [coeff_mul, finset.sum_eq_zero], rintros ⟨i,j⟩ hij, by_cases hi : ↑i < order φ, { rw [coeff_of_lt_order φ i hi, zero_mul] }, by_cases hj : ↑j < order ψ, { rw [coeff_of_lt_order ψ j hj, mul_zero] }, rw not_lt at hi hj, rw finset.nat.mem_antidiagonal at hij, exfalso, apply ne_of_lt (lt_of_lt_of_le hn $ add_le_add' hi hj), rw [← enat.coe_add, hij] end /-- The order of the monomial `a*X^n` is infinite if `a = 0` and `n` otherwise.-/ lemma order_monomial (n : ℕ) (a : α) : order (monomial α n a) = if a = 0 then ⊤ else n := begin split_ifs with h, { rw [h, order_eq_top, add_monoid_hom.map_zero] }, { rw [order_eq], split; intros i hi, { rw [enat.coe_inj] at hi, rwa [hi, coeff_monomial'] }, { rw [enat.coe_lt_coe] at hi, rw [coeff_monomial, if_neg], exact ne_of_lt hi } } end /-- The order of the monomial `a*X^n` is `n` if `a ≠ 0`.-/ lemma order_monomial_of_ne_zero (n : ℕ) (a : α) (h : a ≠ 0) : order (monomial α n a) = n := by rw [order_monomial, if_neg h] end order_basic section order_zero_ne_one variables [nonzero_comm_ring α] /-- The order of the formal power series `1` is `0`.-/ @[simp] lemma order_one : order (1 : power_series α) = 0 := by simpa using order_monomial_of_ne_zero 0 (1:α) one_ne_zero /-- The order of the formal power series `X` is `1`.-/ @[simp] lemma order_X : order (X : power_series α) = 1 := order_monomial_of_ne_zero 1 (1:α) one_ne_zero /-- The order of the formal power series `X^n` is `n`.-/ @[simp] lemma order_X_pow (n : ℕ) : order ((X : power_series α)^n) = n := by { rw [X_pow_eq, order_monomial_of_ne_zero], exact one_ne_zero } end order_zero_ne_one section order_integral_domain variables [integral_domain α] /-- The order of the product of two formal power series over an integral domain is the sum of their orders.-/ lemma order_mul (φ ψ : power_series α) : order (φ * ψ) = order φ + order ψ := multiplicity.mul (X_prime) end order_integral_domain end power_series namespace polynomial open finsupp variables {σ : Type*} {α : Type*} [comm_semiring α] /-- The natural inclusion from polynomials into formal power series.-/ instance coe_to_power_series : has_coe (polynomial α) (power_series α) := ⟨λ φ, power_series.mk $ λ n, coeff φ n⟩ @[simp, elim_cast] lemma coeff_coe (φ : polynomial α) (n) : power_series.coeff α n φ = coeff φ n := congr_arg (coeff φ) (finsupp.single_eq_same) @[simp, elim_cast] lemma coe_monomial (n : ℕ) (a : α) : (monomial n a : power_series α) = power_series.monomial α n a := power_series.ext $ λ m, begin rw [coeff_coe, power_series.coeff_monomial], simp only [@eq_comm _ m n], convert finsupp.single_apply, end @[simp, elim_cast] lemma coe_zero : ((0 : polynomial α) : power_series α) = 0 := rfl @[simp, elim_cast] lemma coe_one : ((1 : polynomial α) : power_series α) = 1 := begin have := coe_monomial 0 (1:α), rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_add (φ ψ : polynomial α) : ((φ + ψ : polynomial α) : power_series α) = φ + ψ := rfl @[simp, elim_cast] lemma coe_mul (φ ψ : polynomial α) : ((φ * ψ : polynomial α) : power_series α) = φ * ψ := power_series.ext $ λ n, by simp only [coeff_coe, power_series.coeff_mul, coeff_mul] @[simp, elim_cast] lemma coe_C (a : α) : ((C a : polynomial α) : power_series α) = power_series.C α a := begin have := coe_monomial 0 a, rwa power_series.monomial_zero_eq_C_apply at this, end @[simp, elim_cast] lemma coe_X : ((X : polynomial α) : power_series α) = power_series.X := coe_monomial _ _ namespace coe_to_mv_power_series instance : is_semiring_hom (coe : polynomial α → power_series α) := { map_zero := coe_zero, map_one := coe_one, map_add := coe_add, map_mul := coe_mul } end coe_to_mv_power_series end polynomial
dd21ea0d55db83433f49d7793c18f35b3b1ab50f
94e33a31faa76775069b071adea97e86e218a8ee
/src/probability/stopping.lean
24c4b321cb627693303ee96eb83de348428c8c97
[ "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
59,028
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.function.conditional_expectation import topology.instances.discrete /-! # Filtration and stopping time This file defines some standard definition from the theory of stochastic processes including filtrations and stopping times. These definitions are used to model the amount of information at a specific time and is the first step in formalizing stochastic processes. ## Main definitions * `measure_theory.filtration`: a filtration on a measurable space * `measure_theory.adapted`: a sequence of functions `u` is said to be adapted to a filtration `f` if at each point in time `i`, `u i` is `f i`-strongly measurable * `measure_theory.prog_measurable`: a sequence of functions `u` is said to be progressively measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to `set.Iic i × α` is strongly measurable with respect to the product `measurable_space` structure where the σ-algebra used for `α` is `f i`. * `measure_theory.filtration.natural`: the natural filtration with respect to a sequence of measurable functions is the smallest filtration to which it is adapted to * `measure_theory.is_stopping_time`: a stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is `f i`-measurable * `measure_theory.is_stopping_time.measurable_space`: the σ-algebra associated with a stopping time ## Main results * `adapted.prog_measurable_of_continuous`: a continuous adapted process is progressively measurable. * `prog_measurable.stopped_process`: the stopped process of a progressively measurable process is progressively measurable. * `mem_ℒp_stopped_process`: if a process belongs to `ℒp` at every time in `ℕ`, then its stopped process belongs to `ℒp` as well. ## Tags filtration, stopping time, stochastic process -/ open filter order topological_space open_locale classical measure_theory nnreal ennreal topological_space big_operators namespace measure_theory /-! ### Filtrations -/ /-- A `filtration` on measurable space `α` with σ-algebra `m` is a monotone sequence of sub-σ-algebras of `m`. -/ structure filtration {α : Type*} (ι : Type*) [preorder ι] (m : measurable_space α) := (seq : ι → measurable_space α) (mono' : monotone seq) (le' : ∀ i : ι, seq i ≤ m) variables {α β ι : Type*} {m : measurable_space α} instance [preorder ι] : has_coe_to_fun (filtration ι m) (λ _, ι → measurable_space α) := ⟨λ f, f.seq⟩ namespace filtration variables [preorder ι] protected lemma mono {i j : ι} (f : filtration ι m) (hij : i ≤ j) : f i ≤ f j := f.mono' hij protected lemma le (f : filtration ι m) (i : ι) : f i ≤ m := f.le' i @[ext] protected lemma ext {f g : filtration ι m} (h : (f : ι → measurable_space α) = g) : f = g := by { cases f, cases g, simp only, exact h, } variable (ι) /-- The constant filtration which is equal to `m` for all `i : ι`. -/ def const (m' : measurable_space α) (hm' : m' ≤ m) : filtration ι m := ⟨λ _, m', monotone_const, λ _, hm'⟩ variable {ι} @[simp] lemma const_apply {m' : measurable_space α} {hm' : m' ≤ m} (i : ι) : const ι m' hm' i = m' := rfl instance : inhabited (filtration ι m) := ⟨const ι m le_rfl⟩ instance : has_le (filtration ι m) := ⟨λ f g, ∀ i, f i ≤ g i⟩ instance : has_bot (filtration ι m) := ⟨const ι ⊥ bot_le⟩ instance : has_top (filtration ι m) := ⟨const ι m le_rfl⟩ instance : has_sup (filtration ι m) := ⟨λ f g, { seq := λ i, f i ⊔ g i, mono' := λ i j hij, sup_le ((f.mono hij).trans le_sup_left) ((g.mono hij).trans le_sup_right), le' := λ i, sup_le (f.le i) (g.le i) }⟩ @[norm_cast] lemma coe_fn_sup {f g : filtration ι m} : ⇑(f ⊔ g) = f ⊔ g := rfl instance : has_inf (filtration ι m) := ⟨λ f g, { seq := λ i, f i ⊓ g i, mono' := λ i j hij, le_inf (inf_le_left.trans (f.mono hij)) (inf_le_right.trans (g.mono hij)), le' := λ i, inf_le_left.trans (f.le i) }⟩ @[norm_cast] lemma coe_fn_inf {f g : filtration ι m} : ⇑(f ⊓ g) = f ⊓ g := rfl instance : has_Sup (filtration ι m) := ⟨λ s, { seq := λ i, Sup ((λ f : filtration ι m, f i) '' s), mono' := λ i j hij, begin refine Sup_le (λ m' hm', _), rw [set.mem_image] at hm', obtain ⟨f, hf_mem, hfm'⟩ := hm', rw ← hfm', refine (f.mono hij).trans _, have hfj_mem : f j ∈ ((λ g : filtration ι m, g j) '' s), from ⟨f, hf_mem, rfl⟩, exact le_Sup hfj_mem, end, le' := λ i, begin refine Sup_le (λ m' hm', _), rw [set.mem_image] at hm', obtain ⟨f, hf_mem, hfm'⟩ := hm', rw ← hfm', exact f.le i, end, }⟩ lemma Sup_def (s : set (filtration ι m)) (i : ι) : Sup s i = Sup ((λ f : filtration ι m, f i) '' s) := rfl noncomputable instance : has_Inf (filtration ι m) := ⟨λ s, { seq := λ i, if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m, mono' := λ i j hij, begin by_cases h_nonempty : set.nonempty s, swap, { simp only [h_nonempty, set.nonempty_image_iff, if_false, le_refl], }, simp only [h_nonempty, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂], refine λ f hf_mem, le_trans _ (f.mono hij), have hfi_mem : f i ∈ ((λ g : filtration ι m, g i) '' s), from ⟨f, hf_mem, rfl⟩, exact Inf_le hfi_mem, end, le' := λ i, begin by_cases h_nonempty : set.nonempty s, swap, { simp only [h_nonempty, if_false, le_refl], }, simp only [h_nonempty, if_true], obtain ⟨f, hf_mem⟩ := h_nonempty, exact le_trans (Inf_le ⟨f, hf_mem, rfl⟩) (f.le i), end, }⟩ lemma Inf_def (s : set (filtration ι m)) (i : ι) : Inf s i = if set.nonempty s then Inf ((λ f : filtration ι m, f i) '' s) else m := rfl noncomputable instance : complete_lattice (filtration ι m) := { le := (≤), le_refl := λ f i, le_rfl, le_trans := λ f g h h_fg h_gh i, (h_fg i).trans (h_gh i), le_antisymm := λ f g h_fg h_gf, filtration.ext $ funext $ λ i, (h_fg i).antisymm (h_gf i), sup := (⊔), le_sup_left := λ f g i, le_sup_left, le_sup_right := λ f g i, le_sup_right, sup_le := λ f g h h_fh h_gh i, sup_le (h_fh i) (h_gh _), inf := (⊓), inf_le_left := λ f g i, inf_le_left, inf_le_right := λ f g i, inf_le_right, le_inf := λ f g h h_fg h_fh i, le_inf (h_fg i) (h_fh i), Sup := Sup, le_Sup := λ s f hf_mem i, le_Sup ⟨f, hf_mem, rfl⟩, Sup_le := λ s f h_forall i, Sup_le $ λ m' hm', begin obtain ⟨g, hg_mem, hfm'⟩ := hm', rw ← hfm', exact h_forall g hg_mem i, end, Inf := Inf, Inf_le := λ s f hf_mem i, begin have hs : s.nonempty := ⟨f, hf_mem⟩, simp only [Inf_def, hs, if_true], exact Inf_le ⟨f, hf_mem, rfl⟩, end, le_Inf := λ s f h_forall i, begin by_cases hs : s.nonempty, swap, { simp only [Inf_def, hs, if_false], exact f.le i, }, simp only [Inf_def, hs, if_true, le_Inf_iff, set.mem_image, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂], exact λ g hg_mem, h_forall g hg_mem i, end, top := ⊤, bot := ⊥, le_top := λ f i, f.le' i, bot_le := λ f i, bot_le, } end filtration lemma measurable_set_of_filtration [preorder ι] {f : filtration ι m} {s : set α} {i : ι} (hs : measurable_set[f i] s) : measurable_set[m] s := f.le i s hs /-- A measure is σ-finite with respect to filtration if it is σ-finite with respect to all the sub-σ-algebra of the filtration. -/ class sigma_finite_filtration [preorder ι] (μ : measure α) (f : filtration ι m) : Prop := (sigma_finite : ∀ i : ι, sigma_finite (μ.trim (f.le i))) instance sigma_finite_of_sigma_finite_filtration [preorder ι] (μ : measure α) (f : filtration ι m) [hf : sigma_finite_filtration μ f] (i : ι) : sigma_finite (μ.trim (f.le i)) := by apply hf.sigma_finite -- can't exact here @[priority 100] instance is_finite_measure.sigma_finite_filtration [preorder ι] (μ : measure α) (f : filtration ι m) [is_finite_measure μ] : sigma_finite_filtration μ f := ⟨λ n, by apply_instance⟩ /-- Given a integrable function `g`, the conditional expectations of `g` with respect to a filtration is uniformly integrable. -/ lemma integrable.uniform_integrable_condexp_filtration [preorder ι] {μ : measure α} [is_finite_measure μ] {f : filtration ι m} {g : α → ℝ} (hg : integrable g μ) : uniform_integrable (λ i, μ[g | f i]) 1 μ := hg.uniform_integrable_condexp f.le section adapted_process variables [topological_space β] [preorder ι] {u v : ι → α → β} {f : filtration ι m} /-- A sequence of functions `u` is adapted to a filtration `f` if for all `i`, `u i` is `f i`-measurable. -/ def adapted (f : filtration ι m) (u : ι → α → β) : Prop := ∀ i : ι, strongly_measurable[f i] (u i) namespace adapted lemma add [has_add β] [has_continuous_add β] (hu : adapted f u) (hv : adapted f v) : adapted f (u + v) := λ i, (hu i).add (hv i) lemma neg [add_group β] [topological_add_group β] (hu : adapted f u) : adapted f (-u) := λ i, (hu i).neg lemma smul [has_smul ℝ β] [has_continuous_smul ℝ β] (c : ℝ) (hu : adapted f u) : adapted f (c • u) := λ i, (hu i).const_smul c end adapted variable (β) lemma adapted_zero [has_zero β] (f : filtration ι m) : adapted f (0 : ι → α → β) := λ i, @strongly_measurable_zero α β (f i) _ _ variable {β} /-- Progressively measurable process. A sequence of functions `u` is said to be progressively measurable with respect to a filtration `f` if at each point in time `i`, `u` restricted to `set.Iic i × α` is measurable with respect to the product `measurable_space` structure where the σ-algebra used for `α` is `f i`. The usual definition uses the interval `[0,i]`, which we replace by `set.Iic i`. We recover the usual definition for index types `ℝ≥0` or `ℕ`. -/ def prog_measurable [measurable_space ι] (f : filtration ι m) (u : ι → α → β) : Prop := ∀ i, strongly_measurable[subtype.measurable_space.prod (f i)] (λ p : set.Iic i × α, u p.1 p.2) lemma prog_measurable_const [measurable_space ι] (f : filtration ι m) (b : β) : prog_measurable f ((λ _ _, b) : ι → α → β) := λ i, @strongly_measurable_const _ _ (subtype.measurable_space.prod (f i)) _ _ namespace prog_measurable variables [measurable_space ι] protected lemma adapted (h : prog_measurable f u) : adapted f u := begin intro i, have : u i = (λ p : set.Iic i × α, u p.1 p.2) ∘ (λ x, (⟨i, set.mem_Iic.mpr le_rfl⟩, x)) := rfl, rw this, exact (h i).comp_measurable measurable_prod_mk_left, end protected lemma comp {t : ι → α → ι} [topological_space ι] [borel_space ι] [metrizable_space ι] (h : prog_measurable f u) (ht : prog_measurable f t) (ht_le : ∀ i x, t i x ≤ i) : prog_measurable f (λ i x, u (t i x) x) := begin intro i, have : (λ p : ↥(set.Iic i) × α, u (t (p.fst : ι) p.snd) p.snd) = (λ p : ↥(set.Iic i) × α, u (p.fst : ι) p.snd) ∘ (λ p : ↥(set.Iic i) × α, (⟨t (p.fst : ι) p.snd, set.mem_Iic.mpr ((ht_le _ _).trans p.fst.prop)⟩, p.snd)) := rfl, rw this, exact (h i).comp_measurable ((ht i).measurable.subtype_mk.prod_mk measurable_snd), end section arithmetic @[to_additive] protected lemma mul [has_mul β] [has_continuous_mul β] (hu : prog_measurable f u) (hv : prog_measurable f v) : prog_measurable f (λ i x, u i x * v i x) := λ i, (hu i).mul (hv i) @[to_additive] protected lemma finset_prod' {γ} [comm_monoid β] [has_continuous_mul β] {U : γ → ι → α → β} {s : finset γ} (h : ∀ c ∈ s, prog_measurable f (U c)) : prog_measurable f (∏ c in s, U c) := finset.prod_induction U (prog_measurable f) (λ _ _, prog_measurable.mul) (prog_measurable_const _ 1) h @[to_additive] protected lemma finset_prod {γ} [comm_monoid β] [has_continuous_mul β] {U : γ → ι → α → β} {s : finset γ} (h : ∀ c ∈ s, prog_measurable f (U c)) : prog_measurable f (λ i a, ∏ c in s, U c i a) := by { convert prog_measurable.finset_prod' h, ext i a, simp only [finset.prod_apply], } @[to_additive] protected lemma inv [group β] [topological_group β] (hu : prog_measurable f u) : prog_measurable f (λ i x, (u i x)⁻¹) := λ i, (hu i).inv @[to_additive] protected lemma div [group β] [topological_group β] (hu : prog_measurable f u) (hv : prog_measurable f v) : prog_measurable f (λ i x, u i x / v i x) := λ i, (hu i).div (hv i) end arithmetic end prog_measurable lemma prog_measurable_of_tendsto' {γ} [measurable_space ι] [metrizable_space β] (fltr : filter γ) [fltr.ne_bot] [fltr.is_countably_generated] {U : γ → ι → α → β} (h : ∀ l, prog_measurable f (U l)) (h_tendsto : tendsto U fltr (𝓝 u)) : prog_measurable f u := begin assume i, apply @strongly_measurable_of_tendsto (set.Iic i × α) β γ (measurable_space.prod _ (f i)) _ _ fltr _ _ _ _ (λ l, h l i), rw tendsto_pi_nhds at h_tendsto ⊢, intro x, specialize h_tendsto x.fst, rw tendsto_nhds at h_tendsto ⊢, exact λ s hs h_mem, h_tendsto {g | g x.snd ∈ s} (hs.preimage (continuous_apply x.snd)) h_mem, end lemma prog_measurable_of_tendsto [measurable_space ι] [metrizable_space β] {U : ℕ → ι → α → β} (h : ∀ l, prog_measurable f (U l)) (h_tendsto : tendsto U at_top (𝓝 u)) : prog_measurable f u := prog_measurable_of_tendsto' at_top h h_tendsto /-- A continuous and adapted process is progressively measurable. -/ theorem adapted.prog_measurable_of_continuous [topological_space ι] [metrizable_space ι] [measurable_space ι] [second_countable_topology ι] [opens_measurable_space ι] [metrizable_space β] (h : adapted f u) (hu_cont : ∀ x, continuous (λ i, u i x)) : prog_measurable f u := λ i, @strongly_measurable_uncurry_of_continuous_of_strongly_measurable _ _ (set.Iic i) _ _ _ _ _ _ _ (f i) _ (λ x, (hu_cont x).comp continuous_induced_dom) (λ j, (h j).mono (f.mono j.prop)) end adapted_process namespace filtration variables [topological_space β] [metrizable_space β] [mβ : measurable_space β] [borel_space β] [preorder ι] include mβ /-- Given a sequence of functions, the natural filtration is the smallest sequence of σ-algebras such that that sequence of functions is measurable with respect to the filtration. -/ def natural (u : ι → α → β) (hum : ∀ i, strongly_measurable (u i)) : filtration ι m := { seq := λ i, ⨆ j ≤ i, measurable_space.comap (u j) mβ, mono' := λ i j hij, bsupr_mono $ λ k, ge_trans hij, le' := λ i, begin refine supr₂_le _, rintros j hj s ⟨t, ht, rfl⟩, exact (hum j).measurable ht, end } lemma adapted_natural {u : ι → α → β} (hum : ∀ i, strongly_measurable[m] (u i)) : adapted (natural u hum) u := begin assume i, refine strongly_measurable.mono _ (le_supr₂_of_le i (le_refl i) le_rfl), rw strongly_measurable_iff_measurable_separable, exact ⟨measurable_iff_comap_le.2 le_rfl, (hum i).is_separable_range⟩ end end filtration /-! ### Stopping times -/ /-- A stopping time with respect to some filtration `f` is a function `τ` such that for all `i`, the preimage of `{j | j ≤ i}` along `τ` is measurable with respect to `f i`. Intuitively, the stopping time `τ` describes some stopping rule such that at time `i`, we may determine it with the information we have at time `i`. -/ def is_stopping_time [preorder ι] (f : filtration ι m) (τ : α → ι) := ∀ i : ι, measurable_set[f i] $ {x | τ x ≤ i} lemma is_stopping_time_const [preorder ι] (f : filtration ι m) (i : ι) : is_stopping_time f (λ x, i) := λ j, by simp only [measurable_set.const] section measurable_set section preorder variables [preorder ι] {f : filtration ι m} {τ : α → ι} protected lemma is_stopping_time.measurable_set_le (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | τ x ≤ i} := hτ i lemma is_stopping_time.measurable_set_lt_of_pred [pred_order ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | τ x < i} := begin by_cases hi_min : is_min i, { suffices : {x : α | τ x < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 x, simp only [set.mem_set_of_eq, set.mem_empty_eq, iff_false], rw is_min_iff_forall_not_lt at hi_min, exact hi_min (τ x), }, have : {x : α | τ x < i} = τ ⁻¹' (set.Iio i) := rfl, rw [this, ←Iic_pred_of_not_is_min hi_min], exact f.mono (pred_le i) _ (hτ.measurable_set_le $ pred i), end end preorder section countable_stopping_time namespace is_stopping_time variables [partial_order ι] {τ : α → ι} {f : filtration ι m} protected lemma measurable_set_eq_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {a | τ a = i} := begin have : {a | τ a = i} = {a | τ a ≤ i} \ (⋃ (j ∈ set.range τ) (hj : j < i), {a | τ a ≤ j}), { ext1 a, simp only [set.mem_set_of_eq, set.mem_range, set.Union_exists, set.Union_Union_eq', set.mem_diff, set.mem_Union, exists_prop, not_exists, not_and, not_le], split; intro h, { simp only [h, lt_iff_le_not_le, le_refl, and_imp, imp_self, implies_true_iff, and_self], }, { have h_lt_or_eq : τ a < i ∨ τ a = i := lt_or_eq_of_le h.1, rcases h_lt_or_eq with h_lt | rfl, { exfalso, exact h.2 a h_lt (le_refl (τ a)), }, { refl, }, }, }, rw this, refine (hτ.measurable_set_le i).diff _, refine measurable_set.bUnion h_countable (λ j hj, _), by_cases hji : j < i, { simp only [hji, set.Union_true], exact f.mono hji.le _ (hτ.measurable_set_le j), }, { simp only [hji, set.Union_false], exact @measurable_set.empty _ (f i), }, end protected lemma measurable_set_eq_of_encodable [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {a | τ a = i} := hτ.measurable_set_eq_of_countable (set.countable_encodable _) i protected lemma measurable_set_lt_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {a | τ a < i} := begin have : {a | τ a < i} = {a | τ a ≤ i} \ {a | τ a = i}, { ext1 x, simp [lt_iff_le_and_ne], }, rw this, exact (hτ.measurable_set_le i).diff (hτ.measurable_set_eq_of_countable h_countable i), end protected lemma measurable_set_lt_of_encodable [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {a | τ a < i} := hτ.measurable_set_lt_of_countable (set.countable_encodable _) i protected lemma measurable_set_ge_of_countable {ι} [linear_order ι] {τ : α → ι} {f : filtration ι m} (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[f i] {a | i ≤ τ a} := begin have : {x | i ≤ τ x} = {x | τ x < i}ᶜ, { ext1 x, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_lt], }, rw this, exact (hτ.measurable_set_lt_of_countable h_countable i).compl, end protected lemma measurable_set_ge_of_encodable {ι} [linear_order ι] {τ : α → ι} {f : filtration ι m} [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {a | i ≤ τ a} := hτ.measurable_set_ge_of_countable (set.countable_encodable _) i end is_stopping_time end countable_stopping_time section linear_order variables [linear_order ι] {f : filtration ι m} {τ : α → ι} lemma is_stopping_time.measurable_set_gt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | i < τ x} := begin have : {x | i < τ x} = {x | τ x ≤ i}ᶜ, { ext1 x, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_le], }, rw this, exact (hτ.measurable_set_le i).compl, end section topological_space variables [topological_space ι] [order_topology ι] [first_countable_topology ι] /-- Auxiliary lemma for `is_stopping_time.measurable_set_lt`. -/ lemma is_stopping_time.measurable_set_lt_of_is_lub (hτ : is_stopping_time f τ) (i : ι) (h_lub : is_lub (set.Iio i) i) : measurable_set[f i] {x | τ x < i} := begin by_cases hi_min : is_min i, { suffices : {x : α | τ x < i} = ∅, by { rw this, exact @measurable_set.empty _ (f i), }, ext1 x, simp only [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact is_min_iff_forall_not_lt.mp hi_min (τ x), }, obtain ⟨seq, -, -, h_tendsto, h_bound⟩ : ∃ seq : ℕ → ι, monotone seq ∧ (∀ j, seq j ≤ i) ∧ tendsto seq at_top (𝓝 i) ∧ (∀ j, seq j < i), from h_lub.exists_seq_monotone_tendsto (not_is_min_iff.mp hi_min), have h_Ioi_eq_Union : set.Iio i = ⋃ j, { k | k ≤ seq j}, { ext1 k, simp only [set.mem_Iio, set.mem_Union, set.mem_set_of_eq], refine ⟨λ hk_lt_i, _, λ h_exists_k_le_seq, _⟩, { rw tendsto_at_top' at h_tendsto, have h_nhds : set.Ici k ∈ 𝓝 i, from mem_nhds_iff.mpr ⟨set.Ioi k, set.Ioi_subset_Ici le_rfl, is_open_Ioi, hk_lt_i⟩, obtain ⟨a, ha⟩ : ∃ (a : ℕ), ∀ (b : ℕ), b ≥ a → k ≤ seq b := h_tendsto (set.Ici k) h_nhds, exact ⟨a, ha a le_rfl⟩, }, { obtain ⟨j, hk_seq_j⟩ := h_exists_k_le_seq, exact hk_seq_j.trans_lt (h_bound j), }, }, have h_lt_eq_preimage : {x : α | τ x < i} = τ ⁻¹' (set.Iio i), { ext1 x, simp only [set.mem_set_of_eq, set.mem_preimage, set.mem_Iio], }, rw [h_lt_eq_preimage, h_Ioi_eq_Union], simp only [set.preimage_Union, set.preimage_set_of_eq], exact measurable_set.Union (λ n, f.mono (h_bound n).le _ (hτ.measurable_set_le (seq n))), end lemma is_stopping_time.measurable_set_lt (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | τ x < i} := begin obtain ⟨i', hi'_lub⟩ : ∃ i', is_lub (set.Iio i) i', from exists_lub_Iio i, cases lub_Iio_eq_self_or_Iio_eq_Iic i hi'_lub with hi'_eq_i h_Iio_eq_Iic, { rw ← hi'_eq_i at hi'_lub ⊢, exact hτ.measurable_set_lt_of_is_lub i' hi'_lub, }, { have h_lt_eq_preimage : {x : α | τ x < i} = τ ⁻¹' (set.Iio i) := rfl, rw [h_lt_eq_preimage, h_Iio_eq_Iic], exact f.mono (lub_Iio_le i hi'_lub) _ (hτ.measurable_set_le i'), }, end lemma is_stopping_time.measurable_set_ge (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | i ≤ τ x} := begin have : {x | i ≤ τ x} = {x | τ x < i}ᶜ, { ext1 x, simp only [set.mem_set_of_eq, set.mem_compl_eq, not_lt], }, rw this, exact (hτ.measurable_set_lt i).compl, end lemma is_stopping_time.measurable_set_eq (hτ : is_stopping_time f τ) (i : ι) : measurable_set[f i] {x | τ x = i} := begin have : {x | τ x = i} = {x | τ x ≤ i} ∩ {x | τ x ≥ i}, { ext1 x, simp only [set.mem_set_of_eq, ge_iff_le, set.mem_inter_eq, le_antisymm_iff], }, rw this, exact (hτ.measurable_set_le i).inter (hτ.measurable_set_ge i), end lemma is_stopping_time.measurable_set_eq_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {x | τ x = i} := f.mono hle _ $ hτ.measurable_set_eq i lemma is_stopping_time.measurable_set_lt_le (hτ : is_stopping_time f τ) {i j : ι} (hle : i ≤ j) : measurable_set[f j] {x | τ x < i} := f.mono hle _ $ hτ.measurable_set_lt i end topological_space end linear_order section encodable lemma is_stopping_time_of_measurable_set_eq [preorder ι] [encodable ι] {f : filtration ι m} {τ : α → ι} (hτ : ∀ i, measurable_set[f i] {x | τ x = i}) : is_stopping_time f τ := begin intro i, rw show {x | τ x ≤ i} = ⋃ k ≤ i, {x | τ x = k}, by { ext, simp }, refine measurable_set.bUnion (set.countable_encodable _) (λ k hk, _), exact f.mono hk _ (hτ k), end end encodable end measurable_set namespace is_stopping_time protected lemma max [linear_order ι] {f : filtration ι m} {τ π : α → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ x, max (τ x) (π x)) := begin intro i, simp_rw [max_le_iff, set.set_of_and], exact (hτ i).inter (hπ i), end protected lemma max_const [linear_order ι] {f : filtration ι m} {τ : α → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ x, max (τ x) i) := hτ.max (is_stopping_time_const f i) protected lemma min [linear_order ι] {f : filtration ι m} {τ π : α → ι} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (λ x, min (τ x) (π x)) := begin intro i, simp_rw [min_le_iff, set.set_of_or], exact (hτ i).union (hπ i), end protected lemma min_const [linear_order ι] {f : filtration ι m} {τ : α → ι} (hτ : is_stopping_time f τ) (i : ι) : is_stopping_time f (λ x, min (τ x) i) := hτ.min (is_stopping_time_const f i) lemma add_const [add_group ι] [preorder ι] [covariant_class ι ι (function.swap (+)) (≤)] [covariant_class ι ι (+) (≤)] {f : filtration ι m} {τ : α → ι} (hτ : is_stopping_time f τ) {i : ι} (hi : 0 ≤ i) : is_stopping_time f (λ x, τ x + i) := begin intro j, simp_rw [← le_sub_iff_add_le], exact f.mono (sub_le_self j hi) _ (hτ (j - i)), end lemma add_const_nat {f : filtration ℕ m} {τ : α → ℕ} (hτ : is_stopping_time f τ) {i : ℕ} : is_stopping_time f (λ x, τ x + i) := begin refine is_stopping_time_of_measurable_set_eq (λ j, _), by_cases hij : i ≤ j, { simp_rw [eq_comm, ← nat.sub_eq_iff_eq_add hij, eq_comm], exact f.mono (j.sub_le i) _ (hτ.measurable_set_eq (j - i)) }, { rw not_le at hij, convert measurable_set.empty, ext x, simp only [set.mem_empty_eq, iff_false], rintro (hx : τ x + i = j), linarith }, end -- generalize to certain encodable type? lemma add {f : filtration ℕ m} {τ π : α → ℕ} (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : is_stopping_time f (τ + π) := begin intro i, rw (_ : {x | (τ + π) x ≤ i} = ⋃ k ≤ i, {x | π x = k} ∩ {x | τ x + k ≤ i}), { exact measurable_set.Union (λ k, measurable_set.Union_Prop (λ hk, (hπ.measurable_set_eq_le hk).inter (hτ.add_const_nat i))) }, ext, simp only [pi.add_apply, set.mem_set_of_eq, set.mem_Union, set.mem_inter_eq, exists_prop], refine ⟨λ h, ⟨π x, by linarith, rfl, h⟩, _⟩, rintro ⟨j, hj, rfl, h⟩, assumption end section preorder variables [preorder ι] {f : filtration ι m} {τ π : α → ι} /-- The associated σ-algebra with a stopping time. -/ protected def measurable_space (hτ : is_stopping_time f τ) : measurable_space α := { measurable_set' := λ s, ∀ i : ι, measurable_set[f i] (s ∩ {x | τ x ≤ i}), measurable_set_empty := λ i, (set.empty_inter {x | τ x ≤ i}).symm ▸ @measurable_set.empty _ (f i), measurable_set_compl := λ s hs i, begin rw (_ : sᶜ ∩ {x | τ x ≤ i} = (sᶜ ∪ {x | τ x ≤ i}ᶜ) ∩ {x | τ x ≤ i}), { refine measurable_set.inter _ _, { rw ← set.compl_inter, exact (hs i).compl }, { exact hτ i} }, { rw set.union_inter_distrib_right, simp only [set.compl_inter_self, set.union_empty] } end, measurable_set_Union := λ s hs i, begin rw forall_swap at hs, rw set.Union_inter, exact measurable_set.Union (hs i), end } protected lemma measurable_set (hτ : is_stopping_time f τ) (s : set α) : measurable_set[hτ.measurable_space] s ↔ ∀ i : ι, measurable_set[f i] (s ∩ {x | τ x ≤ i}) := iff.rfl lemma measurable_space_mono (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (hle : τ ≤ π) : hτ.measurable_space ≤ hπ.measurable_space := begin intros s hs i, rw (_ : s ∩ {x | π x ≤ i} = s ∩ {x | τ x ≤ i} ∩ {x | π x ≤ i}), { exact (hs i).inter (hπ i) }, { ext, simp only [set.mem_inter_eq, iff_self_and, and.congr_left_iff, set.mem_set_of_eq], intros hle' _, exact le_trans (hle _) hle' }, end lemma measurable_space_le_of_encodable [encodable ι] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {x | τ x ≤ i}) at hs, rw (_ : s = ⋃ i, s ∩ {x | τ x ≤ i}), { exact measurable_set.Union (λ i, f.le i _ (hs i)) }, { ext x, split; rw set.mem_Union, { exact λ hx, ⟨τ x, hx, le_rfl⟩ }, { rintro ⟨_, hx, _⟩, exact hx } } end lemma measurable_space_le' [is_countably_generated (at_top : filter ι)] [(at_top : filter ι).ne_bot] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {x | τ x ≤ i}) at hs, obtain ⟨seq : ℕ → ι, h_seq_tendsto⟩ := at_top.exists_seq_tendsto, rw (_ : s = ⋃ n, s ∩ {x | τ x ≤ seq n}), { exact measurable_set.Union (λ i, f.le (seq i) _ (hs (seq i))), }, { ext x, split; rw set.mem_Union, { intros hx, suffices : ∃ i, τ x ≤ seq i, from ⟨this.some, hx, this.some_spec⟩, rw tendsto_at_top at h_seq_tendsto, exact (h_seq_tendsto (τ x)).exists, }, { rintro ⟨_, hx, _⟩, exact hx }, }, all_goals { apply_instance, }, end lemma measurable_space_le {ι} [semilattice_sup ι] {f : filtration ι m} {τ : α → ι} [is_countably_generated (at_top : filter ι)] (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := begin casesI is_empty_or_nonempty ι, { haveI : is_empty α := ⟨λ x, is_empty.false (τ x)⟩, intros s hsτ, suffices hs : s = ∅, by { rw hs, exact measurable_set.empty, }, haveI : unique (set α) := set.unique_empty, rw [unique.eq_default s, unique.eq_default ∅], }, exact measurable_space_le' hτ, end example {f : filtration ℕ m} {τ : α → ℕ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le example {f : filtration ℝ m} {τ : α → ℝ} (hτ : is_stopping_time f τ) : hτ.measurable_space ≤ m := hτ.measurable_space_le @[simp] lemma measurable_space_const (f : filtration ι m) (i : ι) : (is_stopping_time_const f i).measurable_space = f i := begin ext1 s, change measurable_set[(is_stopping_time_const f i).measurable_space] s ↔ measurable_set[f i] s, rw is_stopping_time.measurable_set, split; intro h, { specialize h i, simpa only [le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp only [hij, set.set_of_false, set.inter_empty, measurable_set.empty], }, }, end lemma measurable_set_inter_eq_iff (hτ : is_stopping_time f τ) (s : set α) (i : ι) : measurable_set[hτ.measurable_space] (s ∩ {x | τ x = i}) ↔ measurable_set[f i] (s ∩ {x | τ x = i}) := begin have : ∀ j, ({x : α | τ x = i} ∩ {x : α | τ x ≤ j}) = {x : α | τ x = i} ∩ {x | i ≤ j}, { intro j, ext1 x, simp only [set.mem_inter_eq, set.mem_set_of_eq, and.congr_right_iff], intro hxi, rw hxi, }, split; intro h, { specialize h i, simpa only [set.inter_assoc, this, le_refl, set.set_of_true, set.inter_univ] using h, }, { intro j, rw [set.inter_assoc, this], by_cases hij : i ≤ j, { simp only [hij, set.set_of_true, set.inter_univ], exact f.mono hij _ h, }, { simp [hij], }, }, end lemma measurable_space_le_of_le_const (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ x, τ x ≤ i) : hτ.measurable_space ≤ f i := (measurable_space_mono hτ _ hτ_le).trans (measurable_space_const _ _).le lemma le_measurable_space_of_const_le (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ x, i ≤ τ x) : f i ≤ hτ.measurable_space := (measurable_space_const _ _).symm.le.trans (measurable_space_mono _ hτ hτ_le) end preorder instance sigma_finite_stopping_time {ι} [semilattice_sup ι] [order_bot ι] [(filter.at_top : filter ι).is_countably_generated] {μ : measure α} {f : filtration ι m} {τ : α → ι} [sigma_finite_filtration μ f] (hτ : is_stopping_time f τ) : sigma_finite (μ.trim hτ.measurable_space_le) := begin refine sigma_finite_trim_mono hτ.measurable_space_le _, { exact f ⊥, }, { exact hτ.le_measurable_space_of_const_le (λ _, bot_le), }, { apply_instance, }, end section linear_order variables [linear_order ι] {f : filtration ι m} {τ π : α → ι} protected lemma measurable_set_le' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {x | τ x ≤ i} := begin intro j, have : {x : α | τ x ≤ i} ∩ {x : α | τ x ≤ j} = {x : α | τ x ≤ min i j}, { ext1 x, simp only [set.mem_inter_eq, set.mem_set_of_eq, le_min_iff], }, rw this, exact f.mono (min_le_right i j) _ (hτ _), end protected lemma measurable_set_gt' (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {x | i < τ x} := begin have : {x : α | i < τ x} = {x : α | τ x ≤ i}ᶜ, by { ext1 x, simp, }, rw this, exact (hτ.measurable_set_le' i).compl, end protected lemma measurable_set_eq' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {x | τ x = i} := begin rw [← set.univ_inter {x | τ x = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq i, end protected lemma measurable_set_ge' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {x | i ≤ τ x} := begin have : {x | i ≤ τ x} = {x | τ x = i} ∪ {x | i < τ x}, { ext1 x, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union_eq], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq' i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_lt' [topological_space ι] [order_topology ι] [first_countable_topology ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {x | τ x < i} := begin have : {x | τ x < i} = {x | τ x ≤ i} \ {x | τ x = i}, { ext1 x, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq' i), end section countable protected lemma measurable_set_eq_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {x | τ x = i} := begin rw [← set.univ_inter {x | τ x = i}, measurable_set_inter_eq_iff, set.univ_inter], exact hτ.measurable_set_eq_of_countable h_countable i, end protected lemma measurable_set_eq_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {a | τ a = i} := hτ.measurable_set_eq_of_countable' (set.countable_encodable _) i protected lemma measurable_set_ge_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {x | i ≤ τ x} := begin have : {x | i ≤ τ x} = {x | τ x = i} ∪ {x | i < τ x}, { ext1 x, simp only [le_iff_lt_or_eq, set.mem_set_of_eq, set.mem_union_eq], rw [@eq_comm _ i, or_comm], }, rw this, exact (hτ.measurable_set_eq_of_countable' h_countable i).union (hτ.measurable_set_gt' i), end protected lemma measurable_set_ge_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {a | i ≤ τ a} := hτ.measurable_set_ge_of_countable' (set.countable_encodable _) i protected lemma measurable_set_lt_of_countable' (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) (i : ι) : measurable_set[hτ.measurable_space] {x | τ x < i} := begin have : {x | τ x < i} = {x | τ x ≤ i} \ {x | τ x = i}, { ext1 x, simp only [lt_iff_le_and_ne, set.mem_set_of_eq, set.mem_diff], }, rw this, exact (hτ.measurable_set_le' i).diff (hτ.measurable_set_eq_of_countable' h_countable i), end protected lemma measurable_set_lt_of_encodable' [encodable ι] (hτ : is_stopping_time f τ) (i : ι) : measurable_set[hτ.measurable_space] {a | τ a < i} := hτ.measurable_set_lt_of_countable' (set.countable_encodable _) i protected lemma measurable_space_le_of_countable (hτ : is_stopping_time f τ) (h_countable : (set.range τ).countable) : hτ.measurable_space ≤ m := begin intros s hs, change ∀ i, measurable_set[f i] (s ∩ {x | τ x ≤ i}) at hs, rw (_ : s = ⋃ (i ∈ set.range τ), s ∩ {x | τ x ≤ i}), { exact measurable_set.bUnion h_countable (λ i _, f.le i _ (hs i)), }, { ext x, split; rw set.mem_Union, { exact λ hx, ⟨τ x, by simpa using hx⟩,}, { rintro ⟨i, hx⟩, simp only [set.mem_range, set.Union_exists, set.mem_Union, set.mem_inter_eq, set.mem_set_of_eq, exists_prop, exists_and_distrib_right] at hx, exact hx.1.2, } } end end countable protected lemma measurable [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] τ := @measurable_of_Iic ι α _ _ _ hτ.measurable_space _ _ _ _ (λ i, hτ.measurable_set_le' i) protected lemma measurable_of_le [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) {i : ι} (hτ_le : ∀ x, τ x ≤ i) : measurable[f i] τ := hτ.measurable.mono (measurable_space_le_of_le_const _ hτ_le) le_rfl lemma measurable_space_min (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : (hτ.min hπ).measurable_space = hτ.measurable_space ⊓ hπ.measurable_space := begin refine le_antisymm _ _, { exact le_inf (measurable_space_mono _ hτ (λ _, min_le_left _ _)) (measurable_space_mono _ hπ (λ _, min_le_right _ _)), }, { intro s, change measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s → measurable_set[(hτ.min hπ).measurable_space] s, simp_rw is_stopping_time.measurable_set, have : ∀ i, {x | min (τ x) (π x) ≤ i} = {x | τ x ≤ i} ∪ {x | π x ≤ i}, { intro i, ext1 x, simp, }, simp_rw [this, set.inter_union_distrib_left], exact λ h i, (h.left i).union (h.right i), }, end lemma measurable_set_min_iff (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set α) : measurable_set[(hτ.min hπ).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[hπ.measurable_space] s := by { rw measurable_space_min, refl, } lemma measurable_space_min_const (hτ : is_stopping_time f τ) {i : ι} : (hτ.min_const i).measurable_space = hτ.measurable_space ⊓ f i := by rw [hτ.measurable_space_min (is_stopping_time_const _ i), measurable_space_const] lemma measurable_set_min_const_iff (hτ : is_stopping_time f τ) (s : set α) {i : ι} : measurable_set[(hτ.min_const i).measurable_space] s ↔ measurable_set[hτ.measurable_space] s ∧ measurable_set[f i] s := by rw [measurable_space_min_const, measurable_space.measurable_set_inf] lemma measurable_set_inter_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set α) (hs : measurable_set[hτ.measurable_space] s) : measurable_set[(hτ.min hπ).measurable_space] (s ∩ {x | τ x ≤ π x}) := begin simp_rw is_stopping_time.measurable_set at ⊢ hs, intro i, have : (s ∩ {x | τ x ≤ π x} ∩ {x | min (τ x) (π x) ≤ i}) = (s ∩ {x | τ x ≤ i}) ∩ {x | min (τ x) (π x) ≤ i} ∩ {x | min (τ x) i ≤ min (min (τ x) (π x)) i}, { ext1 x, simp only [min_le_iff, set.mem_inter_eq, set.mem_set_of_eq, le_min_iff, le_refl, true_and, and_true, true_or, or_true], by_cases hτi : τ x ≤ i, { simp only [hτi, true_or, and_true, and.congr_right_iff], intro hx, split; intro h, { exact or.inl h, }, { cases h, { exact h, }, { exact hτi.trans h, }, }, }, simp only [hτi, false_or, and_false, false_and, iff_false, not_and, not_le, and_imp], refine λ hx hτ_le_π, lt_of_lt_of_le _ hτ_le_π, rw ← not_le, exact hτi, }, rw this, refine ((hs i).inter ((hτ.min hπ) i)).inter _, apply measurable_set_le, { exact (hτ.min_const i).measurable_of_le (λ _, min_le_right _ _), }, { exact ((hτ.min hπ).min_const i).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_inter_le_iff [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) (s : set α) : measurable_set[hτ.measurable_space] (s ∩ {x | τ x ≤ π x}) ↔ measurable_set[(hτ.min hπ).measurable_space] (s ∩ {x | τ x ≤ π x}) := begin split; intro h, { have : s ∩ {x | τ x ≤ π x} = s ∩ {x | τ x ≤ π x} ∩ {x | τ x ≤ π x}, by rw [set.inter_assoc, set.inter_self], rw this, exact measurable_set_inter_le _ _ _ h, }, { rw measurable_set_min_iff at h, exact h.1, }, end lemma measurable_set_le_stopping_time [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {x | τ x ≤ π x} := begin rw hτ.measurable_set, intro j, have : {x | τ x ≤ π x} ∩ {x | τ x ≤ j} = {x | min (τ x) j ≤ min (π x) j} ∩ {x | τ x ≤ j}, { ext1 x, simp only [set.mem_inter_eq, set.mem_set_of_eq, min_le_iff, le_min_iff, le_refl, and_true, and.congr_left_iff], intro h, simp only [h, or_self, and_true], by_cases hj : j ≤ π x, { simp only [hj, h.trans hj, or_self], }, { simp only [hj, or_false], }, }, rw this, refine measurable_set.inter _ (hτ.measurable_set_le j), apply measurable_set_le, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_stopping_time_le [topological_space ι] [second_countable_topology ι] [order_topology ι] [measurable_space ι] [borel_space ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hπ.measurable_space] {x | τ x ≤ π x} := begin suffices : measurable_set[(hτ.min hπ).measurable_space] {x : α | τ x ≤ π x}, by { rw measurable_set_min_iff hτ hπ at this, exact this.2, }, rw [← set.univ_inter {x : α | τ x ≤ π x}, ← hτ.measurable_set_inter_le_iff hπ, set.univ_inter], exact measurable_set_le_stopping_time hτ hπ, end lemma measurable_set_eq_stopping_time [add_group ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] [has_measurable_sub₂ ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {x | τ x = π x} := begin rw hτ.measurable_set, intro j, have : {x | τ x = π x} ∩ {x | τ x ≤ j} = {x | min (τ x) j = min (π x) j} ∩ {x | τ x ≤ j} ∩ {x | π x ≤ j}, { ext1 x, simp only [set.mem_inter_eq, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hσ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hσ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end lemma measurable_set_eq_stopping_time_of_encodable [encodable ι] [topological_space ι] [measurable_space ι] [borel_space ι] [order_topology ι] [measurable_singleton_class ι] [second_countable_topology ι] (hτ : is_stopping_time f τ) (hπ : is_stopping_time f π) : measurable_set[hτ.measurable_space] {x | τ x = π x} := begin rw hτ.measurable_set, intro j, have : {x | τ x = π x} ∩ {x | τ x ≤ j} = {x | min (τ x) j = min (π x) j} ∩ {x | τ x ≤ j} ∩ {x | π x ≤ j}, { ext1 x, simp only [set.mem_inter_eq, set.mem_set_of_eq], refine ⟨λ h, ⟨⟨_, h.2⟩, _⟩, λ h, ⟨_, h.1.2⟩⟩, { rw h.1, }, { rw ← h.1, exact h.2, }, { cases h with h' hπ_le, cases h' with h_eq hτ_le, rwa [min_eq_left hτ_le, min_eq_left hπ_le] at h_eq, }, }, rw this, refine measurable_set.inter (measurable_set.inter _ (hτ.measurable_set_le j)) (hπ.measurable_set_le j), apply measurable_set_eq_fun_of_encodable, { exact (hτ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, { exact (hπ.min_const j).measurable_of_le (λ _, min_le_right _ _), }, end end linear_order end is_stopping_time section linear_order /-! ## Stopped value and stopped process -/ /-- Given a map `u : ι → α → E`, its stopped value with respect to the stopping time `τ` is the map `x ↦ u (τ x) x`. -/ def stopped_value (u : ι → α → β) (τ : α → ι) : α → β := λ x, u (τ x) x lemma stopped_value_const (u : ι → α → β) (i : ι) : stopped_value u (λ x, i) = u i := rfl variable [linear_order ι] /-- Given a map `u : ι → α → E`, the stopped process with respect to `τ` is `u i x` if `i ≤ τ x`, and `u (τ x) x` otherwise. Intuitively, the stopped process stops evolving once the stopping time has occured. -/ def stopped_process (u : ι → α → β) (τ : α → ι) : ι → α → β := λ i x, u (min i (τ x)) x lemma stopped_process_eq_of_le {u : ι → α → β} {τ : α → ι} {i : ι} {x : α} (h : i ≤ τ x) : stopped_process u τ i x = u i x := by simp [stopped_process, min_eq_left h] lemma stopped_process_eq_of_ge {u : ι → α → β} {τ : α → ι} {i : ι} {x : α} (h : τ x ≤ i) : stopped_process u τ i x = u (τ x) x := by simp [stopped_process, min_eq_right h] section prog_measurable variables [measurable_space ι] [topological_space ι] [order_topology ι] [second_countable_topology ι] [borel_space ι] [topological_space β] {u : ι → α → β} {τ : α → ι} {f : filtration ι m} lemma prog_measurable_min_stopping_time [metrizable_space ι] (hτ : is_stopping_time f τ) : prog_measurable f (λ i x, min i (τ x)) := begin intro i, let m_prod : measurable_space (set.Iic i × α) := measurable_space.prod _ (f i), let m_set : ∀ t : set (set.Iic i × α), measurable_space t := λ _, @subtype.measurable_space (set.Iic i × α) _ m_prod, let s := {p : set.Iic i × α | τ p.2 ≤ i}, have hs : measurable_set[m_prod] s, from @measurable_snd (set.Iic i) α _ (f i) _ (hτ i), have h_meas_fst : ∀ t : set (set.Iic i × α), measurable[m_set t] (λ x : t, ((x : set.Iic i × α).fst : ι)), from λ t, (@measurable_subtype_coe (set.Iic i × α) m_prod _).fst.subtype_coe, apply measurable.strongly_measurable, refine measurable_of_restrict_of_restrict_compl hs _ _, { refine @measurable.min _ _ _ _ _ (m_set s) _ _ _ _ _ (h_meas_fst s) _, refine @measurable_of_Iic ι s _ _ _ (m_set s) _ _ _ _ (λ j, _), have h_set_eq : (λ x : s, τ (x : set.Iic i × α).snd) ⁻¹' set.Iic j = (λ x : s, (x : set.Iic i × α).snd) ⁻¹' {x | τ x ≤ min i j}, { ext1 x, simp only [set.mem_preimage, set.mem_Iic, iff_and_self, le_min_iff, set.mem_set_of_eq], exact λ _, x.prop, }, rw h_set_eq, suffices h_meas : @measurable _ _ (m_set s) (f i) (λ x : s, (x : set.Iic i × α).snd), from h_meas (f.mono (min_le_left _ _) _ (hτ.measurable_set_le (min i j))), exact measurable_snd.comp (@measurable_subtype_coe _ m_prod _), }, { suffices h_min_eq_left : (λ x : sᶜ, min ↑((x : set.Iic i × α).fst) (τ (x : set.Iic i × α).snd)) = λ x : sᶜ, ↑((x : set.Iic i × α).fst), { rw [set.restrict, h_min_eq_left], exact h_meas_fst _, }, ext1 x, rw min_eq_left, have hx_fst_le : ↑(x : set.Iic i × α).fst ≤ i, from (x : set.Iic i × α).fst.prop, refine hx_fst_le.trans (le_of_lt _), convert x.prop, simp only [not_le, set.mem_compl_eq, set.mem_set_of_eq], }, end lemma prog_measurable.stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : prog_measurable f (stopped_process u τ) := h.comp (prog_measurable_min_stopping_time hτ) (λ i x, min_le_left _ _) lemma prog_measurable.adapted_stopped_process [metrizable_space ι] (h : prog_measurable f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (h.stopped_process hτ).adapted lemma prog_measurable.strongly_measurable_stopped_process [metrizable_space ι] (hu : prog_measurable f u) (hτ : is_stopping_time f τ) (i : ι) : strongly_measurable (stopped_process u τ i) := (hu.adapted_stopped_process hτ i).mono (f.le _) lemma strongly_measurable_stopped_value_of_le (h : prog_measurable f u) (hτ : is_stopping_time f τ) {n : ι} (hτ_le : ∀ x, τ x ≤ n) : strongly_measurable[f n] (stopped_value u τ) := begin have : stopped_value u τ = (λ (p : set.Iic n × α), u ↑(p.fst) p.snd) ∘ (λ x, (⟨τ x, hτ_le x⟩, x)), { ext1 x, simp only [stopped_value, function.comp_app, subtype.coe_mk], }, rw this, refine strongly_measurable.comp_measurable (h n) _, exact (hτ.measurable_of_le hτ_le).subtype_mk.prod_mk measurable_id, end lemma measurable_stopped_value [metrizable_space β] [measurable_space β] [borel_space β] (hf_prog : prog_measurable f u) (hτ : is_stopping_time f τ) : measurable[hτ.measurable_space] (stopped_value u τ) := begin have h_str_meas : ∀ i, strongly_measurable[f i] (stopped_value u (λ x, min (τ x) i)), from λ i, strongly_measurable_stopped_value_of_le hf_prog (hτ.min_const i) (λ _, min_le_right _ _), intros t ht i, suffices : stopped_value u τ ⁻¹' t ∩ {x : α | τ x ≤ i} = stopped_value u (λ x, min (τ x) i) ⁻¹' t ∩ {x : α | τ x ≤ i}, by { rw this, exact ((h_str_meas i).measurable ht).inter (hτ.measurable_set_le i), }, ext1 x, simp only [stopped_value, set.mem_inter_eq, set.mem_preimage, set.mem_set_of_eq, and.congr_left_iff], intro h, rw min_eq_left h, end end prog_measurable end linear_order section nat /-! ### Filtrations indexed by `ℕ` -/ open filtration variables {f : filtration ℕ m} {u : ℕ → α → β} {τ π : α → ℕ} lemma stopped_value_sub_eq_sum [add_comm_group β] (hle : τ ≤ π) : stopped_value u π - stopped_value u τ = λ x, (∑ i in finset.Ico (τ x) (π x), (u (i + 1) - u i)) x := begin ext x, rw [finset.sum_Ico_eq_sub _ (hle x), finset.sum_range_sub, finset.sum_range_sub], simp [stopped_value], end lemma stopped_value_sub_eq_sum' [add_comm_group β] (hle : τ ≤ π) {N : ℕ} (hbdd : ∀ x, π x ≤ N) : stopped_value u π - stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {x | τ x ≤ i ∧ i < π x} (u (i + 1) - u i)) x := begin rw stopped_value_sub_eq_sum hle, ext x, simp only [finset.sum_apply, finset.sum_indicator_eq_sum_filter], refine finset.sum_congr _ (λ _ _, rfl), ext i, simp only [finset.mem_filter, set.mem_set_of_eq, finset.mem_range, finset.mem_Ico], exact ⟨λ h, ⟨lt_trans h.2 (nat.lt_succ_iff.2 $ hbdd _), h⟩, λ h, h.2⟩ end section add_comm_monoid variables [add_comm_monoid β] /-- For filtrations indexed by `ℕ`, `adapted` and `prog_measurable` are equivalent. This lemma provides `adapted f u → prog_measurable f u`. See `prog_measurable.adapted` for the reverse direction, which is true more generally. -/ lemma adapted.prog_measurable_of_nat [topological_space β] [has_continuous_add β] (h : adapted f u) : prog_measurable f u := begin intro i, have : (λ p : ↥(set.Iic i) × α, u ↑(p.fst) p.snd) = λ p : ↥(set.Iic i) × α, ∑ j in finset.range (i + 1), if ↑p.fst = j then u j p.snd else 0, { ext1 p, rw finset.sum_ite_eq, have hp_mem : (p.fst : ℕ) ∈ finset.range (i + 1) := finset.mem_range_succ_iff.mpr p.fst.prop, simp only [hp_mem, if_true], }, rw this, refine finset.strongly_measurable_sum _ (λ j hj, strongly_measurable.ite _ _ _), { suffices h_meas : measurable[measurable_space.prod _ (f i)] (λ a : ↥(set.Iic i) × α, (a.fst : ℕ)), from h_meas (measurable_set_singleton j), exact measurable_fst.subtype_coe, }, { have h_le : j ≤ i, from finset.mem_range_succ_iff.mp hj, exact (strongly_measurable.mono (h j) (f.mono h_le)).comp_measurable measurable_snd, }, { exact strongly_measurable_const, }, end /-- For filtrations indexed by `ℕ`, the stopped process obtained from an adapted process is adapted. -/ lemma adapted.stopped_process_of_nat [topological_space β] [has_continuous_add β] (hu : adapted f u) (hτ : is_stopping_time f τ) : adapted f (stopped_process u τ) := (hu.prog_measurable_of_nat.stopped_process hτ).adapted lemma adapted.strongly_measurable_stopped_process_of_nat [topological_space β] [has_continuous_add β] (hτ : is_stopping_time f τ) (hu : adapted f u) (n : ℕ) : strongly_measurable (stopped_process u τ n) := hu.prog_measurable_of_nat.strongly_measurable_stopped_process hτ n lemma stopped_value_eq {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : stopped_value u τ = λ x, (∑ i in finset.range (N + 1), set.indicator {x | τ x = i} (u i)) x := begin ext y, rw [stopped_value, finset.sum_apply, finset.sum_eq_single (τ y)], { rw set.indicator_of_mem, exact rfl }, { exact λ i hi hneq, set.indicator_of_not_mem hneq.symm _ }, { intro hy, rw set.indicator_of_not_mem, exact λ _, hy (finset.mem_range.2 $ lt_of_le_of_lt (hbdd _) (nat.lt_succ_self _)) } end lemma stopped_process_eq (n : ℕ) : stopped_process u τ n = set.indicator {a | n ≤ τ a} (u n) + ∑ i in finset.range n, set.indicator {a | τ a = i} (u i) := begin ext x, rw [pi.add_apply, finset.sum_apply], cases le_or_lt n (τ x), { rw [stopped_process_eq_of_le h, set.indicator_of_mem, finset.sum_eq_zero, add_zero], { intros m hm, rw finset.mem_range at hm, exact set.indicator_of_not_mem ((lt_of_lt_of_le hm h).ne.symm) _ }, { exact h } }, { rw [stopped_process_eq_of_ge (le_of_lt h), finset.sum_eq_single_of_mem (τ x)], { rw [set.indicator_of_not_mem, zero_add, set.indicator_of_mem], { exact rfl }, -- refl does not work { exact not_le.2 h } }, { rwa [finset.mem_range] }, { intros b hb hneq, rw set.indicator_of_not_mem, exact hneq.symm } }, end end add_comm_monoid section normed_group variables [normed_group β] {p : ℝ≥0∞} {μ : measure α} lemma mem_ℒp_stopped_process (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) (n : ℕ) : mem_ℒp (stopped_process u τ n) p μ := begin rw stopped_process_eq, refine mem_ℒp.add _ _, { exact mem_ℒp.indicator (f.le n {a : α | n ≤ τ a} (hτ.measurable_set_ge n)) (hu n) }, { suffices : mem_ℒp (λ x, ∑ (i : ℕ) in finset.range n, {a : α | τ a = i}.indicator (u i) x) p μ, { convert this, ext1 x, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : α | τ a = i} (hτ.measurable_set_eq i) }, end lemma integrable_stopped_process (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) (n : ℕ) : integrable (stopped_process u τ n) μ := by { simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_process hτ hu n, } lemma mem_ℒp_stopped_value (hτ : is_stopping_time f τ) (hu : ∀ n, mem_ℒp (u n) p μ) {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : mem_ℒp (stopped_value u τ) p μ := begin rw stopped_value_eq hbdd, suffices : mem_ℒp (λ x, ∑ (i : ℕ) in finset.range (N + 1), {a : α | τ a = i}.indicator (u i) x) p μ, { convert this, ext1 x, simp only [finset.sum_apply] }, refine mem_ℒp_finset_sum _ (λ i hi, mem_ℒp.indicator _ (hu i)), exact f.le i {a : α | τ a = i} (hτ.measurable_set_eq i) end lemma integrable_stopped_value (hτ : is_stopping_time f τ) (hu : ∀ n, integrable (u n) μ) {N : ℕ} (hbdd : ∀ x, τ x ≤ N) : integrable (stopped_value u τ) μ := by { simp_rw ← mem_ℒp_one_iff_integrable at hu ⊢, exact mem_ℒp_stopped_value hτ hu hbdd, } end normed_group end nat section piecewise_const variables [preorder ι] {𝒢 : filtration ι m} {τ η : α → ι} {i j : ι} {s : set α} [decidable_pred (∈ s)] /-- Given stopping times `τ` and `η` which are bounded below, `set.piecewise s τ η` is also a stopping time with respect to the same filtration. -/ lemma is_stopping_time.piecewise_of_le (hτ_st : is_stopping_time 𝒢 τ) (hη_st : is_stopping_time 𝒢 η) (hτ : ∀ x, i ≤ τ x) (hη : ∀ x, i ≤ η x) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise τ η) := begin intro n, have : {x | s.piecewise τ η x ≤ n} = (s ∩ {x | τ x ≤ n}) ∪ (sᶜ ∩ {x | η x ≤ n}), { ext1 x, simp only [set.piecewise, set.mem_inter_eq, set.mem_set_of_eq, and.congr_right_iff], by_cases hx : x ∈ s; simp [hx], }, rw this, by_cases hin : i ≤ n, { have hs_n : measurable_set[𝒢 n] s, from 𝒢.mono hin _ hs, exact (hs_n.inter (hτ_st n)).union (hs_n.compl.inter (hη_st n)), }, { have hτn : ∀ x, ¬ τ x ≤ n := λ x hτn, hin ((hτ x).trans hτn), have hηn : ∀ x, ¬ η x ≤ n := λ x hηn, hin ((hη x).trans hηn), simp [hτn, hηn], }, end lemma is_stopping_time_piecewise_const (hij : i ≤ j) (hs : measurable_set[𝒢 i] s) : is_stopping_time 𝒢 (s.piecewise (λ _, i) (λ _, j)) := (is_stopping_time_const 𝒢 i).piecewise_of_le (is_stopping_time_const 𝒢 j) (λ x, le_rfl) (λ _, hij) hs lemma stopped_value_piecewise_const {ι' : Type*} {i j : ι'} {f : ι' → α → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.piecewise (f i) (f j) := by { ext x, rw stopped_value, by_cases hx : x ∈ s; simp [hx] } lemma stopped_value_piecewise_const' {ι' : Type*} {i j : ι'} {f : ι' → α → ℝ} : stopped_value f (s.piecewise (λ _, i) (λ _, j)) = s.indicator (f i) + sᶜ.indicator (f j) := by { ext x, rw stopped_value, by_cases hx : x ∈ s; simp [hx] } end piecewise_const end measure_theory
735566c95d8dd57953b98d86a4610f2071949773
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/lint/type_classes.lean
37a282f92aaeee3edd70f20a4e512e20d5b12899
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
16,309
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import tactic.lint.basic /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority * `has_inhabited_instances` checks that every type has an `inhabited` instance * `impossible_instance` checks that there are no instances which can never apply * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments * `dangerous_instance` checks for instances that generate subproblems with metavariables * `fails_quickly` checks that type class resolution finishes quickly * `has_coe_variable` checks that there is no instance of type `has_coe α t` * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]` * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. -/ open tactic /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-- checks whether an instance that always applies has priority ≥ 1000. -/ private meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. See note [lower instance priority] for instructions to change the priority.", auto_decls := tt } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ private meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← open_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, auto_decls := ff, no_errors_found := "No types have missing inhabited instances", errors_found := "TYPES ARE MISSING INHABITED INSTANCES", is_fast := ff } attribute [nolint has_inhabited_instance] pempty /-- Checks whether an instance can never be applied. -/ private meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter] meta def linter.impossible_instance : linter := { test := impossible_instance, auto_decls := tt, no_errors_found := "All instances are applicable", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and therefore can never succeed. Either mark the arguments with square brackets (if it is a class), or don't make it an instance" } /-- Checks whether an instance can never be applied. -/ private meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← open_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, auto_decls := tt, no_errors_found := "All declarations have correct type-class arguments", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ private meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← open_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← open_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, auto_decls := tt, no_errors_found := "No type-class searches timed out", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search.", is_fast := ff } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable, or `has_coe t α` where `α` does not occur in `t`. See note [use has_coe_t]. -/ private meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a %%b) ← return d.type.pi_codomain | return none, if a.is_var then return $ some $ "illegal instance, first argument is variable" else if b.is_var ∧ ¬ b.occurs a then return $ some $ "illegal instance, second argument is variable not occurring in first argument" else return none /-- A linter object for `has_coe_variable`. -/ @[linter] meta def linter.has_coe_variable : linter := { test := has_coe_variable, auto_decls := tt, no_errors_found := "No invalid `has_coe` instances", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ private meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_nondep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, auto_decls := ff, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- Checks whether a declaration is `Prop`-valued and takes a `decidable* _` hypothesis that is unused elsewhere in the type. In this case, that hypothesis can be replaced with `classical` in the proof. Theorems in the `decidable` namespace are exempt from the check. -/ private meta def decidable_classical (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, ff ← pure $ (`decidable).is_prefix_of d.to_name | return none, (binders, _) ← get_pi_binders_nondep d.type, let deceq_binders := binders.filter $ λ pr, pr.2.type.is_app_of `decidable_eq ∨ pr.2.type.is_app_of `decidable_pred ∨ pr.2.type.is_app_of `decidable_rel ∨ pr.2.type.is_app_of `decidable, if deceq_binders.length = 0 then return none else (λ s, some $ "The following `decidable` hypotheses should be replaced with `classical` in the proof. " ++ s) <$> print_arguments deceq_binders /-- A linter object for `decidable_classical`. -/ @[linter] meta def linter.decidable_classical : linter := { test := decidable_classical, auto_decls := ff, no_errors_found := "No uses of `decidable` arguments should be replaced with `classical`", errors_found := "USES OF `decidable` SHOULD BE REPLACED WITH `classical` IN THE PROOF." } /- The file `logic/basic.lean` emphasizes the differences between what holds under classical and non-classical logic. It makes little sense to make all these lemmas classical, so we add them to the list of lemmas which are not checked by the linter `decidable_classical`. -/ attribute [nolint decidable_classical] dec_em not.decidable_imp_symm private meta def has_coe_to_fun_linter (d : declaration) : tactic (option string) := retrieve $ do mk_meta_var d.type >>= set_goals ∘ pure, args ← unfreezing intros, expr.sort _ ← target | pure none, let ty : expr := (expr.const d.to_name d.univ_levels).mk_app args, some coe_fn_inst ← try_core $ to_expr ``(_root_.has_coe_to_fun %%ty) >>= mk_instance | pure none, some trans_inst@(expr.app (expr.app _ trans_inst_1) trans_inst_2) ← try_core $ to_expr ``(@_root_.coe_fn_trans %%ty _ _ _) | pure none, tt ← succeeds $ unify trans_inst coe_fn_inst transparency.reducible | pure none, set_bool_option `pp.all true, trans_inst_1 ← pp trans_inst_1, trans_inst_2 ← pp trans_inst_2, pure $ format.to_string $ "`has_coe_to_fun` instance is definitionally equal to a transitive instance composed of: " ++ trans_inst_1.group.indent 2 ++ format.line ++ "and" ++ trans_inst_2.group.indent 2 /-- Linter that checks whether `has_coe_to_fun` instances comply with Note [function coercion]. -/ @[linter] meta def linter.has_coe_to_fun : linter := { test := has_coe_to_fun_linter, auto_decls := tt, no_errors_found := "has_coe_to_fun is used correctly", errors_found := "INVALID/MISSING `has_coe_to_fun` instances. You should add a `has_coe_to_fun` instance for the following types. See Note function coercions]." }
e7e003ef2d5084b9e04991e278e88e959753b873
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/IO4.lean
fb9a156ad476efc9220dfadfe025405f05da09e5
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
202
lean
import system.IO set_option trace.compiler.code_gen true definition main : IO unit := do { n ← return (10:nat), if n = (11:nat) then put_nat 1 else put_nat 2 } vm_eval main
61fe75f052971412961dd474c9286bb2aaa5b165
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/check2.lean
b5ee7ee528f3ca6f737a1e32fcca30d38d4a9abc
[ "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
21
lean
-- #check eq.rec_on
743e2124fefefe827325eef92fef77e51c041adc
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/topology/local_homeomorph.lean
b30bd74df899253877bb3f6bf9ea749fe6d55227
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,523
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.local_equiv import topology.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. -/ open function set filter open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_inhabited_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) := ⟨_, λ e, e.to_local_equiv.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := λ _ h, map_source e h lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[{x}ᶜ] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_inter_source_eq (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) := e.image_eq_target_inter_inv_preimage (inter_subset_right _ _) lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_inter_target_eq (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) := e.symm.image_inter_source_eq _ /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (mem_nhds_sets e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds (e : local_homeomorph α β) {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := begin apply subset.antisymm, { exact e.continuous_on.preimage_interior_subset_interior_preimage e.open_source }, { calc e.source ∩ interior (e ⁻¹' s) = (e.source ∩ interior (e ⁻¹' s)) ∩ (e ⁻¹' e.target) : by mfld_set_tac ... = (e.source ∩ e ⁻¹' (e.symm ⁻¹' (interior (e ⁻¹' s)))) ∩ (e ⁻¹' e.target) : begin have := e.to_local_equiv.source_inter_preimage_inv_preimage _, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' (e.target ∩ e.symm ⁻¹' (interior (e ⁻¹' s))) : by rw [inter_comm e.target, preimage_inter, inter_assoc] ... ⊆ e.source ∩ e ⁻¹' (e.target ∩ interior (e.symm ⁻¹' (e ⁻¹' s))) : begin apply inter_subset_inter (subset.refl _) (preimage_mono _), exact e.continuous_on_symm.preimage_interior_subset_interior_preimage e.open_target end ... = e.source ∩ e ⁻¹' (interior (e.target ∩ e.symm ⁻¹' (e ⁻¹' s))) : by rw [interior_inter, e.open_target.interior_eq] ... = e.source ∩ e ⁻¹' (interior (e.target ∩ s)) : begin have := e.to_local_equiv.target_inter_inv_preimage_preimage, simp only [coe_coe_symm, coe_coe] at this, rw this end ... = e.source ∩ e ⁻¹' e.target ∩ e ⁻¹' (interior s) : by rw [interior_inter, preimage_inter, e.open_target.interior_eq, inter_assoc] ... = e.source ∩ e ⁻¹' (interior s) : by mfld_set_tac } end lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (s ∩ e.source)) := begin refine image_open_of_open _ (is_open_inter hs e.open_source) _, simp, end /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := { open_source := is_open_inter e.open_source hs, open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs, continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _), continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _), ..e.to_local_equiv.restr s} @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, have := interior_mono h, rwa e.open_source.interior_eq at this end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq], rw [← inter_assoc, inter_self] end /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl lemma refl_source : (local_homeomorph.refl α).source = univ := rfl lemma refl_target : (local_homeomorph.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma refl_coe : (local_homeomorph.refl α : α → α) = id := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl lemma of_set_source : (of_set s hs).source = s := rfl lemma of_set_target : (of_set s hs).target = s := rfl @[simp, mfld_simps] lemma of_set_coe : (of_set s hs : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open_inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := continuous_on.prod (e.continuous_to_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_to_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), continuous_inv_fun := continuous_on.prod (e.continuous_inv_fun.comp continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (e'.continuous_inv_fun.comp continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), ..e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e' : α × γ → β × δ) = λp, (e p.1, e' p.2) := rfl lemma prod_coe_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : ((e.prod e').symm : β × δ → α × γ) = λp, (e.symm p.1, e'.symm p.2) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans end prod section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := begin split, { assume f_cont, have : e (e.symm x) = x := e.right_inv h, rw ← this at f_cont, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target h), rw [← continuous_within_at_inter this, inter_comm], exact continuous_within_at.comp f_cont ((e.continuous_at (e.map_target h)).continuous_within_at) (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at ((f ∘ e) ∘ e.symm) (s ∩ e.target) x, { apply continuous_within_at.comp fe_cont, apply (e.continuous_at_symm h).continuous_within_at, assume x hx, simp [hx.1, hx.2, e.map_target] }, have : continuous_within_at f (s ∩ e.target) x := continuous_within_at.congr this (λy hy, by simp [hy.2]) (by simp [h]), rwa continuous_within_at_inter at this, exact mem_nhds_sets e.open_target h } end /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin split, { assume f_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (e.map_source hx.1), rw e.left_inv hx.1 at this, have A := f_cont _ hx.2, rw this at A, exact A.mono (inter_subset_right _ _), }, { assume fe_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), rw this, have : e.source ∈ 𝓝 (e.symm x) := mem_nhds_sets e.open_source (e.map_target (h hx)), rw [← continuous_within_at_inter this, inter_comm], exact fe_cont _ (by simp [hx, h hx, e.map_target (h hx)]) } end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin rw [← continuous_within_at_inter' h, ← continuous_within_at_inter' h], split, { assume f_cont, have : e.source ∈ 𝓝 (f x) := mem_nhds_sets e.open_source hx, apply continuous_within_at.comp (e.continuous_on (f x) hx) f_cont (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) } end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := begin split, { assume f_cont, exact e.continuous_on.comp f_cont h }, { assume fe_cont, have : continuous_on (e.symm ∘ e ∘ f) s, { apply continuous_on.comp e.continuous_on_symm fe_cont, assume x hx, have : f x ∈ e.source := h hx, simp [this] }, refine continuous_on.congr_mono this (λx hx, _) (subset.refl _), have : f x ∈ e.source := h hx, simp [this] } end end continuity /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : homeomorph α β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } @[simp, mfld_simps] lemma to_homeomorph_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h' : α → β) = e := rfl @[simp, mfld_simps] lemma to_homeomorph_symm_coe (h : e.source = (univ : set α)) (h' : e.target = univ) : ((e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').symm : β → α) = e.symm := rfl /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : homeomorph α β) (e' : homeomorph β γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe : (e.to_local_homeomorph : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_homeomorph_coe_symm : (e.to_local_homeomorph.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables [nonempty α] variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ noncomputable def to_local_homeomorph : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ @[simp, mfld_simps] lemma to_local_homeomorph_coe : ⇑(h.to_local_homeomorph f) = f := rfl @[simp, mfld_simps] lemma source : (h.to_local_homeomorph f).source = set.univ := rfl @[simp, mfld_simps] lemma target : (h.to_local_homeomorph f).target = set.range f := image_univ end open_embedding -- We close and reopen the namespace to avoid -- picking up the unnecessary `[nonempty α]` typeclass argument namespace open_embedding lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict (e : α → β) s := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
4a261a76530cdf24b6f688065af0459d461e00eb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/atoms.lean
5b0884c84a67a017d64e06648ce5b3666b67c4c4
[ "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
20,823
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import order.complete_boolean_algebra import order.modular_lattice import data.fintype.basic /-! # Atoms, Coatoms, and Simple Lattices This module defines atoms, which are minimal non-`⊥` elements in bounded lattices, simple lattices, which are lattices with only two elements, and related ideas. ## Main definitions ### Atoms and Coatoms * `is_atom a` indicates that the only element below `a` is `⊥`. * `is_coatom a` indicates that the only element above `a` is `⊤`. ### Atomic and Atomistic Lattices * `is_atomic` indicates that every element other than `⊥` is above an atom. * `is_coatomic` indicates that every element other than `⊤` is below a coatom. * `is_atomistic` indicates that every element is the `Sup` of a set of atoms. * `is_coatomistic` indicates that every element is the `Inf` of a set of coatoms. ### Simple Lattices * `is_simple_lattice` indicates that a bounded lattice has only two elements, `⊥` and `⊤`. * `is_simple_lattice.bounded_distrib_lattice` * Given an instance of `is_simple_lattice`, we provide the following definitions. These are not made global instances as they contain data : * `is_simple_lattice.boolean_algebra` * `is_simple_lattice.complete_lattice` * `is_simple_lattice.complete_boolean_algebra` ## Main results * `is_atom_dual_iff_is_coatom` and `is_coatom_dual_iff_is_atom` express the (definitional) duality of `is_atom` and `is_coatom`. * `is_simple_lattice_iff_is_atom_top` and `is_simple_lattice_iff_is_coatom_bot` express the connection between atoms, coatoms, and simple lattices * `is_compl.is_atom_iff_is_coatom` and `is_compl.is_coatom_if_is_atom`: In a modular bounded lattice, a complement of an atom is a coatom and vice versa. * ``is_atomic_iff_is_coatomic`: A modular complemented lattice is atomic iff it is coatomic. -/ variable {α : Type*} section atoms section is_atom variable [order_bot α] /-- An atom of an `order_bot` is an element with no other element between it and `⊥`, which is not `⊥`. -/ def is_atom (a : α) : Prop := a ≠ ⊥ ∧ (∀ b, b < a → b = ⊥) lemma eq_bot_or_eq_of_le_atom {a b : α} (ha : is_atom a) (hab : b ≤ a) : b = ⊥ ∨ b = a := hab.lt_or_eq.imp_left (ha.2 b) lemma is_atom.Iic {x a : α} (ha : is_atom a) (hax : a ≤ x) : is_atom (⟨a, hax⟩ : set.Iic x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_atom.of_is_atom_coe_Iic {x : α} {a : set.Iic x} (ha : is_atom a) : is_atom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, hba.le.trans a.prop⟩ hba)⟩ end is_atom section is_coatom variable [order_top α] /-- A coatom of an `order_top` is an element with no other element between it and `⊤`, which is not `⊤`. -/ def is_coatom (a : α) : Prop := a ≠ ⊤ ∧ (∀ b, a < b → b = ⊤) lemma eq_top_or_eq_of_coatom_le {a b : α} (ha : is_coatom a) (hab : a ≤ b) : b = ⊤ ∨ b = a := hab.lt_or_eq.imp (ha.2 b) eq_comm.2 lemma is_coatom.Ici {x a : α} (ha : is_coatom a) (hax : x ≤ a) : is_coatom (⟨a, hax⟩ : set.Ici x) := ⟨λ con, ha.1 (subtype.mk_eq_mk.1 con), λ ⟨b, hb⟩ hba, subtype.mk_eq_mk.2 (ha.2 b hba)⟩ lemma is_coatom.of_is_coatom_coe_Ici {x : α} {a : set.Ici x} (ha : is_coatom a) : is_coatom (a : α) := ⟨λ con, ha.1 (subtype.ext con), λ b hba, subtype.mk_eq_mk.1 (ha.2 ⟨b, le_trans a.prop hba.le⟩ hba)⟩ end is_coatom section pairwise lemma is_atom.inf_eq_bot_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : a ⊓ b = ⊥ := or.elim (eq_bot_or_eq_of_le_atom ha inf_le_left) id (λ h1, or.elim (eq_bot_or_eq_of_le_atom hb inf_le_right) id (λ h2, false.rec _ (hab (le_antisymm (inf_eq_left.mp h1) (inf_eq_right.mp h2))))) lemma is_atom.disjoint_of_ne [semilattice_inf_bot α] {a b : α} (ha : is_atom a) (hb : is_atom b) (hab : a ≠ b) : disjoint a b := disjoint_iff.mpr (is_atom.inf_eq_bot_of_ne ha hb hab) lemma is_coatom.sup_eq_top_of_ne [semilattice_sup_top α] {a b : α} (ha : is_coatom a) (hb : is_coatom b) (hab : a ≠ b) : a ⊔ b = ⊤ := or.elim (eq_top_or_eq_of_coatom_le ha le_sup_left) id (λ h1, or.elim (eq_top_or_eq_of_coatom_le hb le_sup_right) id (λ h2, false.rec _ (hab (le_antisymm (sup_eq_right.mp h2) (sup_eq_left.mp h1))))) end pairwise variable {a : α} @[simp] lemma is_coatom_dual_iff_is_atom [order_bot α] : is_coatom (order_dual.to_dual a) ↔ is_atom a := iff.rfl @[simp] lemma is_atom_dual_iff_is_coatom [order_top α] : is_atom (order_dual.to_dual a) ↔ is_coatom a := iff.rfl end atoms section atomic variable (α) /-- A lattice is atomic iff every element other than `⊥` has an atom below it. -/ class is_atomic [order_bot α] : Prop := (eq_bot_or_exists_atom_le : ∀ (b : α), b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) /-- A lattice is coatomic iff every element other than `⊤` has a coatom above it. -/ class is_coatomic [order_top α] : Prop := (eq_top_or_exists_le_coatom : ∀ (b : α), b = ⊤ ∨ ∃ (a : α), is_coatom a ∧ b ≤ a) export is_atomic (eq_bot_or_exists_atom_le) is_coatomic (eq_top_or_exists_le_coatom) variable {α} @[simp] theorem is_coatomic_dual_iff_is_atomic [order_bot α] : is_coatomic (order_dual α) ↔ is_atomic α := ⟨λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩, λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩⟩ @[simp] theorem is_atomic_dual_iff_is_coatomic [order_top α] : is_atomic (order_dual α) ↔ is_coatomic α := ⟨λ h, ⟨λ b, by apply h.eq_bot_or_exists_atom_le⟩, λ h, ⟨λ b, by apply h.eq_top_or_exists_le_coatom⟩⟩ namespace is_atomic variables [order_bot α] [is_atomic α] instance is_coatomic_dual : is_coatomic (order_dual α) := is_coatomic_dual_iff_is_atomic.2 ‹is_atomic α› instance {x : α} : is_atomic (set.Iic x) := ⟨λ ⟨y, hy⟩, (eq_bot_or_exists_atom_le y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, hay.trans hy⟩, ha.Iic (hay.trans hy), hay⟩)⟩ end is_atomic namespace is_coatomic variables [order_top α] [is_coatomic α] instance is_coatomic : is_atomic (order_dual α) := is_atomic_dual_iff_is_coatomic.2 ‹is_coatomic α› instance {x : α} : is_coatomic (set.Ici x) := ⟨λ ⟨y, hy⟩, (eq_top_or_exists_le_coatom y).imp subtype.mk_eq_mk.2 (λ ⟨a, ha, hay⟩, ⟨⟨a, le_trans hy hay⟩, ha.Ici (le_trans hy hay), hay⟩)⟩ end is_coatomic theorem is_atomic_iff_forall_is_atomic_Iic [order_bot α] : is_atomic α ↔ ∀ (x : α), is_atomic (set.Iic x) := ⟨@is_atomic.set.Iic.is_atomic _ _, λ h, ⟨λ x, ((@eq_bot_or_exists_atom_le _ _ (h x)) (⊤ : set.Iic x)).imp subtype.mk_eq_mk.1 (exists_imp_exists' coe (λ ⟨a, ha⟩, and.imp_left (is_atom.of_is_atom_coe_Iic)))⟩⟩ theorem is_coatomic_iff_forall_is_coatomic_Ici [order_top α] : is_coatomic α ↔ ∀ (x : α), is_coatomic (set.Ici x) := is_atomic_dual_iff_is_coatomic.symm.trans $ is_atomic_iff_forall_is_atomic_Iic.trans $ forall_congr (λ x, is_coatomic_dual_iff_is_atomic.symm.trans iff.rfl) end atomic section atomistic variables (α) [complete_lattice α] /-- A lattice is atomistic iff every element is a `Sup` of a set of atoms. -/ class is_atomistic : Prop := (eq_Sup_atoms : ∀ (b : α), ∃ (s : set α), b = Sup s ∧ ∀ a, a ∈ s → is_atom a) /-- A lattice is coatomistic iff every element is an `Inf` of a set of coatoms. -/ class is_coatomistic : Prop := (eq_Inf_coatoms : ∀ (b : α), ∃ (s : set α), b = Inf s ∧ ∀ a, a ∈ s → is_coatom a) export is_atomistic (eq_Sup_atoms) is_coatomistic (eq_Inf_coatoms) variable {α} @[simp] theorem is_coatomistic_dual_iff_is_atomistic : is_coatomistic (order_dual α) ↔ is_atomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩, λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩⟩ @[simp] theorem is_atomistic_dual_iff_is_coatomistic : is_atomistic (order_dual α) ↔ is_coatomistic α := ⟨λ h, ⟨λ b, by apply h.eq_Sup_atoms⟩, λ h, ⟨λ b, by apply h.eq_Inf_coatoms⟩⟩ namespace is_atomistic instance is_coatomistic_dual [h : is_atomistic α] : is_coatomistic (order_dual α) := is_coatomistic_dual_iff_is_atomistic.2 h variable [is_atomistic α] @[priority 100] instance : is_atomic α := ⟨λ b, by { rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, le_Sup h.some_spec⟩ } } ⟩ end is_atomistic section is_atomistic variables [is_atomistic α] @[simp] theorem Sup_atoms_le_eq (b : α) : Sup {a : α | is_atom a ∧ a ≤ b} = b := begin rcases eq_Sup_atoms b with ⟨s, rfl, hs⟩, exact le_antisymm (Sup_le (λ _, and.right)) (Sup_le_Sup (λ a ha, ⟨hs a ha, le_Sup ha⟩)), end @[simp] theorem Sup_atoms_eq_top : Sup {a : α | is_atom a} = ⊤ := begin refine eq.trans (congr rfl (set.ext (λ x, _))) (Sup_atoms_le_eq ⊤), exact (and_iff_left le_top).symm, end theorem le_iff_atom_le_imp {a b : α} : a ≤ b ↔ ∀ c : α, is_atom c → c ≤ a → c ≤ b := ⟨λ ab c hc ca, le_trans ca ab, λ h, begin rw [← Sup_atoms_le_eq a, ← Sup_atoms_le_eq b], exact Sup_le_Sup (λ c hc, ⟨hc.1, h c hc.1 hc.2⟩), end⟩ end is_atomistic namespace is_coatomistic instance is_atomistic_dual [h : is_coatomistic α] : is_atomistic (order_dual α) := is_atomistic_dual_iff_is_coatomistic.2 h variable [is_coatomistic α] @[priority 100] instance : is_coatomic α := ⟨λ b, by { rcases eq_Inf_coatoms b with ⟨s, rfl, hs⟩, cases s.eq_empty_or_nonempty with h h, { simp [h] }, { exact or.intro_right _ ⟨h.some, hs _ h.some_spec, Inf_le h.some_spec⟩ } } ⟩ end is_coatomistic end atomistic /-- A lattice is simple iff it has only two elements, `⊥` and `⊤`. -/ class is_simple_lattice (α : Type*) [bounded_lattice α] extends nontrivial α : Prop := (eq_bot_or_eq_top : ∀ (a : α), a = ⊥ ∨ a = ⊤) export is_simple_lattice (eq_bot_or_eq_top) theorem is_simple_lattice_iff_is_simple_lattice_order_dual [bounded_lattice α] : is_simple_lattice α ↔ is_simple_lattice (order_dual α) := begin split; intro i; haveI := i, { exact { exists_pair_ne := @exists_pair_ne α _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top ((order_dual.of_dual a)) : _ ∨ _) } }, { exact { exists_pair_ne := @exists_pair_ne (order_dual α) _, eq_bot_or_eq_top := λ a, or.symm (eq_bot_or_eq_top (order_dual.to_dual a)) } } end section is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] instance : is_simple_lattice (order_dual α) := is_simple_lattice_iff_is_simple_lattice_order_dual.1 (by apply_instance) @[simp] lemma is_atom_top : is_atom (⊤ : α) := ⟨top_ne_bot, λ a ha, or.resolve_right (eq_bot_or_eq_top a) (ne_of_lt ha)⟩ @[simp] lemma is_coatom_bot : is_coatom (⊥ : α) := is_atom_dual_iff_is_coatom.1 is_atom_top end is_simple_lattice namespace is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] /-- A simple `bounded_lattice` is also distributive. -/ @[priority 100] instance : bounded_distrib_lattice α := { le_sup_inf := λ x y z, by { rcases eq_bot_or_eq_top x with rfl | rfl; simp }, .. (infer_instance : bounded_lattice α) } @[priority 100] instance : is_atomic α := ⟨λ b, (eq_bot_or_eq_top b).imp_right (λ h, ⟨⊤, ⟨is_atom_top, ge_of_eq h⟩⟩)⟩ @[priority 100] instance : is_coatomic α := is_atomic_dual_iff_is_coatomic.1 is_simple_lattice.is_atomic section decidable_eq variable [decidable_eq α] /-- Every simple lattice is order-isomorphic to `bool`. -/ def order_iso_bool : α ≃o bool := { to_fun := λ x, x = ⊤, inv_fun := λ x, cond x ⊤ ⊥, left_inv := λ x, by { rcases (eq_bot_or_eq_top x) with rfl | rfl; simp [bot_ne_top] }, right_inv := λ x, by { cases x; simp [bot_ne_top] }, map_rel_iff' := λ a b, begin rcases (eq_bot_or_eq_top a) with rfl | rfl, { simp [bot_ne_top] }, { rcases (eq_bot_or_eq_top b) with rfl | rfl, { simp [bot_ne_top.symm, bot_ne_top, bool.ff_lt_tt] }, { simp [bot_ne_top] } } end } @[priority 200] instance : fintype α := fintype.of_equiv bool (order_iso_bool.to_equiv).symm /-- A simple `bounded_lattice` is also a `boolean_algebra`. -/ protected def boolean_algebra : boolean_algebra α := { compl := λ x, if x = ⊥ then ⊤ else ⊥, sdiff := λ x y, if x = ⊤ ∧ y = ⊥ then ⊤ else ⊥, sdiff_eq := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; simp [bot_ne_top, has_sdiff.sdiff, compl], inf_compl_le_bot := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, top_le_sup_compl := λ x, by rcases eq_bot_or_eq_top x with rfl | rfl; simp, sup_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; rcases eq_bot_or_eq_top y with rfl | rfl; simp [bot_ne_top], inf_inf_sdiff := λ x y, by rcases eq_bot_or_eq_top x with rfl | rfl; rcases eq_bot_or_eq_top y with rfl | rfl; simp, .. is_simple_lattice.bounded_distrib_lattice } end decidable_eq open_locale classical /-- A simple `bounded_lattice` is also complete. -/ protected noncomputable def complete_lattice : complete_lattice α := { Sup := λ s, if ⊤ ∈ s then ⊤ else ⊥, Inf := λ s, if ⊥ ∈ s then ⊥ else ⊤, le_Sup := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_pos h } }, Sup_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_neg, intro con, exact bot_ne_top (eq_top_iff.2 (h ⊤ con)) }, { exact le_top } }, Inf_le := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { rw if_pos h }, { exact le_top } }, le_Inf := λ s x h, by { rcases eq_bot_or_eq_top x with rfl | rfl, { exact bot_le }, { rw if_neg, intro con, exact top_ne_bot (eq_bot_iff.2 (h ⊥ con)) } }, .. (infer_instance : bounded_lattice α) } /-- A simple `bounded_lattice` is also a `complete_boolean_algebra`. -/ protected noncomputable def complete_boolean_algebra : complete_boolean_algebra α := { infi_sup_le_sup_Inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_sup_eq, ← Inf_eq_infi], apply le_refl }, { simp only [top_sup_eq, le_top] }, }, inf_Sup_le_supr_inf := λ x s, by { rcases eq_bot_or_eq_top x with rfl | rfl, { simp only [bot_inf_eq, bot_le] }, { simp only [top_inf_eq, ← Sup_eq_supr], apply le_refl } }, .. is_simple_lattice.complete_lattice, .. is_simple_lattice.boolean_algebra } end is_simple_lattice namespace is_simple_lattice variables [complete_lattice α] [is_simple_lattice α] set_option default_priority 100 instance : is_atomistic α := ⟨λ b, (eq_bot_or_eq_top b).elim (λ h, ⟨∅, ⟨h.trans Sup_empty.symm, λ a ha, false.elim (set.not_mem_empty _ ha)⟩⟩) (λ h, ⟨{⊤}, h.trans Sup_singleton.symm, λ a ha, (set.mem_singleton_iff.1 ha).symm ▸ is_atom_top⟩)⟩ instance : is_coatomistic α := is_atomistic_dual_iff_is_coatomistic.1 is_simple_lattice.is_atomistic end is_simple_lattice namespace fintype namespace is_simple_lattice variables [bounded_lattice α] [is_simple_lattice α] [decidable_eq α] lemma univ : (finset.univ : finset α) = {⊤, ⊥} := begin change finset.map _ (finset.univ : finset bool) = _, rw fintype.univ_bool, simp only [finset.map_insert, function.embedding.coe_fn_mk, finset.map_singleton], refl, end lemma card : fintype.card α = 2 := (fintype.of_equiv_card _).trans fintype.card_bool end is_simple_lattice end fintype namespace bool instance : is_simple_lattice bool := ⟨λ a, begin rw [← finset.mem_singleton, or.comm, ← finset.mem_insert, top_eq_tt, bot_eq_ff, ← fintype.univ_bool], apply finset.mem_univ, end⟩ end bool theorem is_simple_lattice_iff_is_atom_top [bounded_lattice α] : is_simple_lattice α ↔ is_atom (⊤ : α) := ⟨λ h, @is_atom_top _ _ h, λ h, { exists_pair_ne := ⟨⊤, ⊥, h.1⟩, eq_bot_or_eq_top := λ a, ((eq_or_lt_of_le (@le_top _ _ a)).imp_right (h.2 a)).symm }⟩ theorem is_simple_lattice_iff_is_coatom_bot [bounded_lattice α] : is_simple_lattice α ↔ is_coatom (⊥ : α) := is_simple_lattice_iff_is_simple_lattice_order_dual.trans is_simple_lattice_iff_is_atom_top namespace set theorem is_simple_lattice_Iic_iff_is_atom [bounded_lattice α] {a : α} : is_simple_lattice (Iic a) ↔ is_atom a := is_simple_lattice_iff_is_atom_top.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ theorem is_simple_lattice_Ici_iff_is_coatom [bounded_lattice α] {a : α} : is_simple_lattice (Ici a) ↔ is_coatom a := is_simple_lattice_iff_is_coatom_bot.trans $ and_congr (not_congr subtype.mk_eq_mk) ⟨λ h b ab, subtype.mk_eq_mk.1 (h ⟨b, le_of_lt ab⟩ ab), λ h ⟨b, hab⟩ hbotb, subtype.mk_eq_mk.2 (h b (subtype.mk_lt_mk.1 hbotb))⟩ end set namespace order_iso @[simp] lemma is_atom_iff [order_bot α] {β : Type*} [order_bot β] (f : α ≃o β) (a : α) : is_atom (f a) ↔ is_atom a := and_congr (not_congr ⟨λ h, f.injective (f.map_bot.symm ▸ h), λ h, f.map_bot ▸ (congr rfl h)⟩) ⟨λ h b hb, f.injective ((h (f b) ((f : α ↪o β).lt_iff_lt.2 hb)).trans f.map_bot.symm), λ h b hb, f.symm.injective begin rw f.symm.map_bot, apply h, rw [← f.symm_apply_apply a], exact (f.symm : β ↪o α).lt_iff_lt.2 hb, end⟩ @[simp] lemma is_coatom_iff [order_top α] {β : Type*} [order_top β] (f : α ≃o β) (a : α) : is_coatom (f a) ↔ is_coatom a := f.dual.is_atom_iff a lemma is_simple_lattice_iff [bounded_lattice α] {β : Type*} [bounded_lattice β] (f : α ≃o β) : is_simple_lattice α ↔ is_simple_lattice β := by rw [is_simple_lattice_iff_is_atom_top, is_simple_lattice_iff_is_atom_top, ← f.is_atom_iff ⊤, f.map_top] lemma is_simple_lattice [bounded_lattice α] {β : Type*} [bounded_lattice β] [h : is_simple_lattice β] (f : α ≃o β) : is_simple_lattice α := f.is_simple_lattice_iff.mpr h lemma is_atomic_iff [order_bot α] {β : Type*} [order_bot β] (f : α ≃o β) : is_atomic α ↔ is_atomic β := begin suffices : (∀ b : α, b = ⊥ ∨ ∃ (a : α), is_atom a ∧ a ≤ b) ↔ (∀ b : β, b = ⊥ ∨ ∃ (a : β), is_atom a ∧ a ≤ b), from ⟨λ ⟨p⟩, ⟨this.mp p⟩, λ ⟨p⟩, ⟨this.mpr p⟩⟩, apply f.to_equiv.forall_congr, simp_rw [rel_iso.coe_fn_to_equiv], intro b, apply or_congr, { rw [f.apply_eq_iff_eq_symm_apply, map_bot], }, { split, { exact λ ⟨a, ha⟩, ⟨f a, ⟨(f.is_atom_iff a).mpr ha.1, f.le_iff_le.mpr ha.2⟩⟩, }, { rintros ⟨b, ⟨hb1, hb2⟩⟩, refine ⟨f.symm b, ⟨(f.symm.is_atom_iff b).mpr hb1, _⟩⟩, rwa [←f.le_iff_le, f.apply_symm_apply], }, }, end lemma is_coatomic_iff [order_top α] {β : Type*} [order_top β] (f : α ≃o β) : is_coatomic α ↔ is_coatomic β := by { rw [←is_atomic_dual_iff_is_coatomic, ←is_atomic_dual_iff_is_coatomic], exact f.dual.is_atomic_iff } end order_iso section is_modular_lattice variables [bounded_lattice α] [is_modular_lattice α] namespace is_compl variables {a b : α} (hc : is_compl a b) include hc lemma is_atom_iff_is_coatom : is_atom a ↔ is_coatom b := set.is_simple_lattice_Iic_iff_is_atom.symm.trans $ hc.Iic_order_iso_Ici.is_simple_lattice_iff.trans set.is_simple_lattice_Ici_iff_is_coatom lemma is_coatom_iff_is_atom : is_coatom a ↔ is_atom b := hc.symm.is_atom_iff_is_coatom.symm end is_compl variables [is_complemented α] lemma is_coatomic_of_is_atomic_of_is_complemented_of_is_modular [is_atomic α] : is_coatomic α := ⟨λ x, begin rcases exists_is_compl x with ⟨y, xy⟩, apply (eq_bot_or_exists_atom_le y).imp _ _, { rintro rfl, exact eq_top_of_is_compl_bot xy }, { rintro ⟨a, ha, ay⟩, rcases exists_is_compl (xy.symm.Iic_order_iso_Ici ⟨a, ay⟩) with ⟨⟨b, xb⟩, hb⟩, refine ⟨↑(⟨b, xb⟩ : set.Ici x), is_coatom.of_is_coatom_coe_Ici _, xb⟩, rw [← hb.is_atom_iff_is_coatom, order_iso.is_atom_iff], apply ha.Iic } end⟩ lemma is_atomic_of_is_coatomic_of_is_complemented_of_is_modular [is_coatomic α] : is_atomic α := is_coatomic_dual_iff_is_atomic.1 is_coatomic_of_is_atomic_of_is_complemented_of_is_modular theorem is_atomic_iff_is_coatomic : is_atomic α ↔ is_coatomic α := ⟨λ h, @is_coatomic_of_is_atomic_of_is_complemented_of_is_modular _ _ _ _ h, λ h, @is_atomic_of_is_coatomic_of_is_complemented_of_is_modular _ _ _ _ h⟩ end is_modular_lattice
da74fc5210b34b8cbbaab6bcaa6c9ef713a07e5c
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/data/fintype/basic.lean
4fc44af04bd0fdf167ed2b9353db5bfc7f136afa
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
42,441
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Finite types. -/ import data.finset import data.array.lemmas universes u v variables {α : Type*} {β : Type*} {γ : Type*} /-- `fintype α` means that `α` is finite, i.e. there are only finitely many distinct elements of type `α`. The evidence of this is a finset `elems` (a list up to permutation without duplicates), together with a proof that everything of type `α` is in the list. -/ class fintype (α : Type*) := (elems [] : finset α) (complete : ∀ x : α, x ∈ elems) namespace finset variable [fintype α] /-- `univ` is the universal finite set of type `finset α` implied from the assumption `fintype α`. -/ def univ : finset α := fintype.elems α @[simp] theorem mem_univ (x : α) : x ∈ (univ : finset α) := fintype.complete x @[simp] theorem mem_univ_val : ∀ x, x ∈ (univ : finset α).1 := mem_univ @[simp] lemma coe_univ : ↑(univ : finset α) = (set.univ : set α) := by ext; simp theorem subset_univ (s : finset α) : s ⊆ univ := λ a _, mem_univ a theorem eq_univ_iff_forall {s : finset α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] @[simp] lemma univ_inter [decidable_eq α] (s : finset α) : univ ∩ s = s := ext $ λ a, by simp @[simp] lemma inter_univ [decidable_eq α] (s : finset α) : s ∩ univ = s := by rw [inter_comm, univ_inter] @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (univ : finset α))] {δ : α → Sort*} (f g : Πi, δ i) : univ.piecewise f g = f := by { ext i, simp [piecewise] } lemma univ_map_equiv_to_embedding {α β : Type*} [fintype α] [fintype β] (e : α ≃ β) : univ.map e.to_embedding = univ := begin apply eq_univ_iff_forall.mpr, intro b, rw [mem_map], use e.symm b, simp, end end finset open finset function namespace fintype instance decidable_pi_fintype {α} {β : α → Type*} [∀a, decidable_eq (β a)] [fintype α] : decidable_eq (Πa, β a) := assume f g, decidable_of_iff (∀ a ∈ fintype.elems α, f a = g a) (by simp [function.funext_iff, fintype.complete]) instance decidable_forall_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∀ a, p a) := decidable_of_iff (∀ a ∈ @univ α _, p a) (by simp) instance decidable_exists_fintype {p : α → Prop} [decidable_pred p] [fintype α] : decidable (∃ a, p a) := decidable_of_iff (∃ a ∈ @univ α _, p a) (by simp) instance decidable_eq_equiv_fintype [decidable_eq β] [fintype α] : decidable_eq (α ≃ β) := λ a b, decidable_of_iff (a.1 = b.1) ⟨λ h, equiv.ext (congr_fun h), congr_arg _⟩ instance decidable_injective_fintype [decidable_eq α] [decidable_eq β] [fintype α] : decidable_pred (injective : (α → β) → Prop) := λ x, by unfold injective; apply_instance instance decidable_surjective_fintype [decidable_eq β] [fintype α] [fintype β] : decidable_pred (surjective : (α → β) → Prop) := λ x, by unfold surjective; apply_instance instance decidable_bijective_fintype [decidable_eq α] [decidable_eq β] [fintype α] [fintype β] : decidable_pred (bijective : (α → β) → Prop) := λ x, by unfold bijective; apply_instance instance decidable_left_inverse_fintype [decidable_eq α] [fintype α] (f : α → β) (g : β → α) : decidable (function.right_inverse f g) := show decidable (∀ x, g (f x) = x), by apply_instance instance decidable_right_inverse_fintype [decidable_eq β] [fintype β] (f : α → β) (g : β → α) : decidable (function.left_inverse f g) := show decidable (∀ x, f (g x) = x), by apply_instance /-- Construct a proof of `fintype α` from a universal multiset -/ def of_multiset [decidable_eq α] (s : multiset α) (H : ∀ x : α, x ∈ s) : fintype α := ⟨s.to_finset, by simpa using H⟩ /-- Construct a proof of `fintype α` from a universal list -/ def of_list [decidable_eq α] (l : list α) (H : ∀ x : α, x ∈ l) : fintype α := ⟨l.to_finset, by simpa using H⟩ theorem exists_univ_list (α) [fintype α] : ∃ l : list α, l.nodup ∧ ∀ x : α, x ∈ l := let ⟨l, e⟩ := quotient.exists_rep (@univ α _).1 in by have := and.intro univ.2 mem_univ_val; exact ⟨_, by rwa ← e at this⟩ /-- `card α` is the number of elements in `α`, defined when `α` is a fintype. -/ def card (α) [fintype α] : ℕ := (@univ α _).card /-- If `l` lists all the elements of `α` without duplicates, then `α ≃ fin (l.length)`. -/ def equiv_fin_of_forall_mem_list {α} [decidable_eq α] {l : list α} (h : ∀ x:α, x ∈ l) (nd : l.nodup) : α ≃ fin (l.length) := ⟨λ a, ⟨_, list.index_of_lt_length.2 (h a)⟩, λ i, l.nth_le i.1 i.2, λ a, by simp, λ ⟨i, h⟩, fin.eq_of_veq $ list.nodup_iff_nth_le_inj.1 nd _ _ (list.index_of_lt_length.2 (list.nth_le_mem _ _ _)) h $ by simp⟩ /-- There is (computably) a bijection between `α` and `fin n` where `n = card α`. Since it is not unique, and depends on which permutation of the universe list is used, the bijection is wrapped in `trunc` to preserve computability. -/ def equiv_fin (α) [fintype α] [decidable_eq α] : trunc (α ≃ fin (card α)) := by unfold card finset.card; exact quot.rec_on_subsingleton (@univ α _).1 (λ l (h : ∀ x:α, x ∈ l) (nd : l.nodup), trunc.mk (equiv_fin_of_forall_mem_list h nd)) mem_univ_val univ.2 theorem exists_equiv_fin (α) [fintype α] : ∃ n, nonempty (α ≃ fin n) := by haveI := classical.dec_eq α; exact ⟨card α, nonempty_of_trunc (equiv_fin α)⟩ /-- Given a linearly ordered fintype `α` of cardinal `k`, the equiv `mono_equiv_of_fin α h` is the increasing bijection between `fin k` and `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of a map `fin s.card → α` to avoid casting issues in further uses of this function. -/ noncomputable def mono_equiv_of_fin (α) [fintype α] [decidable_linear_order α] {k : ℕ} (h : fintype.card α = k) : fin k ≃ α := equiv.of_bijective (mono_of_fin univ h) begin apply set.bijective_iff_bij_on_univ.2, rw ← @coe_univ α _, exact mono_of_fin_bij_on (univ : finset α) h end instance (α : Type*) : subsingleton (fintype α) := ⟨λ ⟨s₁, h₁⟩ ⟨s₂, h₂⟩, by congr; simp [finset.ext_iff, h₁, h₂]⟩ protected def subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : fintype {x // p x} := ⟨⟨multiset.pmap subtype.mk s.1 (λ x, (H x).1), multiset.nodup_pmap (λ a _ b _, congr_arg subtype.val) s.2⟩, λ ⟨x, px⟩, multiset.mem_pmap.2 ⟨x, (H x).2 px, rfl⟩⟩ theorem subtype_card {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) : @card {x // p x} (fintype.subtype s H) = s.card := multiset.card_pmap _ _ _ theorem card_of_subtype {p : α → Prop} (s : finset α) (H : ∀ x : α, x ∈ s ↔ p x) [fintype {x // p x}] : card {x // p x} = s.card := by rw ← subtype_card s H; congr /-- Construct a fintype from a finset with the same elements. -/ def of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : fintype p := fintype.subtype s H @[simp] theorem card_of_finset {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) : @fintype.card p (of_finset s H) = s.card := fintype.subtype_card s H theorem card_of_finset' {p : set α} (s : finset α) (H : ∀ x, x ∈ s ↔ x ∈ p) [fintype p] : fintype.card p = s.card := by rw ← card_of_finset s H; congr /-- If `f : α → β` is a bijection and `α` is a fintype, then `β` is also a fintype. -/ def of_bijective [fintype α] (f : α → β) (H : function.bijective f) : fintype β := ⟨univ.map ⟨f, H.1⟩, λ b, let ⟨a, e⟩ := H.2 b in e ▸ mem_map_of_mem _ (mem_univ _)⟩ /-- If `f : α → β` is a surjection and `α` is a fintype, then `β` is also a fintype. -/ def of_surjective [fintype α] [decidable_eq β] (f : α → β) (H : function.surjective f) : fintype β := ⟨univ.image f, λ b, let ⟨a, e⟩ := H b in e ▸ mem_image_of_mem _ (mem_univ _)⟩ noncomputable def of_injective [fintype β] (f : α → β) (H : function.injective f) : fintype α := by letI := classical.dec; exact if hα : nonempty α then by letI := classical.inhabited_of_nonempty hα; exact of_surjective (inv_fun f) (inv_fun_surjective H) else ⟨∅, λ x, (hα ⟨x⟩).elim⟩ /-- If `f : α ≃ β` and `α` is a fintype, then `β` is also a fintype. -/ def of_equiv (α : Type*) [fintype α] (f : α ≃ β) : fintype β := of_bijective _ f.bijective theorem of_equiv_card [fintype α] (f : α ≃ β) : @card β (of_equiv α f) = card α := multiset.card_map _ _ theorem card_congr {α β} [fintype α] [fintype β] (f : α ≃ β) : card α = card β := by rw ← of_equiv_card f; congr theorem card_eq {α β} [F : fintype α] [G : fintype β] : card α = card β ↔ nonempty (α ≃ β) := ⟨λ h, ⟨by classical; calc α ≃ fin (card α) : trunc.out (equiv_fin α) ... ≃ fin (card β) : by rw h ... ≃ β : (trunc.out (equiv_fin β)).symm⟩, λ ⟨f⟩, card_congr f⟩ def of_subsingleton (a : α) [subsingleton α] : fintype α := ⟨{a}, λ b, finset.mem_singleton.2 (subsingleton.elim _ _)⟩ @[simp] theorem univ_of_subsingleton (a : α) [subsingleton α] : @univ _ (of_subsingleton a) = {a} := rfl @[simp] theorem card_of_subsingleton (a : α) [subsingleton α] : @fintype.card _ (of_subsingleton a) = 1 := rfl end fintype namespace set /-- Construct a finset enumerating a set `s`, given a `fintype` instance. -/ def to_finset (s : set α) [fintype s] : finset α := ⟨(@finset.univ s _).1.map subtype.val, multiset.nodup_map (λ a b, subtype.eq) finset.univ.2⟩ @[simp] theorem mem_to_finset {s : set α} [fintype s] {a : α} : a ∈ s.to_finset ↔ a ∈ s := by simp [to_finset] @[simp] theorem mem_to_finset_val {s : set α} [fintype s] {a : α} : a ∈ s.to_finset.1 ↔ a ∈ s := mem_to_finset -- We use an arbitrary `[fintype s]` instance here, -- not necessarily coming from a `[fintype α]`. @[simp] lemma to_finset_card {α : Type*} (s : set α) [fintype s] : s.to_finset.card = fintype.card s := multiset.card_map subtype.val finset.univ.val @[simp] theorem coe_to_finset (s : set α) [fintype s] : (↑s.to_finset : set α) = s := set.ext $ λ _, mem_to_finset @[simp] theorem to_finset_inj {s t : set α} [fintype s] [fintype t] : s.to_finset = t.to_finset ↔ s = t := ⟨λ h, by rw [← s.coe_to_finset, h, t.coe_to_finset], λ h, by simp [h]; congr⟩ end set lemma finset.card_univ [fintype α] : (finset.univ : finset α).card = fintype.card α := rfl lemma finset.card_univ_diff [fintype α] [decidable_eq α] (s : finset α) : (finset.univ \ s).card = fintype.card α - s.card := finset.card_sdiff (subset_univ s) instance (n : ℕ) : fintype (fin n) := ⟨⟨list.fin_range n, list.nodup_fin_range n⟩, list.mem_fin_range⟩ @[simp] theorem fintype.card_fin (n : ℕ) : fintype.card (fin n) = n := list.length_fin_range n @[simp] lemma finset.card_fin (n : ℕ) : finset.card (finset.univ : finset (fin n)) = n := by rw [finset.card_univ, fintype.card_fin] lemma fin.univ_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert 0 (univ.image fin.succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop], exact fin.cases (or.inl rfl) (λ i, or.inr ⟨i, trivial, rfl⟩) m end lemma fin.univ_cast_succ (n : ℕ) : (univ : finset (fin $ n+1)) = insert (fin.last n) (univ.image fin.cast_succ) := begin ext m, simp only [mem_univ, mem_insert, true_iff, mem_image, exists_prop, true_and], by_cases h : m.val < n, { right, use fin.cast_lt m h, rw fin.cast_succ_cast_lt }, { left, exact fin.eq_last_of_not_lt h } end /-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with the increasing bijection `mono_of_fin s h`. -/ lemma finset.mono_of_fin_unique' [decidable_linear_order α] {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (fmap : set.maps_to f set.univ ↑s) (hmono : strict_mono f) : f = s.mono_of_fin h := begin have finj : set.inj_on f set.univ := hmono.injective.inj_on _, apply mono_of_fin_unique h (set.bij_on.mk fmap finj (λ y hy, _)) hmono, simp only [set.image_univ, set.mem_range], rcases surj_on_of_inj_on_of_card_le (λ i (hi : i ∈ finset.univ), f i) (λ i hi, fmap (set.mem_univ i)) (λ i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij) (by simp [h]) y hy with ⟨x, _, hx⟩, exact ⟨x, hx.symm⟩ end @[instance, priority 10] def unique.fintype {α : Type*} [unique α] : fintype α := fintype.of_subsingleton (default α) @[simp] lemma univ_unique {α : Type*} [unique α] [f : fintype α] : @finset.univ α _ = {default α} := by rw [subsingleton.elim f (@unique.fintype α _)]; refl instance : fintype empty := ⟨∅, empty.rec _⟩ @[simp] theorem fintype.univ_empty : @univ empty _ = ∅ := rfl @[simp] theorem fintype.card_empty : fintype.card empty = 0 := rfl instance : fintype pempty := ⟨∅, pempty.rec _⟩ @[simp] theorem fintype.univ_pempty : @univ pempty _ = ∅ := rfl @[simp] theorem fintype.card_pempty : fintype.card pempty = 0 := rfl instance : fintype unit := fintype.of_subsingleton () theorem fintype.univ_unit : @univ unit _ = {()} := rfl theorem fintype.card_unit : fintype.card unit = 1 := rfl instance : fintype punit := fintype.of_subsingleton punit.star @[simp] theorem fintype.univ_punit : @univ punit _ = {punit.star} := rfl @[simp] theorem fintype.card_punit : fintype.card punit = 1 := rfl instance : fintype bool := ⟨⟨tt::ff::0, by simp⟩, λ x, by cases x; simp⟩ @[simp] theorem fintype.univ_bool : @univ bool _ = {tt, ff} := rfl instance units_int.fintype : fintype (units ℤ) := ⟨{1, -1}, λ x, by cases int.units_eq_one_or x; simp *⟩ instance additive.fintype : Π [fintype α], fintype (additive α) := id instance multiplicative.fintype : Π [fintype α], fintype (multiplicative α) := id @[simp] theorem fintype.card_units_int : fintype.card (units ℤ) = 2 := rfl noncomputable instance [monoid α] [fintype α] : fintype (units α) := by classical; exact fintype.of_injective units.val units.ext @[simp] theorem fintype.card_bool : fintype.card bool = 2 := rfl def finset.insert_none (s : finset α) : finset (option α) := ⟨none :: s.1.map some, multiset.nodup_cons.2 ⟨by simp, multiset.nodup_map (λ a b, option.some.inj) s.2⟩⟩ @[simp] theorem finset.mem_insert_none {s : finset α} : ∀ {o : option α}, o ∈ s.insert_none ↔ ∀ a ∈ o, a ∈ s | none := iff_of_true (multiset.mem_cons_self _ _) (λ a h, by cases h) | (some a) := multiset.mem_cons.trans $ by simp; refl theorem finset.some_mem_insert_none {s : finset α} {a : α} : some a ∈ s.insert_none ↔ a ∈ s := by simp instance {α : Type*} [fintype α] : fintype (option α) := ⟨univ.insert_none, λ a, by simp⟩ @[simp] theorem fintype.card_option {α : Type*} [fintype α] : fintype.card (option α) = fintype.card α + 1 := (multiset.card_cons _ _).trans (by rw multiset.card_map; refl) instance {α : Type*} (β : α → Type*) [fintype α] [∀ a, fintype (β a)] : fintype (sigma β) := ⟨univ.sigma (λ _, univ), λ ⟨a, b⟩, by simp⟩ @[simp] lemma finset.univ_sigma_univ {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : (univ : finset α).sigma (λ a, (univ : finset (β a))) = univ := rfl instance (α β : Type*) [fintype α] [fintype β] : fintype (α × β) := ⟨univ.product univ, λ ⟨a, b⟩, by simp⟩ @[simp] theorem fintype.card_prod (α β : Type*) [fintype α] [fintype β] : fintype.card (α × β) = fintype.card α * fintype.card β := card_product _ _ def fintype.fintype_prod_left {α β} [decidable_eq α] [fintype (α × β)] [nonempty β] : fintype α := ⟨(fintype.elems (α × β)).image prod.fst, assume a, let ⟨b⟩ := ‹nonempty β› in by simp; exact ⟨b, fintype.complete _⟩⟩ def fintype.fintype_prod_right {α β} [decidable_eq β] [fintype (α × β)] [nonempty α] : fintype β := ⟨(fintype.elems (α × β)).image prod.snd, assume b, let ⟨a⟩ := ‹nonempty α› in by simp; exact ⟨a, fintype.complete _⟩⟩ instance (α : Type*) [fintype α] : fintype (ulift α) := fintype.of_equiv _ equiv.ulift.symm @[simp] theorem fintype.card_ulift (α : Type*) [fintype α] : fintype.card (ulift α) = fintype.card α := fintype.of_equiv_card _ instance (α : Type u) (β : Type v) [fintype α] [fintype β] : fintype (α ⊕ β) := @fintype.of_equiv _ _ (@sigma.fintype _ (λ b, cond b (ulift α) (ulift.{(max u v) v} β)) _ (λ b, by cases b; apply ulift.fintype)) ((equiv.sum_equiv_sigma_bool _ _).symm.trans (equiv.sum_congr equiv.ulift equiv.ulift)) lemma fintype.card_le_of_injective [fintype α] [fintype β] (f : α → β) (hf : function.injective f) : fintype.card α ≤ fintype.card β := by haveI := classical.prop_decidable; exact finset.card_le_card_of_inj_on f (λ _ _, finset.mem_univ _) (λ _ _ _ _ h, hf h) lemma fintype.card_eq_one_iff [fintype α] : fintype.card α = 1 ↔ (∃ x : α, ∀ y, y = x) := by rw [← fintype.card_unit, fintype.card_eq]; exact ⟨λ ⟨a⟩, ⟨a.symm (), λ y, a.injective (subsingleton.elim _ _)⟩, λ ⟨x, hx⟩, ⟨⟨λ _, (), λ _, x, λ _, (hx _).trans (hx _).symm, λ _, subsingleton.elim _ _⟩⟩⟩ lemma fintype.card_eq_zero_iff [fintype α] : fintype.card α = 0 ↔ (α → false) := ⟨λ h a, have e : α ≃ empty := classical.choice (fintype.card_eq.1 (by simp [h])), (e a).elim, λ h, have e : α ≃ empty := ⟨λ a, (h a).elim, λ a, a.elim, λ a, (h a).elim, λ a, a.elim⟩, by simp [fintype.card_congr e]⟩ lemma fintype.card_pos_iff [fintype α] : 0 < fintype.card α ↔ nonempty α := ⟨λ h, classical.by_contradiction (λ h₁, have fintype.card α = 0 := fintype.card_eq_zero_iff.2 (λ a, h₁ ⟨a⟩), lt_irrefl 0 $ by rwa this at h), λ ⟨a⟩, nat.pos_of_ne_zero (mt fintype.card_eq_zero_iff.1 (λ h, h a))⟩ lemma fintype.card_le_one_iff [fintype α] : fintype.card α ≤ 1 ↔ (∀ a b : α, a = b) := let n := fintype.card α in have hn : n = fintype.card α := rfl, match n, hn with | 0 := λ ha, ⟨λ h, λ a, (fintype.card_eq_zero_iff.1 ha.symm a).elim, λ _, ha ▸ nat.le_succ _⟩ | 1 := λ ha, ⟨λ h, λ a b, let ⟨x, hx⟩ := fintype.card_eq_one_iff.1 ha.symm in by rw [hx a, hx b], λ _, ha ▸ le_refl _⟩ | (n+2) := λ ha, ⟨λ h, by rw ← ha at h; exact absurd h dec_trivial, (λ h, fintype.card_unit ▸ fintype.card_le_of_injective (λ _, ()) (λ _ _ _, h _ _))⟩ end lemma fintype.exists_ne_of_one_lt_card [fintype α] (h : 1 < fintype.card α) (a : α) : ∃ b : α, b ≠ a := let ⟨b, hb⟩ := classical.not_forall.1 (mt fintype.card_le_one_iff.2 (not_le_of_gt h)) in let ⟨c, hc⟩ := classical.not_forall.1 hb in by haveI := classical.dec_eq α; exact if hba : b = a then ⟨c, by cc⟩ else ⟨b, hba⟩ lemma fintype.exists_pair_of_one_lt_card [fintype α] (h : 1 < fintype.card α) : ∃ (a b : α), b ≠ a := begin rcases fintype.card_pos_iff.1 (nat.lt_of_succ_lt h) with a, exact ⟨a, fintype.exists_ne_of_one_lt_card h a⟩, end lemma fintype.injective_iff_surjective [fintype α] {f : α → α} : injective f ↔ surjective f := by haveI := classical.prop_decidable; exact have ∀ {f : α → α}, injective f → surjective f, from λ f hinj x, have h₁ : image f univ = univ := eq_of_subset_of_card_le (subset_univ _) ((card_image_of_injective univ hinj).symm ▸ le_refl _), have h₂ : x ∈ image f univ := h₁.symm ▸ mem_univ _, exists_of_bex (mem_image.1 h₂), ⟨this, λ hsurj, has_left_inverse.injective ⟨surj_inv hsurj, left_inverse_of_surjective_of_right_inverse (this (injective_surj_inv _)) (right_inverse_surj_inv _)⟩⟩ lemma fintype.injective_iff_bijective [fintype α] {f : α → α} : injective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.surjective_iff_bijective [fintype α] {f : α → α} : surjective f ↔ bijective f := by simp [bijective, fintype.injective_iff_surjective] lemma fintype.injective_iff_surjective_of_equiv [fintype α] {f : α → β} (e : α ≃ β) : injective f ↔ surjective f := have injective (e.symm ∘ f) ↔ surjective (e.symm ∘ f), from fintype.injective_iff_surjective, ⟨λ hinj, by simpa [function.comp] using e.surjective.comp (this.1 (e.symm.injective.comp hinj)), λ hsurj, by simpa [function.comp] using e.injective.comp (this.2 (e.symm.surjective.comp hsurj))⟩ lemma fintype.coe_image_univ [fintype α] [decidable_eq β] {f : α → β} : ↑(finset.image f finset.univ) = set.range f := by { ext x, simp } instance list.subtype.fintype [decidable_eq α] (l : list α) : fintype {x // x ∈ l} := fintype.of_list l.attach l.mem_attach instance multiset.subtype.fintype [decidable_eq α] (s : multiset α) : fintype {x // x ∈ s} := fintype.of_multiset s.attach s.mem_attach instance finset.subtype.fintype (s : finset α) : fintype {x // x ∈ s} := ⟨s.attach, s.mem_attach⟩ instance finset_coe.fintype (s : finset α) : fintype (↑s : set α) := finset.subtype.fintype s @[simp] lemma fintype.card_coe (s : finset α) : fintype.card (↑s : set α) = s.card := card_attach lemma finset.attach_eq_univ {s : finset α} : s.attach = finset.univ := rfl lemma finset.card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {x y}, x ∈ s → y ∈ s → x = y := begin let t : set α := ↑s, letI : fintype t := finset_coe.fintype s, have : fintype.card t = s.card := fintype.card_coe s, rw [← this, fintype.card_le_one_iff], split, { assume H x y hx hy, exact subtype.mk.inj (H ⟨x, hx⟩ ⟨y, hy⟩) }, { assume H x y, exact subtype.eq (H x.2 y.2) } end lemma finset.one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := begin classical, rw ← not_iff_not, push_neg, simpa [classical.or_iff_not_imp_left] using finset.card_le_one_iff end instance plift.fintype (p : Prop) [decidable p] : fintype (plift p) := ⟨if h : p then {⟨h⟩} else ∅, λ ⟨h⟩, by simp [h]⟩ instance Prop.fintype : fintype Prop := ⟨⟨true::false::0, by simp [true_ne_false]⟩, classical.cases (by simp) (by simp)⟩ def set_fintype {α} [fintype α] (s : set α) [decidable_pred s] : fintype s := fintype.subtype (univ.filter (∈ s)) (by simp) namespace function.embedding /-- An embedding from a `fintype` to itself can be promoted to an equivalence. -/ noncomputable def equiv_of_fintype_self_embedding {α : Type*} [fintype α] (e : α ↪ α) : α ≃ α := equiv.of_bijective e (fintype.injective_iff_bijective.1 e.2) @[simp] lemma equiv_of_fintype_self_embedding_to_embedding {α : Type*} [fintype α] (e : α ↪ α) : e.equiv_of_fintype_self_embedding.to_embedding = e := by { ext, refl, } end function.embedding @[simp] lemma finset.univ_map_embedding {α : Type*} [fintype α] (e : α ↪ α) : univ.map e = univ := by rw [← e.equiv_of_fintype_self_embedding_to_embedding, univ_map_equiv_to_embedding] namespace fintype variables [fintype α] [decidable_eq α] {δ : α → Type*} /-- Given for all `a : α` a finset `t a` of `δ a`, then one can define the finset `fintype.pi_finset t` of all functions taking values in `t a` for all `a`. This is the analogue of `finset.pi` where the base finset is `univ` (but formally they are not the same, as there is an additional condition `i ∈ finset.univ` in the `finset.pi` definition). -/ def pi_finset (t : Πa, finset (δ a)) : finset (Πa, δ a) := (finset.univ.pi t).map ⟨λ f a, f a (mem_univ a), λ _ _, by simp [function.funext_iff]⟩ @[simp] lemma mem_pi_finset {t : Πa, finset (δ a)} {f : Πa, δ a} : f ∈ pi_finset t ↔ (∀a, f a ∈ t a) := begin split, { simp only [pi_finset, mem_map, and_imp, forall_prop_of_true, exists_prop, mem_univ, exists_imp_distrib, mem_pi], assume g hg hgf a, rw ← hgf, exact hg a }, { simp only [pi_finset, mem_map, forall_prop_of_true, exists_prop, mem_univ, mem_pi], assume hf, exact ⟨λ a ha, f a, hf, rfl⟩ } end lemma pi_finset_subset (t₁ t₂ : Πa, finset (δ a)) (h : ∀ a, t₁ a ⊆ t₂ a) : pi_finset t₁ ⊆ pi_finset t₂ := λ g hg, mem_pi_finset.2 $ λ a, h a $ mem_pi_finset.1 hg a lemma pi_finset_disjoint_of_disjoint [∀ a, decidable_eq (δ a)] (t₁ t₂ : Πa, finset (δ a)) {a : α} (h : disjoint (t₁ a) (t₂ a)) : disjoint (pi_finset t₁) (pi_finset t₂) := disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂, disjoint_iff_ne.1 h (f₁ a) (mem_pi_finset.1 hf₁ a) (f₂ a) (mem_pi_finset.1 hf₂ a) (congr_fun eq₁₂ a) end fintype /-! ### pi -/ /-- A dependent product of fintypes, indexed by a fintype, is a fintype. -/ instance pi.fintype {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype (Πa, β a) := ⟨fintype.pi_finset (λ _, univ), by simp⟩ @[simp] lemma fintype.pi_finset_univ {α : Type*} {β : α → Type*} [decidable_eq α] [fintype α] [∀a, fintype (β a)] : fintype.pi_finset (λ a : α, (finset.univ : finset (β a))) = (finset.univ : finset (Π a, β a)) := rfl instance d_array.fintype {n : ℕ} {α : fin n → Type*} [∀n, fintype (α n)] : fintype (d_array n α) := fintype.of_equiv _ (equiv.d_array_equiv_fin _).symm instance array.fintype {n : ℕ} {α : Type*} [fintype α] : fintype (array n α) := d_array.fintype instance vector.fintype {α : Type*} [fintype α] {n : ℕ} : fintype (vector α n) := fintype.of_equiv _ (equiv.vector_equiv_fin _ _).symm instance quotient.fintype [fintype α] (s : setoid α) [decidable_rel ((≈) : α → α → Prop)] : fintype (quotient s) := fintype.of_surjective quotient.mk (λ x, quotient.induction_on x (λ x, ⟨x, rfl⟩)) instance finset.fintype [fintype α] : fintype (finset α) := ⟨univ.powerset, λ x, finset.mem_powerset.2 (finset.subset_univ _)⟩ @[simp] lemma fintype.card_finset [fintype α] : fintype.card (finset α) = 2 ^ (fintype.card α) := finset.card_powerset finset.univ instance subtype.fintype (p : α → Prop) [decidable_pred p] [fintype α] : fintype {x // p x} := set_fintype _ @[simp] lemma set.to_finset_univ [fintype α] : (set.univ : set α).to_finset = finset.univ := by { ext, simp only [set.mem_univ, mem_univ, set.mem_to_finset] } theorem fintype.card_subtype_le [fintype α] (p : α → Prop) [decidable_pred p] : fintype.card {x // p x} ≤ fintype.card α := by rw fintype.subtype_card; exact card_le_of_subset (subset_univ _) theorem fintype.card_subtype_lt [fintype α] {p : α → Prop} [decidable_pred p] {x : α} (hx : ¬ p x) : fintype.card {x // p x} < fintype.card α := by rw [fintype.subtype_card]; exact finset.card_lt_card ⟨subset_univ _, classical.not_forall.2 ⟨x, by simp [*, set.mem_def]⟩⟩ instance psigma.fintype {α : Type*} {β : α → Type*} [fintype α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := fintype.of_equiv _ (equiv.psigma_equiv_sigma _).symm instance psigma.fintype_prop_left {α : Prop} {β : α → Type*} [decidable α] [∀ a, fintype (β a)] : fintype (Σ' a, β a) := if h : α then fintype.of_equiv (β h) ⟨λ x, ⟨h, x⟩, psigma.snd, λ _, rfl, λ ⟨_, _⟩, rfl⟩ else ⟨∅, λ x, h x.1⟩ instance psigma.fintype_prop_right {α : Type*} {β : α → Prop} [∀ a, decidable (β a)] [fintype α] : fintype (Σ' a, β a) := fintype.of_equiv {a // β a} ⟨λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, ⟨x, y⟩, λ ⟨x, y⟩, rfl, λ ⟨x, y⟩, rfl⟩ instance psigma.fintype_prop_prop {α : Prop} {β : α → Prop} [decidable α] [∀ a, decidable (β a)] : fintype (Σ' a, β a) := if h : ∃ a, β a then ⟨{⟨h.fst, h.snd⟩}, λ ⟨_, _⟩, by simp⟩ else ⟨∅, λ ⟨x, y⟩, h ⟨x, y⟩⟩ instance set.fintype [fintype α] : fintype (set α) := ⟨(@finset.univ α _).powerset.map ⟨coe, coe_injective⟩, λ s, begin classical, refine mem_map.2 ⟨finset.univ.filter s, mem_powerset.2 (subset_univ _), _⟩, apply (coe_filter _).trans, rw [coe_univ, set.sep_univ], refl end⟩ instance pfun_fintype (p : Prop) [decidable p] (α : p → Type*) [Π hp, fintype (α hp)] : fintype (Π hp : p, α hp) := if hp : p then fintype.of_equiv (α hp) ⟨λ a _, a, λ f, f hp, λ _, rfl, λ _, rfl⟩ else ⟨singleton (λ h, (hp h).elim), by simp [hp, function.funext_iff]⟩ lemma mem_image_univ_iff_mem_range {α β : Type*} [fintype α] [decidable_eq β] {f : α → β} {b : β} : b ∈ univ.image f ↔ b ∈ set.range f := by simp lemma card_lt_card_of_injective_of_not_mem {α β : Type*} [fintype α] [fintype β] (f : α → β) (h : function.injective f) {b : β} (w : b ∉ set.range f) : fintype.card α < fintype.card β := begin classical, calc fintype.card α = (univ : finset α).card : rfl ... = (image f univ).card : (card_image_of_injective univ h).symm ... < (insert b (image f univ)).card : card_lt_card (ssubset_insert (mt mem_image_univ_iff_mem_range.mp w)) ... ≤ (univ : finset β).card : card_le_of_subset (subset_univ _) ... = fintype.card β : rfl end def quotient.fin_choice_aux {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι), (∀ i ∈ l, quotient (S i)) → @quotient (Π i ∈ l, α i) (by apply_instance) | [] f := ⟦λ i, false.elim⟧ | (i::l) f := begin refine quotient.lift_on₂ (f i (list.mem_cons_self _ _)) (quotient.fin_choice_aux l (λ j h, f j (list.mem_cons_of_mem _ h))) _ _, exact λ a l, ⟦λ j h, if e : j = i then by rw e; exact a else l _ (h.resolve_left e)⟧, refine λ a₁ l₁ a₂ l₂ h₁ h₂, quotient.sound (λ j h, _), by_cases e : j = i; simp [e], { subst j, exact h₁ }, { exact h₂ _ _ } end theorem quotient.fin_choice_aux_eq {ι : Type*} [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] : ∀ (l : list ι) (f : ∀ i ∈ l, α i), quotient.fin_choice_aux l (λ i h, ⟦f i h⟧) = ⟦f⟧ | [] f := quotient.sound (λ i h, h.elim) | (i::l) f := begin simp [quotient.fin_choice_aux, quotient.fin_choice_aux_eq l], refine quotient.sound (λ j h, _), by_cases e : j = i; simp [e], subst j, refl end def quotient.fin_choice {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := quotient.lift_on (@quotient.rec_on _ _ (λ l : multiset ι, @quotient (Π i ∈ l, α i) (by apply_instance)) finset.univ.1 (λ l, quotient.fin_choice_aux l (λ i _, f i)) (λ a b h, begin have := λ a, quotient.fin_choice_aux_eq a (λ i h, quotient.out (f i)), simp [quotient.out_eq] at this, simp [this], let g := λ a:multiset ι, ⟦λ (i : ι) (h : i ∈ a), quotient.out (f i)⟧, refine eq_of_heq ((eq_rec_heq _ _).trans (_ : g a == g b)), congr' 1, exact quotient.sound h, end)) (λ f, ⟦λ i, f i (finset.mem_univ _)⟧) (λ a b h, quotient.sound $ λ i, h _ _) theorem quotient.fin_choice_eq {ι : Type*} [fintype ι] [decidable_eq ι] {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.fin_choice (λ i, ⟦f i⟧) = ⟦f⟧ := begin let q, swap, change quotient.lift_on q _ _ = _, have : q = ⟦λ i h, f i⟧, { dsimp [q], exact quotient.induction_on (@finset.univ ι _).1 (λ l, quotient.fin_choice_aux_eq _ _) }, simp [this], exact setoid.refl _ end section equiv open list equiv equiv.perm variables [decidable_eq α] [decidable_eq β] def perms_of_list : list α → list (perm α) | [] := [1] | (a :: l) := perms_of_list l ++ l.bind (λ b, (perms_of_list l).map (λ f, swap a b * f)) lemma length_perms_of_list : ∀ l : list α, length (perms_of_list l) = l.length.fact | [] := rfl | (a :: l) := begin rw [length_cons, nat.fact_succ], simp [perms_of_list, length_bind, length_perms_of_list, function.comp, nat.succ_mul], cc end lemma mem_perms_of_list_of_mem : ∀ {l : list α} {f : perm α} (h : ∀ x, f x ≠ x → x ∈ l), f ∈ perms_of_list l | [] f h := list.mem_singleton.2 $ equiv.ext $ λ x, by simp [imp_false, *] at * | (a::l) f h := if hfa : f a = a then mem_append_left _ $ mem_perms_of_list_of_mem (λ x hx, mem_of_ne_of_mem (λ h, by rw h at hx; exact hx hfa) (h x hx)) else have hfa' : f (f a) ≠ f a, from mt (λ h, f.injective h) hfa, have ∀ (x : α), (swap a (f a) * f) x ≠ x → x ∈ l, from λ x hx, have hxa : x ≠ a, from λ h, by simpa [h, mul_apply] using hx, have hfxa : f x ≠ f a, from mt (λ h, f.injective h) hxa, list.mem_of_ne_of_mem hxa (h x (λ h, by simp [h, mul_apply, swap_apply_def] at hx; split_ifs at hx; cc)), suffices f ∈ perms_of_list l ∨ ∃ (b : α), b ∈ l ∧ ∃ g : perm α, g ∈ perms_of_list l ∧ swap a b * g = f, by simpa [perms_of_list], (@or_iff_not_imp_left _ _ (classical.prop_decidable _)).2 (λ hfl, ⟨f a, if hffa : f (f a) = a then mem_of_ne_of_mem hfa (h _ (mt (λ h, f.injective h) hfa)) else this _ $ by simp [mul_apply, swap_apply_def]; split_ifs; cc, ⟨swap a (f a) * f, mem_perms_of_list_of_mem this, by rw [← mul_assoc, mul_def (swap a (f a)) (swap a (f a)), swap_swap, ← equiv.perm.one_def, one_mul]⟩⟩) lemma mem_of_mem_perms_of_list : ∀ {l : list α} {f : perm α}, f ∈ perms_of_list l → ∀ {x}, f x ≠ x → x ∈ l | [] f h := have f = 1 := by simpa [perms_of_list] using h, by rw this; simp | (a::l) f h := (mem_append.1 h).elim (λ h x hx, mem_cons_of_mem _ (mem_of_mem_perms_of_list h hx)) (λ h x hx, let ⟨y, hy, hy'⟩ := list.mem_bind.1 h in let ⟨g, hg₁, hg₂⟩ := list.mem_map.1 hy' in if hxa : x = a then by simp [hxa] else if hxy : x = y then mem_cons_of_mem _ $ by rwa hxy else mem_cons_of_mem _ $ mem_of_mem_perms_of_list hg₁ $ by rw [eq_inv_mul_iff_mul_eq.2 hg₂, mul_apply, swap_inv, swap_apply_def]; split_ifs; cc) lemma mem_perms_of_list_iff {l : list α} {f : perm α} : f ∈ perms_of_list l ↔ ∀ {x}, f x ≠ x → x ∈ l := ⟨mem_of_mem_perms_of_list, mem_perms_of_list_of_mem⟩ lemma nodup_perms_of_list : ∀ {l : list α} (hl : l.nodup), (perms_of_list l).nodup | [] hl := by simp [perms_of_list] | (a::l) hl := have hl' : l.nodup, from nodup_of_nodup_cons hl, have hln' : (perms_of_list l).nodup, from nodup_perms_of_list hl', have hmeml : ∀ {f : perm α}, f ∈ perms_of_list l → f a = a, from λ f hf, not_not.1 (mt (mem_of_mem_perms_of_list hf) (nodup_cons.1 hl).1), by rw [perms_of_list, list.nodup_append, list.nodup_bind, pairwise_iff_nth_le]; exact ⟨hln', ⟨λ _ _, nodup_map (λ _ _, (mul_right_inj _).1) hln', λ i j hj hij x hx₁ hx₂, let ⟨f, hf⟩ := list.mem_map.1 hx₁ in let ⟨g, hg⟩ := list.mem_map.1 hx₂ in have hix : x a = nth_le l i (lt_trans hij hj), by rw [← hf.2, mul_apply, hmeml hf.1, swap_apply_left], have hiy : x a = nth_le l j hj, by rw [← hg.2, mul_apply, hmeml hg.1, swap_apply_left], absurd (hf.2.trans (hg.2.symm)) $ λ h, ne_of_lt hij $ nodup_iff_nth_le_inj.1 hl' i j (lt_trans hij hj) hj $ by rw [← hix, hiy]⟩, λ f hf₁ hf₂, let ⟨x, hx, hx'⟩ := list.mem_bind.1 hf₂ in let ⟨g, hg⟩ := list.mem_map.1 hx' in have hgxa : g⁻¹ x = a, from f.injective $ by rw [hmeml hf₁, ← hg.2]; simp, have hxa : x ≠ a, from λ h, (list.nodup_cons.1 hl).1 (h ▸ hx), (list.nodup_cons.1 hl).1 $ hgxa ▸ mem_of_mem_perms_of_list hg.1 (by rwa [apply_inv_self, hgxa])⟩ def perms_of_finset (s : finset α) : finset (perm α) := quotient.hrec_on s.1 (λ l hl, ⟨perms_of_list l, nodup_perms_of_list hl⟩) (λ a b hab, hfunext (congr_arg _ (quotient.sound hab)) (λ ha hb _, heq_of_eq $ finset.ext $ by simp [mem_perms_of_list_iff, hab.mem_iff])) s.2 lemma mem_perms_of_finset_iff : ∀ {s : finset α} {f : perm α}, f ∈ perms_of_finset s ↔ ∀ {x}, f x ≠ x → x ∈ s := by rintros ⟨⟨l⟩, hs⟩ f; exact mem_perms_of_list_iff lemma card_perms_of_finset : ∀ (s : finset α), (perms_of_finset s).card = s.card.fact := by rintros ⟨⟨l⟩, hs⟩; exact length_perms_of_list l def fintype_perm [fintype α] : fintype (perm α) := ⟨perms_of_finset (@finset.univ α _), by simp [mem_perms_of_finset_iff]⟩ instance [fintype α] [fintype β] : fintype (α ≃ β) := if h : fintype.card β = fintype.card α then trunc.rec_on_subsingleton (fintype.equiv_fin α) (λ eα, trunc.rec_on_subsingleton (fintype.equiv_fin β) (λ eβ, @fintype.of_equiv _ (perm α) fintype_perm (equiv_congr (equiv.refl α) (eα.trans (eq.rec_on h eβ.symm)) : (α ≃ α) ≃ (α ≃ β)))) else ⟨∅, λ x, false.elim (h (fintype.card_eq.2 ⟨x.symm⟩))⟩ lemma fintype.card_perm [fintype α] : fintype.card (perm α) = (fintype.card α).fact := subsingleton.elim (@fintype_perm α _ _) (@equiv.fintype α α _ _ _ _) ▸ card_perms_of_finset _ lemma fintype.card_equiv [fintype α] [fintype β] (e : α ≃ β) : fintype.card (α ≃ β) = (fintype.card α).fact := fintype.card_congr (equiv_congr (equiv.refl α) e) ▸ fintype.card_perm lemma univ_eq_singleton_of_card_one {α} [fintype α] (x : α) (h : fintype.card α = 1) : (univ : finset α) = {x} := begin apply symm, apply eq_of_subset_of_card_le (subset_univ ({x})), apply le_of_eq, simp [h, finset.card_univ] end end equiv namespace fintype section choose open fintype open equiv variables [fintype α] [decidable_eq α] (p : α → Prop) [decidable_pred p] def choose_x (hp : ∃! a : α, p a) : {a // p a} := ⟨finset.choose p univ (by simp; exact hp), finset.choose_property _ _ _⟩ def choose (hp : ∃! a, p a) : α := choose_x p hp lemma choose_spec (hp : ∃! a, p a) : p (choose p hp) := (choose_x p hp).property end choose section bijection_inverse open function variables [fintype α] [decidable_eq α] variables [fintype β] [decidable_eq β] variables {f : α → β} /-- ` `bij_inv f` is the unique inverse to a bijection `f`. This acts as a computable alternative to `function.inv_fun`. -/ def bij_inv (f_bij : bijective f) (b : β) : α := fintype.choose (λ a, f a = b) begin rcases f_bij.right b with ⟨a', fa_eq_b⟩, rw ← fa_eq_b, exact ⟨a', ⟨rfl, (λ a h, f_bij.left h)⟩⟩ end lemma left_inverse_bij_inv (f_bij : bijective f) : left_inverse (bij_inv f_bij) f := λ a, f_bij.left (choose_spec (λ a', f a' = f a) _) lemma right_inverse_bij_inv (f_bij : bijective f) : right_inverse (bij_inv f_bij) f := λ b, choose_spec (λ a', f a' = b) _ lemma bijective_bij_inv (f_bij : bijective f) : bijective (bij_inv f_bij) := ⟨(right_inverse_bij_inv _).injective, (left_inverse_bij_inv _).surjective⟩ end bijection_inverse lemma well_founded_of_trans_of_irrefl [fintype α] (r : α → α → Prop) [is_trans α r] [is_irrefl α r] : well_founded r := by classical; exact have ∀ x y, r x y → (univ.filter (λ z, r z x)).card < (univ.filter (λ z, r z y)).card, from λ x y hxy, finset.card_lt_card $ by simp only [finset.lt_iff_ssubset.symm, lt_iff_le_not_le, finset.le_iff_subset, finset.subset_iff, mem_filter, true_and, mem_univ, hxy]; exact ⟨λ z hzx, trans hzx hxy, not_forall_of_exists_not ⟨x, not_imp.2 ⟨hxy, irrefl x⟩⟩⟩, subrelation.wf this (measure_wf _) lemma preorder.well_founded [fintype α] [preorder α] : well_founded ((<) : α → α → Prop) := well_founded_of_trans_of_irrefl _ @[instance, priority 10] lemma linear_order.is_well_order [fintype α] [linear_order α] : is_well_order α (<) := { wf := preorder.well_founded } end fintype class infinite (α : Type*) : Prop := (not_fintype : fintype α → false) @[simp] lemma not_nonempty_fintype {α : Type*} : ¬nonempty (fintype α) ↔ infinite α := ⟨λf, ⟨λ x, f ⟨x⟩⟩, λ⟨f⟩ ⟨x⟩, f x⟩ namespace infinite lemma exists_not_mem_finset [infinite α] (s : finset α) : ∃ x, x ∉ s := classical.not_forall.1 $ λ h, not_fintype ⟨s, h⟩ @[priority 100] -- see Note [lower instance priority] instance nonempty (α : Type*) [infinite α] : nonempty α := nonempty_of_exists (exists_not_mem_finset (∅ : finset α)) lemma of_injective [infinite β] (f : β → α) (hf : injective f) : infinite α := ⟨λ I, by exactI not_fintype (fintype.of_injective f hf)⟩ lemma of_surjective [infinite β] (f : α → β) (hf : surjective f) : infinite α := ⟨λ I, by classical; exactI not_fintype (fintype.of_surjective f hf)⟩ private noncomputable def nat_embedding_aux (α : Type*) [infinite α] : ℕ → α | n := by letI := classical.dec_eq α; exact classical.some (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux m) (λ _, multiset.mem_range.1)).to_finset) private lemma nat_embedding_aux_injective (α : Type*) [infinite α] : function.injective (nat_embedding_aux α) := begin assume m n h, letI := classical.dec_eq α, wlog hmlen : m ≤ n using m n, by_contradiction hmn, have hmn : m < n, from lt_of_le_of_ne hmlen hmn, refine (classical.some_spec (exists_not_mem_finset ((multiset.range n).pmap (λ m (hm : m < n), nat_embedding_aux α m) (λ _, multiset.mem_range.1)).to_finset)) _, refine multiset.mem_to_finset.2 (multiset.mem_pmap.2 ⟨m, multiset.mem_range.2 hmn, _⟩), rw [h, nat_embedding_aux] end noncomputable def nat_embedding (α : Type*) [infinite α] : ℕ ↪ α := ⟨_, nat_embedding_aux_injective α⟩ end infinite lemma not_injective_infinite_fintype [infinite α] [fintype β] (f : α → β) : ¬ injective f := assume (hf : injective f), have H : fintype α := fintype.of_injective f hf, infinite.not_fintype H lemma not_surjective_fintype_infinite [fintype α] [infinite β] (f : α → β) : ¬ surjective f := assume (hf : surjective f), have H : infinite α := infinite.of_surjective f hf, @infinite.not_fintype _ H infer_instance instance nat.infinite : infinite ℕ := ⟨λ ⟨s, hs⟩, finset.not_mem_range_self $ s.subset_range_sup_succ (hs _)⟩ instance int.infinite : infinite ℤ := infinite.of_injective int.of_nat (λ _ _, int.of_nat_inj)
2ab90bf5e9efae31df7237b0e6732dfd1332f7b0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/archive/sensitivity.lean
1bd54993a14c446b1a35e4ea73754fd387ead4d4
[ "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
15,856
lean
/- Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot -/ import tactic.fin_cases import tactic.apply_fun import linear_algebra.finite_dimensional import linear_algebra.dual import analysis.normed_space.basic import data.real.sqrt /-! # Huang's sensitivity theorem > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A formalization of Hao Huang's sensitivity theorem: in the hypercube of dimension n ≥ 1, if one colors more than half the vertices then at least one vertex has at least √n colored neighbors. A fun summer collaboration by Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot, based on Don Knuth's account of the story (https://www.cs.stanford.edu/~knuth/papers/huang.pdf), using the Lean theorem prover (https://leanprover.github.io/), by Leonardo de Moura at Microsoft Research, and his collaborators (https://leanprover.github.io/people/), and using Lean's user maintained mathematics library (https://github.com/leanprover-community/mathlib). The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean -/ namespace sensitivity /-! The next two lines assert we do not want to give a constructive proof, but rather use classical logic. -/ noncomputable theory open_locale classical /-! We also want to use the notation `∑` for sums. -/ open_locale big_operators notation `√` := real.sqrt open function bool linear_map fintype finite_dimensional module.dual_bases /-! ### The hypercube Notations: - `ℕ` denotes natural numbers (including zero). - `fin n` = {0, ⋯ , n - 1}. - `bool` = {`tt`, `ff`}. -/ /-- The hypercube in dimension `n`. -/ @[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool /-- The projection from `Q (n + 1)` to `Q n` forgetting the first value (ie. the image of zero). -/ def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ namespace Q /-! `n` will always denote a natural number. -/ variable (n : ℕ) /-- `Q 0` has a unique element. -/ instance : unique (Q 0) := ⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩ /-- `Q n` has 2^n elements. -/ lemma card : card (Q n) = 2^n := by simp [Q] /-! Until the end of this namespace, `n` will be an implicit argument (still a natural number). -/ variable {n} lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) := begin split, { rintro rfl, exact ⟨rfl, rfl⟩, }, { rintros ⟨h₀, h⟩, ext x, by_cases hx : x = 0, { rwa hx }, { rw ← fin.succ_pred x hx, convert congr_fun h (fin.pred x hx) } } end /-- The adjacency relation defining the graph structure on `Q n`: `p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/ def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i /-- In `Q 0`, no two vertices are adjacent. -/ lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q := by rintros ⟨v, _⟩; apply fin_zero_elim v /-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent iff their projections to `Q n` are equal. -/ lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) : p.adjacent q ↔ π p = π q := begin split, { rintros ⟨i, h_eq, h_uni⟩, ext x, by_contradiction hx, apply fin.succ_ne_zero x, rw [h_uni _ hx, h_uni _ h₀] }, { intro heq, use [0, h₀], intros y hy, contrapose! hy, rw ←fin.succ_pred _ hy, apply congr_fun heq } end /-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent iff their projections to `Q n` are adjacent. -/ lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) : p.adjacent q ↔ (π p).adjacent (π q) := begin split, { rintros ⟨i, h_eq, h_uni⟩, have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq), use [i.pred h_i, show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)), by rwa fin.succ_pred], intros y hy, simp [eq.symm (h_uni _ hy)] }, { rintros ⟨i, h_eq, h_uni⟩, use [i.succ, h_eq], intros y hy, rw [←fin.pred_inj, fin.pred_succ], { apply h_uni, change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ, simp [hy] }, { contrapose! hy, rw [hy, h₀] }, { apply fin.succ_ne_zero } } end @[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p := by simp only [adjacent, ne_comm] end Q /-! ### The vector space -/ /-- The free vector space on vertices of a hypercube, defined inductively. -/ def V : ℕ → Type | 0 := ℝ | (n+1) := V n × V n namespace V variables (n : ℕ) /-! `V n` is a real vector space whose equality relation is computable. -/ instance : decidable_eq (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : add_comm_group (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : module ℝ (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } end V /-- The basis of `V` indexed by the hypercube, defined inductively. -/ noncomputable def e : Π {n}, Q n → V n | 0 := λ _, (1:ℝ) | (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x)) @[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl /-- The dual basis to `e`, defined inductively. -/ noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ | 0 _ := linear_map.id | (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _) variable {n : ℕ} lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := begin induction n with n IH, { rw (show p = q, from subsingleton.elim p q), dsimp [ε, e], simp }, { dsimp [ε, e], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH], try { congr' 1, rw Q.succ_n_eq, finish }, try { erw (ε _).map_zero, have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish }, simp [this] } } } end /-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/ lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := begin induction n with n ih, { dsimp [ε] at h, exact h (λ _, tt) }, { cases v with v₁ v₂, ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ; [ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h), let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)], all_goals { specialize h q, rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h, rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } } end open module /-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis and `ε` computes coefficients of decompositions of vectors on that basis. -/ def dual_bases_e_ε (n : ℕ) : dual_bases (@e n) (@ε n) := { eval := duality, total := @epsilon_total _ } /-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and, since this cardinal is finite, as a natural number in `finrank_V` -/ lemma dim_V : module.rank ℝ (V n) = 2^n := have module.rank ℝ (V n) = (2^n : ℕ), by { rw [rank_eq_card_basis (dual_bases_e_ε _).basis, Q.card]; apply_instance }, by assumption_mod_cast instance : finite_dimensional ℝ (V n) := finite_dimensional.of_fintype_basis (dual_bases_e_ε _).basis lemma finrank_V : finrank ℝ (V n) = 2^n := have _ := @dim_V n, by rw ←finrank_eq_rank at this; assumption_mod_cast /-! ### The linear map -/ /-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$, defined inductively as a ℝ-linear map from `V n` to `V n`. -/ noncomputable def f : Π n, V n →ₗ[ℝ] V n | 0 := 0 | (n+1) := linear_map.prod (linear_map.coprod (f n) linear_map.id) (linear_map.coprod linear_map.id (-f n)) /-! The preceding definition uses linear map constructions to automatically get that `f` is linear, but its values are somewhat buried as a side-effect. The next two lemmas unbury them. -/ @[simp] lemma f_zero : f 0 = 0 := rfl lemma f_succ_apply (v : V (n+1)) : f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) := begin cases v, rw f, simp only [linear_map.id_apply, linear_map.prod_apply, pi.prod, prod.mk.inj_iff, linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply], exact ⟨rfl, rfl⟩ end /-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number is necessary since otherwise `n • v` refers to the multiplication defined using only the addition of `V`. -/ lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v := begin induction n with n IH; intro, { simpa only [nat.cast_zero, zero_smul] }, { cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel } end /-! We now compute the matrix of `f` in the `e` basis (`p` is the line index, `q` the column index). -/ lemma f_matrix : ∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 := begin induction n with n IH, { intros p q, dsimp [f], simp [Q.not_adjacent_zero] }, { intros p q, have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0, { split_ifs ; norm_num }, have f_map_zero := (show (V (n+0)) →ₗ[ℝ] (V n), from f n).map_zero, dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq, Q.adj_iff_proj_adj] } } end /-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/ noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) := linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id /-! In the following lemmas, `m` will denote a natural number. -/ variables {m : ℕ} /-! Again we unpack what are the values of `g`. -/ lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) := by delta g; simp lemma g_injective : injective (g m) := begin rw g, intros x₁ x₂ h, simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff, pi.prod] at h, exact h.right end lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) : f (m + 1) w = √(m + 1) • w := begin rcases hv with ⟨v, rfl⟩, have : √(m+1) * √(m+1) = m+1 := real.mul_self_sqrt (by exact_mod_cast zero_le _), simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul], abel end /-! ### The main proof In this section, in order to enforce that `n` is positive, we write it as `m + 1` for some natural number `m`. -/ /-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/ notation `dim ` X:70 := module.rank ℝ ↥X /-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/ notation `fdim` := finrank ℝ /-! `Span S` will denote the ℝ-subspace spanned by `S`. -/ notation `Span` := submodule.span ℝ /-! `Card X` will denote the cardinal of a subset of a finite type, as a natural number. -/ notation `Card ` X:70 := X.to_finset.card /-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces, equipped with their subspace structures. The notations come from the general theory of lattices, with inf and sup (also known as meet and join). -/ /-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially intersects the range of `g m`. -/ lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) := begin let W := Span (e '' H), let img := (g m).range, suffices : 0 < dim (W ⊓ img), { simp only [exists_prop], exact_mod_cast exists_mem_ne_zero_of_rank_pos this }, have dim_le : dim (W ⊔ img) ≤ 2^(m + 1), { convert ← rank_submodule_le (W ⊔ img), apply dim_V }, have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m, { convert ← submodule.rank_sup_add_rank_inf_eq W img, rw ← rank_eq_of_injective (g m) g_injective, apply dim_V }, have dimW : dim W = card H, { have li : linear_independent ℝ (H.restrict e), { convert (dual_bases_e_ε _).basis.linear_independent.comp _ subtype.val_injective, rw (dual_bases_e_ε _).coe_basis }, have hdW := rank_span li, rw set.range_restrict at hdW, convert hdW, rw [← (dual_bases_e_ε _).coe_basis, cardinal.mk_image_eq (dual_bases_e_ε _).basis.injective, cardinal.mk_fintype] }, rw ← finrank_eq_rank ℝ at ⊢ dim_le dim_add dimW, rw [← finrank_eq_rank ℝ, ← finrank_eq_rank ℝ] at dim_add, norm_cast at ⊢ dim_le dim_add dimW, rw pow_succ' at dim_le, rw set.to_finset_card at hH, linarith end /-- **Huang sensitivity theorem** also known as the **Huang degree theorem** -/ theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) := begin rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩, have coeffs_support : ((dual_bases_e_ε (m+1)).coeffs y).support ⊆ H.to_finset, { intros p p_in, rw finsupp.mem_support_iff at p_in, rw set.mem_to_finset, exact (dual_bases_e_ε _).mem_of_mem_span y_mem_H p p_in }, obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|, from finite.exists_max _, have H_q_pos : 0 < |ε q y|, { contrapose! y_ne, exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) }, refine ⟨q, (dual_bases_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), _⟩, let s := √(m+1), suffices : s * |ε q y| ≤ ↑(_) * |ε q y|, from (mul_le_mul_right H_q_pos).mp ‹_›, let coeffs := (dual_bases_e_ε (m+1)).coeffs, calc s * |ε q y| = |ε q (s • y)| : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)] ... = |ε q (f (m+1) y)| : by rw [← f_image_g y (by simpa using y_mem_g)] ... = |ε q (f (m+1) (lc _ (coeffs y)))| : by rw (dual_bases_e_ε _).lc_coeffs y ... = |(coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)| : by erw [(f $ m + 1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _ ... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix] ... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter] ... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p) ... = (((coeffs y).support.filter (Q.adjacent q)).card : ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul] ... = (((coeffs y).support ∩ (Q.adjacent q).to_finset).card : ℝ) * |coeffs y q| : by { congr' with x, simp, refl } ... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| : begin refine (mul_le_mul_right H_q_pos).2 _, norm_cast, apply finset.card_le_of_subset, rw set.to_finset_inter, convert finset.inter_subset_inter_right coeffs_support end end end sensitivity
a2e54dbb71bdcb4a7c0d54ed287fd2f69d5ceac9
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Elab/Tactic/ElabTerm.lean
d6bf27ac27b5b1a705b02bd7659485dc74ce6e0f
[ "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,088
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 import Init.Lean.Meta.Tactic.Apply import Init.Lean.Meta.Tactic.Assert import Init.Lean.Elab.Tactic.Basic import Init.Lean.Elab.SyntheticMVars namespace Lean namespace Elab namespace Tactic /- `elabTerm` for Tactics and basic tactics that use it. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := liftTermElabM $ adaptReader (fun (ctx : Term.Context) => { errToSorry := false, .. ctx }) $ do e ← Term.elabTerm stx expectedType?; Term.synthesizeSyntheticMVars mayPostpone; Term.instantiateMVars stx e @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match_syntax stx with | `(tactic| exact $e) => do let ref := stx; (g, gs) ← getMainGoal stx; withMVarContext g $ do { decl ← getMVarDecl g; val ← elabTerm e decl.type; val ← ensureHasType ref decl.type val; ensureHasNoMVars ref val; assignExprMVar g val }; setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match_syntax stx with | `(tactic| refine $e) => do let ref := stx; (g, gs) ← getMainGoal stx; gs' ← withMVarContext g $ do { decl ← getMVarDecl g; val ← elabTerm e decl.type; val ← ensureHasType ref decl.type val; assignExprMVar g val; gs' ← collectMVars ref val; tagUntaggedGoals decl.userName `refine gs'; pure gs' }; setGoals (gs' ++ gs) | _ => throwUnsupportedSyntax @[builtinTactic «apply»] def evalApply : Tactic := fun stx => match_syntax stx with | `(tactic| apply $e) => do let ref := stx; (g, gs) ← getMainGoal stx; gs' ← withMVarContext g $ do { decl ← getMVarDecl g; val ← elabTerm e none true; gs' ← liftMetaM ref $ Meta.apply g val; liftTermElabM $ Term.synthesizeSyntheticMVars false; pure gs' }; -- TODO: handle optParam and autoParam setGoals (gs' ++ gs) | _ => throwUnsupportedSyntax /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := do (mvarId, others) ← getMainGoal stx; withMVarContext mvarId $ do e ← elabTerm stx none; match e with | Expr.fvar fvarId _ => pure fvarId | _ => do type ← inferType stx e; let intro (userName : Name) (useUnusedNames : Bool) : TacticM FVarId := do { (fvarId, mvarId) ← liftMetaM stx $ do { mvarId ← Meta.assert mvarId userName type e; Meta.intro1 mvarId useUnusedNames }; setGoals $ mvarId::others; pure fvarId }; match userName? with | none => intro `h true | some userName => intro userName false end Tactic end Elab end Lean
b701e8e8aca7e8009f440d976b130122ebda2113
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/uniform_space/separation.lean
f8bca62c5c04cb0bda12963d018d1eb2db07dfec
[ "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
13,590
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, Patrick Massot Hausdorff properties of uniform spaces. Separation quotient. -/ import topology.uniform_space.basic open filter topological_space lattice set classical open_locale classical topological_space noncomputable theory set_option eqn_compiler.zeta true universes u v w variables {α : Type u} {β : Type v} {γ : Type w} variables [uniform_space α] [uniform_space β] [uniform_space γ] open_locale uniformity /- separated uniformity -/ /-- The separation relation is the intersection of all entourages. Two points which are related by the separation relation are "indistinguishable" according to the uniform structure. -/ protected def separation_rel (α : Type u) [u : uniform_space α] := ⋂₀ (𝓤 α).sets lemma separated_equiv : equivalence (λx y, (x, y) ∈ separation_rel α) := ⟨assume x, assume s, refl_mem_uniformity, assume x y, assume h (s : set (α×α)) hs, have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, h _ this, assume x y z (hxy : (x, y) ∈ separation_rel α) (hyz : (y, z) ∈ separation_rel α) s (hs : s ∈ 𝓤 α), let ⟨t, ht, (h_ts : comp_rel t t ⊆ s)⟩ := comp_mem_uniformity_sets hs in h_ts $ show (x, z) ∈ comp_rel t t, from ⟨y, hxy t ht, hyz t ht⟩⟩ @[class] def separated (α : Type u) [uniform_space α] := separation_rel α = id_rel theorem separated_def {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, (∀ r ∈ 𝓤 α, (x, y) ∈ r) → x = y := by simp [separated, id_rel_subset.2 separated_equiv.1, subset.antisymm_iff]; simp [subset_def, separation_rel] theorem separated_def' {α : Type u} [uniform_space α] : separated α ↔ ∀ x y, x ≠ y → ∃ r ∈ 𝓤 α, (x, y) ∉ r := separated_def.trans $ forall_congr $ λ x, forall_congr $ λ y, by rw ← not_imp_not; simp [classical.not_forall] instance separated_t2 [s : separated α] : t2_space α := ⟨assume x y, assume h : x ≠ y, let ⟨d, hd, (hxy : (x, y) ∉ d)⟩ := separated_def'.1 s x y h in let ⟨d', hd', (hd'd' : comp_rel d' d' ⊆ d)⟩ := comp_mem_uniformity_sets hd in have {y | (x, y) ∈ d'} ∈ 𝓝 x, from mem_nhds_left x hd', let ⟨u, hu₁, hu₂, hu₃⟩ := mem_nhds_sets_iff.mp this in have {x | (x, y) ∈ d'} ∈ 𝓝 y, from mem_nhds_right y hd', let ⟨v, hv₁, hv₂, hv₃⟩ := mem_nhds_sets_iff.mp this in have u ∩ v = ∅, from eq_empty_of_subset_empty $ assume z ⟨(h₁ : z ∈ u), (h₂ : z ∈ v)⟩, have (x, y) ∈ comp_rel d' d', from ⟨z, hu₁ h₁, hv₁ h₂⟩, hxy $ hd'd' this, ⟨u, v, hu₂, hv₂, hu₃, hv₃, this⟩⟩ instance separated_regular [separated α] : regular_space α := { regular := λs a hs ha, have -s ∈ 𝓝 a, from mem_nhds_sets hs ha, have {p : α × α | p.1 = a → p.2 ∈ -s} ∈ 𝓤 α, from mem_nhds_uniformity_iff.mp this, let ⟨d, hd, h⟩ := comp_mem_uniformity_sets this in let e := {y:α| (a, y) ∈ d} in have hae : a ∈ closure e, from subset_closure $ refl_mem_uniformity hd, have set.prod (closure e) (closure e) ⊆ comp_rel d (comp_rel (set.prod e e) d), begin rw [←closure_prod_eq, closure_eq_inter_uniformity], change (⨅d' ∈ 𝓤 α, _) ≤ comp_rel d (comp_rel _ d), exact (infi_le_of_le d $ infi_le_of_le hd $ le_refl _) end, have e_subset : closure e ⊆ -s, from assume a' ha', let ⟨x, (hx : (a, x) ∈ d), y, ⟨hx₁, hx₂⟩, (hy : (y, _) ∈ d)⟩ := @this ⟨a, a'⟩ ⟨hae, ha'⟩ in have (a, a') ∈ comp_rel d d, from ⟨y, hx₂, hy⟩, h this rfl, have closure e ∈ 𝓝 a, from (𝓝 a).sets_of_superset (mem_nhds_left a hd) subset_closure, have 𝓝 a ⊓ principal (-closure e) = ⊥, from (@inf_eq_bot_iff_le_compl _ _ _ (principal (- closure e)) (principal (closure e)) (by simp [principal_univ, union_comm]) (by simp)).mpr (by simp [this]), ⟨- closure e, is_closed_closure, assume x h₁ h₂, @e_subset x h₂ h₁, this⟩, ..separated_t2 } /- separation space -/ namespace uniform_space def separation_setoid (α : Type u) [uniform_space α] : setoid α := ⟨λx y, (x, y) ∈ separation_rel α, separated_equiv⟩ local attribute [instance] separation_setoid instance separation_setoid.uniform_space {α : Type u} [u : uniform_space α] : uniform_space (quotient (separation_setoid α)) := { to_topological_space := u.to_topological_space.coinduced (λx, ⟦x⟧), uniformity := map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity, refl := le_trans (by simp [quotient.exists_rep]) (filter.map_mono refl_le_uniformity), symm := tendsto_map' $ by simp [prod.swap, (∘)]; exact tendsto_map.comp tendsto_swap_uniformity, comp := calc (map (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) u.uniformity).lift' (λs, comp_rel s s) = u.uniformity.lift' ((λs, comp_rel s s) ∘ image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧))) : map_lift'_eq2 $ monotone_comp_rel monotone_id monotone_id ... ≤ u.uniformity.lift' (image (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ∘ (λs:set (α×α), comp_rel s (comp_rel s s))) : lift'_mono' $ assume s hs ⟨a, b⟩ ⟨c, ⟨⟨a₁, a₂⟩, ha, a_eq⟩, ⟨⟨b₁, b₂⟩, hb, b_eq⟩⟩, begin simp at a_eq, simp at b_eq, have h : ⟦a₂⟧ = ⟦b₁⟧, { rw [a_eq.right, b_eq.left] }, have h : (a₂, b₁) ∈ separation_rel α := quotient.exact h, simp [function.comp, set.image, comp_rel, and.comm, and.left_comm, and.assoc], exact ⟨a₁, a_eq.left, b₂, b_eq.right, a₂, ha, b₁, h s hs, hb⟩ end ... = map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) (u.uniformity.lift' (λs:set (α×α), comp_rel s (comp_rel s s))) : by rw [map_lift'_eq]; exact monotone_comp_rel monotone_id (monotone_comp_rel monotone_id monotone_id) ... ≤ map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) u.uniformity : map_mono comp_le_uniformity3, is_open_uniformity := assume s, have ∀a, ⟦a⟧ ∈ s → ({p:α×α | p.1 = a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α ↔ {p:α×α | p.1 ≈ a → ⟦p.2⟧ ∈ s} ∈ 𝓤 α), from assume a ha, ⟨assume h, let ⟨t, ht, hts⟩ := comp_mem_uniformity_sets h in have hts : ∀{a₁ a₂}, (a, a₁) ∈ t → (a₁, a₂) ∈ t → ⟦a₂⟧ ∈ s, from assume a₁ a₂ ha₁ ha₂, @hts (a, a₂) ⟨a₁, ha₁, ha₂⟩ rfl, have ht' : ∀{a₁ a₂}, a₁ ≈ a₂ → (a₁, a₂) ∈ t, from assume a₁ a₂ h, sInter_subset_of_mem ht h, u.uniformity.sets_of_superset ht $ assume ⟨a₁, a₂⟩ h₁ h₂, hts (ht' $ setoid.symm h₂) h₁, assume h, u.uniformity.sets_of_superset h $ by simp {contextual := tt}⟩, begin simp [topological_space.coinduced, u.is_open_uniformity, uniformity, forall_quotient_iff], exact ⟨λh a ha, (this a ha).mp $ h a ha, λh a ha, (this a ha).mpr $ h a ha⟩ end } lemma uniformity_quotient : 𝓤 (quotient (separation_setoid α)) = (𝓤 α).map (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)) := rfl lemma uniform_continuous_quotient_mk : uniform_continuous (quotient.mk : α → quotient (separation_setoid α)) := le_refl _ lemma uniform_continuous_quotient {f : quotient (separation_setoid α) → β} (hf : uniform_continuous (λx, f ⟦x⟧)) : uniform_continuous f := hf lemma uniform_continuous_quotient_lift {f : α → β} {h : ∀a b, (a, b) ∈ separation_rel α → f a = f b} (hf : uniform_continuous f) : uniform_continuous (λa, quotient.lift f h a) := uniform_continuous_quotient hf lemma uniform_continuous_quotient_lift₂ {f : α → β → γ} {h : ∀a c b d, (a, b) ∈ separation_rel α → (c, d) ∈ separation_rel β → f a c = f b d} (hf : uniform_continuous (λp:α×β, f p.1 p.2)) : uniform_continuous (λp:_×_, quotient.lift₂ f h p.1 p.2) := begin rw [uniform_continuous, uniformity_prod_eq_prod, uniformity_quotient, uniformity_quotient, filter.prod_map_map_eq, filter.tendsto_map'_iff, filter.tendsto_map'_iff], rwa [uniform_continuous, uniformity_prod_eq_prod, filter.tendsto_map'_iff] at hf end lemma comap_quotient_le_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) ≤ (𝓤 α) := assume t' ht', let ⟨t, ht, tt_t'⟩ := comp_mem_uniformity_sets ht' in let ⟨s, hs, ss_t⟩ := comp_mem_uniformity_sets ht in ⟨(λp:α×α, (⟦p.1⟧, ⟦p.2⟧)) '' s, (𝓤 α).sets_of_superset hs $ assume x hx, ⟨x, hx, rfl⟩, assume ⟨a₁, a₂⟩ ⟨⟨b₁, b₂⟩, hb, ab_eq⟩, have ⟦b₁⟧ = ⟦a₁⟧ ∧ ⟦b₂⟧ = ⟦a₂⟧, from prod.mk.inj ab_eq, have b₁ ≈ a₁ ∧ b₂ ≈ a₂, from and.imp quotient.exact quotient.exact this, have ab₁ : (a₁, b₁) ∈ t, from (setoid.symm this.left) t ht, have ba₂ : (b₂, a₂) ∈ s, from this.right s hs, tt_t' ⟨b₁, show ((a₁, a₂).1, b₁) ∈ t, from ab₁, ss_t ⟨b₂, show ((b₁, a₂).1, b₂) ∈ s, from hb, ba₂⟩⟩⟩ lemma comap_quotient_eq_uniformity : (𝓤 $ quotient $ separation_setoid α).comap (λ (p : α × α), (⟦p.fst⟧, ⟦p.snd⟧)) = 𝓤 α := le_antisymm comap_quotient_le_uniformity le_comap_map instance separated_separation : separated (quotient (separation_setoid α)) := set.ext $ assume ⟨a, b⟩, quotient.induction_on₂ a b $ assume a b, ⟨assume h, have a ≈ b, from assume s hs, have s ∈ (𝓤 $ quotient $ separation_setoid α).comap (λp:(α×α), (⟦p.1⟧, ⟦p.2⟧)), from comap_quotient_le_uniformity hs, let ⟨t, ht, hts⟩ := this in hts begin dsimp [preimage], exact h t ht end, show ⟦a⟧ = ⟦b⟧, from quotient.sound this, assume heq : ⟦a⟧ = ⟦b⟧, assume h hs, heq ▸ refl_mem_uniformity hs⟩ lemma separated_of_uniform_continuous {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x ≈ f y := assume _ h', h _ (H h') lemma eq_of_separated_of_uniform_continuous [separated β] {f : α → β} {x y : α} (H : uniform_continuous f) (h : x ≈ y) : f x = f y := separated_def.1 (by apply_instance) _ _ $ separated_of_uniform_continuous H h def separation_quotient (α : Type*) [uniform_space α] := quotient (separation_setoid α) namespace separation_quotient instance : uniform_space (separation_quotient α) := by dunfold separation_quotient ; apply_instance instance : separated (separation_quotient α) := by dunfold separation_quotient ; apply_instance def lift [separated β] (f : α → β) : (separation_quotient α → β) := if h : uniform_continuous f then quotient.lift f (λ x y, eq_of_separated_of_uniform_continuous h) else λ x, f (classical.inhabited_of_nonempty $ (nonempty_quotient_iff $ separation_setoid α).1 ⟨x⟩).default lemma lift_mk [separated β] {f : α → β} (h : uniform_continuous f) (a : α) : lift f ⟦a⟧ = f a := by rw [lift, dif_pos h]; refl lemma uniform_continuous_lift [separated β] (f : α → β) : uniform_continuous (lift f) := begin by_cases hf : uniform_continuous f, { rw [lift, dif_pos hf], exact uniform_continuous_quotient_lift hf }, { rw [lift, dif_neg hf], exact uniform_continuous_of_const (assume a b, rfl) } end def map (f : α → β) : separation_quotient α → separation_quotient β := lift (quotient.mk ∘ f) lemma map_mk {f : α → β} (h : uniform_continuous f) (a : α) : map f ⟦a⟧ = ⟦f a⟧ := by rw [map, lift_mk (uniform_continuous_quotient_mk.comp h)] lemma uniform_continuous_map (f : α → β) : uniform_continuous (map f) := uniform_continuous_lift (quotient.mk ∘ f) lemma map_unique {f : α → β} (hf : uniform_continuous f) {g : separation_quotient α → separation_quotient β} (comm : quotient.mk ∘ f = g ∘ quotient.mk) : map f = g := by ext ⟨a⟩; calc map f ⟦a⟧ = ⟦f a⟧ : map_mk hf a ... = g ⟦a⟧ : congr_fun comm a lemma map_id : map (@id α) = id := map_unique uniform_continuous_id rfl lemma map_comp {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : map g ∘ map f = map (g ∘ f) := (map_unique (hg.comp hf) $ by simp only [(∘), map_mk, hf, hg]).symm end separation_quotient lemma separation_prod {a₁ a₂ : α} {b₁ b₂ : β} : (a₁, b₁) ≈ (a₂, b₂) ↔ a₁ ≈ a₂ ∧ b₁ ≈ b₂ := begin split, { assume h, exact ⟨separated_of_uniform_continuous uniform_continuous_fst h, separated_of_uniform_continuous uniform_continuous_snd h⟩ }, { rintros ⟨eqv_α, eqv_β⟩ r r_in, rw uniformity_prod at r_in, rcases r_in with ⟨t_α, ⟨r_α, r_α_in, h_α⟩, t_β, ⟨r_β, r_β_in, h_β⟩, H⟩, let p_α := λ(p : (α × β) × (α × β)), (p.1.1, p.2.1), let p_β := λ(p : (α × β) × (α × β)), (p.1.2, p.2.2), have key_α : p_α ((a₁, b₁), (a₂, b₂)) ∈ r_α, { simp [p_α, eqv_α r_α r_α_in] }, have key_β : p_β ((a₁, b₁), (a₂, b₂)) ∈ r_β, { simp [p_β, eqv_β r_β r_β_in] }, exact H ⟨h_α key_α, h_β key_β⟩ }, end instance separated.prod [separated α] [separated β] : separated (α × β) := separated_def.2 $ assume x y H, prod.ext (eq_of_separated_of_uniform_continuous uniform_continuous_fst H) (eq_of_separated_of_uniform_continuous uniform_continuous_snd H) end uniform_space
3e100f571e13adaf5d0224a07396a2ab19354051
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/817.lean
f43cd65732a1054229c06ce48b9775119ae6caab
[ "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
254
lean
variables A B : Prop variables(H₁ : A) (H₂ : A → B) example : B := suffices A ∧ (A → B), from and.right this (and.left this), and.intro H₁ H₂ example : B := suffices H : A ∧ (A → B), from and.right H (and.left H), and.intro H₁ H₂
72a6ec55ada969d00efd3ae162f669c4a07f09ca
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/cones.lean
486157996a98dc8f6261992c789679ffe9920b82
[]
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
37,605
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, Floris van Doorn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.const import Mathlib.category_theory.discrete_category import Mathlib.category_theory.yoneda import Mathlib.category_theory.reflects_isomorphisms import Mathlib.PostPort universes v u l u' namespace Mathlib namespace category_theory namespace functor /-- `F.cones` is the functor assigning to an object `X` the type of natural transformations from the constant functor with value `X` to `F`. An object representing this functor is a limit of `F`. -/ def cones {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) : Cᵒᵖ ⥤ Type v := functor.op (const J) ⋙ obj yoneda F /-- `F.cocones` is the functor assigning to an object `X` the type of natural transformations from `F` to the constant functor with value `X`. An object corepresenting this functor is a colimit of `F`. -/ @[simp] theorem cocones_obj {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) (X : C) : obj (cocones F) X = (F ⟶ obj (const J) X) := Eq.refl (F ⟶ obj (const J) X) end functor /-- Functorially associated to each functor `J ⥤ C`, we have the `C`-presheaf consisting of cones with a given cone point. -/ @[simp] theorem cones_map (J : Type v) [small_category J] (C : Type u) [category C] (F : J ⥤ C) (G : J ⥤ C) (f : F ⟶ G) : functor.map (cones J C) f = whisker_left (functor.op (functor.const J)) (functor.map yoneda f) := Eq.refl (functor.map (cones J C) f) /-- Contravariantly associated to each functor `J ⥤ C`, we have the `C`-copresheaf consisting of cocones with a given cocone point. -/ @[simp] theorem cocones_obj (J : Type v) [small_category J] (C : Type u) [category C] (F : J ⥤ Cᵒᵖ) : functor.obj (cocones J C) F = functor.cocones (opposite.unop F) := Eq.refl (functor.obj (cocones J C) F) namespace limits /-- A `c : cone F` is: * an object `c.X` and * a natural transformation `c.π : c.X ⟶ F` from the constant `c.X` functor to `F`. `cone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cones.obj X`. -/ structure cone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where X : C π : functor.obj (functor.const J) X ⟶ F protected instance inhabited_cone {C : Type u} [category C] (F : discrete PUnit ⥤ C) : Inhabited (cone F) := { default := cone.mk (functor.obj F PUnit.unit) (nat_trans.mk fun (X : discrete PUnit) => sorry) } @[simp] theorem cone.w {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone F) {j : J} {j' : J} (f : j ⟶ j') : nat_trans.app (cone.π c) j ≫ functor.map F f = nat_trans.app (cone.π c) j' := sorry /-- A `c : cocone F` is * an object `c.X` and * a natural transformation `c.ι : F ⟶ c.X` from `F` to the constant `c.X` functor. `cocone F` is equivalent, via `cone.equiv` below, to `Σ X, F.cocones.obj X`. -/ structure cocone {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) where X : C ι : F ⟶ functor.obj (functor.const J) X protected instance inhabited_cocone {C : Type u} [category C] (F : discrete PUnit ⥤ C) : Inhabited (cocone F) := { default := cocone.mk (functor.obj F PUnit.unit) (nat_trans.mk fun (X : discrete PUnit) => sorry) } @[simp] theorem cocone.w_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone F) {j : J} {j' : J} (f : j ⟶ j') {X' : C} (f' : functor.obj (functor.obj (functor.const J) (cocone.X c)) j' ⟶ X') : functor.map F f ≫ nat_trans.app (cocone.ι c) j' ≫ f' = nat_trans.app (cocone.ι c) j ≫ f' := sorry namespace cone /-- The isomorphism between a cone on `F` and an element of the functor `F.cones`. -/ def equiv {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) : cone F ≅ sigma fun (X : Cᵒᵖ) => functor.obj (functor.cones F) X := iso.mk (fun (c : cone F) => sigma.mk (opposite.op (X c)) (π c)) fun (c : sigma fun (X : Cᵒᵖ) => functor.obj (functor.cones F) X) => mk (opposite.unop (sigma.fst c)) (sigma.snd c) /-- A map to the vertex of a cone naturally induces a cone by composition. -/ @[simp] def extensions {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone F) : functor.obj yoneda (X c) ⟶ functor.cones F := nat_trans.mk fun (X : Cᵒᵖ) (f : functor.obj (functor.obj yoneda (X c)) X) => functor.map (functor.const J) f ≫ π c /-- A map to the vertex of a cone induces a cone by composition. -/ @[simp] def extend {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone F) {X : C} (f : X ⟶ X c) : cone F := mk X (nat_trans.app (extensions c) (opposite.op X) f) @[simp] theorem extend_π {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone F) {X : Cᵒᵖ} (f : opposite.unop X ⟶ X c) : π (extend c f) = nat_trans.app (extensions c) X f := rfl /-- Whisker a cone by precomposition of a functor. -/ def whisker {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : cone (E ⋙ F) := mk (X c) (whisker_left E (π c)) end cone namespace cocone /-- The isomorphism between a cocone on `F` and an element of the functor `F.cocones`. -/ def equiv {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) : cocone F ≅ sigma fun (X : C) => functor.obj (functor.cocones F) X := iso.mk (fun (c : cocone F) => sigma.mk (X c) (ι c)) fun (c : sigma fun (X : C) => functor.obj (functor.cocones F) X) => mk (sigma.fst c) (sigma.snd c) /-- A map from the vertex of a cocone naturally induces a cocone by composition. -/ @[simp] def extensions {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone F) : functor.obj coyoneda (opposite.op (X c)) ⟶ functor.cocones F := nat_trans.mk fun (X : C) (f : functor.obj (functor.obj coyoneda (opposite.op (X c))) X) => ι c ≫ functor.map (functor.const J) f /-- A map from the vertex of a cocone induces a cocone by composition. -/ @[simp] def extend {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone F) {X : C} (f : X c ⟶ X) : cocone F := mk X (nat_trans.app (extensions c) X f) @[simp] theorem extend_ι {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone F) {X : C} (f : X c ⟶ X) : ι (extend c f) = nat_trans.app (extensions c) X f := rfl /-- Whisker a cocone by precomposition of a functor. See `whiskering` for a functorial version. -/ @[simp] theorem whisker_ι {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (E : K ⥤ J) (c : cocone F) : ι (whisker E c) = whisker_left E (ι c) := Eq.refl (ι (whisker E c)) end cocone /-- A cone morphism between two cones for the same diagram is a morphism of the cone points which commutes with the cone legs. -/ structure cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (A : cone F) (B : cone F) where hom : cone.X A ⟶ cone.X B w' : autoParam (∀ (j : J), hom ≫ nat_trans.app (cone.π B) j = nat_trans.app (cone.π A) j) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem cone_morphism.w {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {A : cone F} {B : cone F} (c : cone_morphism A B) (j : J) : cone_morphism.hom c ≫ nat_trans.app (cone.π B) j = nat_trans.app (cone.π A) j := sorry @[simp] theorem cone_morphism.w_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {A : cone F} {B : cone F} (c : cone_morphism A B) (j : J) {X' : C} (f' : functor.obj F j ⟶ X') : cone_morphism.hom c ≫ nat_trans.app (cone.π B) j ≫ f' = nat_trans.app (cone.π A) j ≫ f' := sorry protected instance inhabited_cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (A : cone F) : Inhabited (cone_morphism A A) := { default := cone_morphism.mk 𝟙 } /-- The category of cones on a given diagram. -/ protected instance cone.category {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} : category (cone F) := category.mk namespace cones /-- To give an isomorphism between cones, it suffices to give an isomorphism between their vertices which commutes with the cone maps. -/ def ext {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {c : cone F} {c' : cone F} (φ : cone.X c ≅ cone.X c') (w : ∀ (j : J), nat_trans.app (cone.π c) j = iso.hom φ ≫ nat_trans.app (cone.π c') j) : c ≅ c' := iso.mk (cone_morphism.mk (iso.hom φ)) (cone_morphism.mk (iso.inv φ)) /-- Given a cone morphism whose object part is an isomorphism, produce an isomorphism of cones. -/ def cone_iso_of_hom_iso {J : Type v} [small_category J] {C : Type u} [category C] {K : J ⥤ C} {c : cone K} {d : cone K} (f : c ⟶ d) [i : is_iso (cone_morphism.hom f)] : is_iso f := is_iso.mk (cone_morphism.mk (inv (cone_morphism.hom f))) /-- Functorially postcompose a cone for `F` by a natural transformation `F ⟶ G` to give a cone for `G`. -/ @[simp] theorem postcompose_map_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ⟶ G) (c₁ : cone F) (c₂ : cone F) (f : c₁ ⟶ c₂) : cone_morphism.hom (functor.map (postcompose α) f) = cone_morphism.hom f := Eq.refl (cone_morphism.hom (functor.map (postcompose α) f)) /-- Postcomposing a cone by the composite natural transformation `α ≫ β` is the same as postcomposing by `α` and then by `β`. -/ def postcompose_comp {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : postcompose (α ≫ β) ≅ postcompose α ⋙ postcompose β := nat_iso.of_components (fun (s : cone F) => ext (iso.refl (cone.X (functor.obj (postcompose (α ≫ β)) s))) sorry) sorry /-- Postcomposing by the identity does not change the cone up to isomorphism. -/ def postcompose_id {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} : postcompose 𝟙 ≅ 𝟭 := nat_iso.of_components (fun (s : cone F) => ext (iso.refl (cone.X (functor.obj (postcompose 𝟙) s))) sorry) sorry /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cones. -/ @[simp] theorem postcompose_equivalence_unit_iso {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : F ≅ G) : equivalence.unit_iso (postcompose_equivalence α) = nat_iso.of_components (fun (s : cone F) => ext (iso.refl (cone.X (functor.obj 𝟭 s))) (postcompose_equivalence._proof_1 α s)) (postcompose_equivalence._proof_2 α) := Eq.refl (equivalence.unit_iso (postcompose_equivalence α)) /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cone F` to `cone (E ⋙ F)`. -/ @[simp] theorem whiskering_obj {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (E : K ⥤ J) (c : cone F) : functor.obj (whiskering E) c = cone.whisker E c := Eq.refl (functor.obj (whiskering E) c) /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ @[simp] theorem whiskering_equivalence_inverse {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (e : K ≌ J) : equivalence.inverse (whiskering_equivalence e) = whiskering (equivalence.inverse e) ⋙ postcompose (iso.inv (functor.associator (equivalence.inverse e) (equivalence.functor e) F) ≫ whisker_right (iso.hom (equivalence.counit_iso e)) F ≫ iso.hom (functor.left_unitor F)) := Eq.refl (equivalence.inverse (whiskering_equivalence e)) /-- The categories of cones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ def equivalence_of_reindexing {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : equivalence.functor e ⋙ F ≅ G) : cone F ≌ cone G := equivalence.trans (whiskering_equivalence e) (postcompose_equivalence α) /-- Forget the cone structure and obtain just the cone point. -/ def forget {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) : cone F ⥤ C := functor.mk (fun (t : cone F) => cone.X t) fun (s t : cone F) (f : s ⟶ t) => cone_morphism.hom f /-- A functor `G : C ⥤ D` sends cones over `F` to cones over `F ⋙ G` functorially. -/ @[simp] theorem functoriality_obj_π_app {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) (A : cone F) (j : J) : nat_trans.app (cone.π (functor.obj (functoriality F G) A)) j = functor.map G (nat_trans.app (cone.π A) j) := Eq.refl (nat_trans.app (cone.π (functor.obj (functoriality F G) A)) j) protected instance functoriality_full {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) [full G] [faithful G] : full (functoriality F G) := full.mk fun (X Y : cone F) (t : functor.obj (functoriality F G) X ⟶ functor.obj (functoriality F G) Y) => cone_morphism.mk (functor.preimage G (cone_morphism.hom t)) protected instance functoriality_faithful {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) [faithful G] : faithful (functoriality F G) := faithful.mk /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cones over `F` and cones over `F ⋙ e.functor`. -/ @[simp] theorem functoriality_equivalence_counit_iso {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (e : C ≌ D) : equivalence.counit_iso (functoriality_equivalence F e) = nat_iso.of_components (fun (c : cone (F ⋙ equivalence.functor e)) => ext (iso.app (equivalence.counit_iso e) (cone.X c)) (functoriality_equivalence._proof_3 F e c)) (functoriality_equivalence._proof_4 F e) := Eq.refl (equivalence.counit_iso (functoriality_equivalence F e)) /-- If `F` reflects isomorphisms, then `cones.functoriality F` reflects isomorphisms as well. -/ protected instance reflects_cone_isomorphism {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (functoriality K F) := reflects_isomorphisms.mk fun (A B : cone K) (f : A ⟶ B) (_inst_3_1 : is_iso (functor.map (functoriality K F) f)) => cone_iso_of_hom_iso f end cones /-- A cocone morphism between two cocones for the same diagram is a morphism of the cocone points which commutes with the cocone legs. -/ structure cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (A : cocone F) (B : cocone F) where hom : cocone.X A ⟶ cocone.X B w' : autoParam (∀ (j : J), nat_trans.app (cocone.ι A) j ≫ hom = nat_trans.app (cocone.ι B) j) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) protected instance inhabited_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (A : cocone F) : Inhabited (cocone_morphism A A) := { default := cocone_morphism.mk 𝟙 } @[simp] theorem cocone_morphism.w {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {A : cocone F} {B : cocone F} (c : cocone_morphism A B) (j : J) : nat_trans.app (cocone.ι A) j ≫ cocone_morphism.hom c = nat_trans.app (cocone.ι B) j := sorry @[simp] theorem cocone_morphism.w_assoc {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {A : cocone F} {B : cocone F} (c : cocone_morphism A B) (j : J) {X' : C} (f' : cocone.X B ⟶ X') : nat_trans.app (cocone.ι A) j ≫ cocone_morphism.hom c ≫ f' = nat_trans.app (cocone.ι B) j ≫ f' := sorry @[simp] theorem cocone.category_to_category_struct_id_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (B : cocone F) : cocone_morphism.hom 𝟙 = 𝟙 := Eq.refl (cocone_morphism.hom 𝟙) namespace cocones /-- To give an isomorphism between cocones, it suffices to give an isomorphism between their vertices which commutes with the cocone maps. -/ @[simp] theorem ext_inv_hom {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {c : cocone F} {c' : cocone F} (φ : cocone.X c ≅ cocone.X c') (w : ∀ (j : J), nat_trans.app (cocone.ι c) j ≫ iso.hom φ = nat_trans.app (cocone.ι c') j) : cocone_morphism.hom (iso.inv (ext φ w)) = iso.inv φ := Eq.refl (cocone_morphism.hom (iso.inv (ext φ w))) /-- Given a cocone morphism whose object part is an isomorphism, produce an isomorphism of cocones. -/ def cocone_iso_of_hom_iso {J : Type v} [small_category J] {C : Type u} [category C] {K : J ⥤ C} {c : cocone K} {d : cocone K} (f : c ⟶ d) [i : is_iso (cocone_morphism.hom f)] : is_iso f := is_iso.mk (cocone_morphism.mk (inv (cocone_morphism.hom f))) /-- Functorially precompose a cocone for `F` by a natural transformation `G ⟶ F` to give a cocone for `G`. -/ def precompose {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : G ⟶ F) : cocone F ⥤ cocone G := functor.mk (fun (c : cocone F) => cocone.mk (cocone.X c) (α ≫ cocone.ι c)) fun (c₁ c₂ : cocone F) (f : c₁ ⟶ c₂) => cocone_morphism.mk (cocone_morphism.hom f) /-- Precomposing a cocone by the composite natural transformation `α ≫ β` is the same as precomposing by `β` and then by `α`. -/ def precompose_comp {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} {H : J ⥤ C} (α : F ⟶ G) (β : G ⟶ H) : precompose (α ≫ β) ≅ precompose β ⋙ precompose α := nat_iso.of_components (fun (s : cocone H) => ext (iso.refl (cocone.X (functor.obj (precompose (α ≫ β)) s))) sorry) sorry /-- Precomposing by the identity does not change the cocone up to isomorphism. -/ def precompose_id {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} : precompose 𝟙 ≅ 𝟭 := nat_iso.of_components (fun (s : cocone F) => ext (iso.refl (cocone.X (functor.obj (precompose 𝟙) s))) sorry) sorry /-- If `F` and `G` are naturally isomorphic functors, then they have equivalent categories of cocones. -/ @[simp] theorem precompose_equivalence_functor {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {G : J ⥤ C} (α : G ≅ F) : equivalence.functor (precompose_equivalence α) = precompose (iso.hom α) := Eq.refl (equivalence.functor (precompose_equivalence α)) /-- Whiskering on the left by `E : K ⥤ J` gives a functor from `cocone F` to `cocone (E ⋙ F)`. -/ def whiskering {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (E : K ⥤ J) : cocone F ⥤ cocone (E ⋙ F) := functor.mk (fun (c : cocone F) => cocone.whisker E c) fun (c c' : cocone F) (f : c ⟶ c') => cocone_morphism.mk (cocone_morphism.hom f) /-- Whiskering by an equivalence gives an equivalence between categories of cones. -/ def whiskering_equivalence {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] (e : K ≌ J) : cocone F ≌ cocone (equivalence.functor e ⋙ F) := equivalence.mk' (whiskering (equivalence.functor e)) (whiskering (equivalence.inverse e) ⋙ precompose (iso.inv (functor.left_unitor F) ≫ whisker_right (iso.inv (equivalence.counit_iso e)) F ≫ iso.inv (functor.associator (equivalence.inverse e) (equivalence.functor e) F))) (nat_iso.of_components (fun (s : cocone F) => ext (iso.refl (cocone.X (functor.obj 𝟭 s))) sorry) sorry) (nat_iso.of_components (fun (s : cocone (equivalence.functor e ⋙ F)) => ext (iso.refl (cocone.X (functor.obj ((whiskering (equivalence.inverse e) ⋙ precompose (iso.inv (functor.left_unitor F) ≫ whisker_right (iso.inv (equivalence.counit_iso e)) F ≫ iso.inv (functor.associator (equivalence.inverse e) (equivalence.functor e) F))) ⋙ whiskering (equivalence.functor e)) s))) sorry) sorry) /-- The categories of cocones over `F` and `G` are equivalent if `F` and `G` are naturally isomorphic (possibly after changing the indexing category by an equivalence). -/ @[simp] theorem equivalence_of_reindexing_functor_obj {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {K : Type v} [small_category K] {G : K ⥤ C} (e : K ≌ J) (α : equivalence.functor e ⋙ F ≅ G) (X : cocone F) : functor.obj (equivalence.functor (equivalence_of_reindexing e α)) X = functor.obj (precompose (iso.inv α)) (cocone.whisker (equivalence.functor e) X) := Eq.refl (functor.obj (precompose (iso.inv α)) (cocone.whisker (equivalence.functor e) X)) /-- Forget the cocone structure and obtain just the cocone point. -/ @[simp] theorem forget_map {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) (s : cocone F) (t : cocone F) (f : s ⟶ t) : functor.map (forget F) f = cocone_morphism.hom f := Eq.refl (functor.map (forget F) f) /-- A functor `G : C ⥤ D` sends cocones over `F` to cocones over `F ⋙ G` functorially. -/ @[simp] theorem functoriality_map_hom {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) (_x : cocone F) : ∀ (_x_1 : cocone F) (f : _x ⟶ _x_1), cocone_morphism.hom (functor.map (functoriality F G) f) = functor.map G (cocone_morphism.hom f) := fun (_x_1 : cocone F) (f : _x ⟶ _x_1) => Eq.refl (cocone_morphism.hom (functor.map (functoriality F G) f)) protected instance functoriality_full {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) [full G] [faithful G] : full (functoriality F G) := full.mk fun (X Y : cocone F) (t : functor.obj (functoriality F G) X ⟶ functor.obj (functoriality F G) Y) => cocone_morphism.mk (functor.preimage G (cocone_morphism.hom t)) protected instance functoriality_faithful {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (G : C ⥤ D) [faithful G] : faithful (functoriality F G) := faithful.mk /-- If `e : C ≌ D` is an equivalence of categories, then `functoriality F e.functor` induces an equivalence between cocones over `F` and cocones over `F ⋙ e.functor`. -/ @[simp] theorem functoriality_equivalence_functor {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) {D : Type u'} [category D] (e : C ≌ D) : equivalence.functor (functoriality_equivalence F e) = functoriality F (equivalence.functor e) := Eq.refl (equivalence.functor (functoriality_equivalence F e)) /-- If `F` reflects isomorphisms, then `cocones.functoriality F` reflects isomorphisms as well. -/ protected instance reflects_cocone_isomorphism {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] (F : C ⥤ D) [reflects_isomorphisms F] (K : J ⥤ C) : reflects_isomorphisms (functoriality K F) := reflects_isomorphisms.mk fun (A B : cocone K) (f : A ⟶ B) (_inst_3_1 : is_iso (functor.map (functoriality K F) f)) => cocone_iso_of_hom_iso f end cocones end limits namespace functor /-- The image of a cone in C under a functor G : C ⥤ D is a cone in D. -/ /-- The image of a cocone in C under a functor G : C ⥤ D is a cocone in D. -/ @[simp] theorem map_cone_X {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) (c : limits.cone F) : limits.cone.X (map_cone H c) = obj H (limits.cone.X c) := Eq.refl (obj H (limits.cone.X c)) @[simp] theorem map_cocone_ι_app {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) (c : limits.cocone F) (j : J) : nat_trans.app (limits.cocone.ι (map_cocone H c)) j = map H (nat_trans.app (limits.cocone.ι c) j) := Eq.refl (map H (nat_trans.app (limits.cocone.ι c) j)) /-- Given a cone morphism `c ⟶ c'`, construct a cone morphism on the mapped cones functorially. -/ def map_cone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) {c : limits.cone F} {c' : limits.cone F} (f : c ⟶ c') : map_cone H c ⟶ map_cone H c' := map (limits.cones.functoriality F H) f /-- Given a cocone morphism `c ⟶ c'`, construct a cocone morphism on the mapped cocones functorially. -/ def map_cocone_morphism {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) {c : limits.cocone F} {c' : limits.cocone F} (f : c ⟶ c') : map_cocone H c ⟶ map_cocone H c' := map (limits.cocones.functoriality F H) f /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cone_inv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) [is_equivalence H] (c : limits.cone (F ⋙ H)) : limits.cone F := obj (equivalence.inverse (limits.cones.functoriality_equivalence F (as_equivalence H))) c /-- `map_cone` is the left inverse to `map_cone_inv`. -/ def map_cone_map_cone_inv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : limits.cone (F ⋙ H)) : map_cone H (map_cone_inv H c) ≅ c := iso.app (equivalence.counit_iso (limits.cones.functoriality_equivalence F (as_equivalence H))) c /-- `map_cone` is the right inverse to `map_cone_inv`. -/ def map_cone_inv_map_cone {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : limits.cone F) : map_cone_inv H (map_cone H c) ≅ c := iso.app (iso.symm (equivalence.unit_iso (limits.cones.functoriality_equivalence F (as_equivalence H)))) c /-- If `H` is an equivalence, we invert `H.map_cone` and get a cone for `F` from a cone for `F ⋙ H`.-/ def map_cocone_inv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) [is_equivalence H] (c : limits.cocone (F ⋙ H)) : limits.cocone F := obj (equivalence.inverse (limits.cocones.functoriality_equivalence F (as_equivalence H))) c /-- `map_cocone` is the left inverse to `map_cocone_inv`. -/ def map_cocone_map_cocone_inv {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : limits.cocone (F ⋙ H)) : map_cocone H (map_cocone_inv H c) ≅ c := iso.app (equivalence.counit_iso (limits.cocones.functoriality_equivalence F (as_equivalence H))) c /-- `map_cocone` is the right inverse to `map_cocone_inv`. -/ def map_cocone_inv_map_cocone {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ D} (H : D ⥤ C) [is_equivalence H] (c : limits.cocone F) : map_cocone_inv H (map_cocone H c) ≅ c := iso.app (iso.symm (equivalence.unit_iso (limits.cocones.functoriality_equivalence F (as_equivalence H)))) c /-- `functoriality F _ ⋙ postcompose (whisker_left F _)` simplifies to `functoriality F _`. -/ @[simp] theorem functoriality_comp_postcompose_inv_app_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {H : C ⥤ D} {H' : C ⥤ D} (α : H ≅ H') (X : limits.cone F) : limits.cone_morphism.hom (nat_trans.app (iso.inv (functoriality_comp_postcompose α)) X) = nat_trans.app (iso.inv α) (limits.cone.X X) := Eq.refl (nat_trans.app (iso.inv α) (limits.cone.X X)) /-- For `F : J ⥤ C`, given a cone `c : cone F`, and a natural isomorphism `α : H ≅ H'` for functors `H H' : C ⥤ D`, the postcomposition of the cone `H.map_cone` using the isomorphism `α` is isomorphic to the cone `H'.map_cone`. -/ def postcompose_whisker_left_map_cone {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {H : C ⥤ D} {H' : C ⥤ D} (α : H ≅ H') (c : limits.cone F) : obj (limits.cones.postcompose (whisker_left F (iso.hom α))) (map_cone H c) ≅ map_cone H' c := iso.app (functoriality_comp_postcompose α) c /-- `map_cone` commutes with `postcompose`. In particular, for `F : J ⥤ C`, given a cone `c : cone F`, a natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious ways of producing a cone over `G ⋙ H`, and they are both isomorphic. -/ @[simp] theorem map_cone_postcompose_inv_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) {α : F ⟶ G} {c : limits.cone F} : limits.cone_morphism.hom (iso.inv (map_cone_postcompose H)) = 𝟙 := Eq.refl 𝟙 /-- `map_cone` commutes with `postcompose_equivalence` -/ @[simp] theorem map_cone_postcompose_equivalence_functor_hom_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) {α : F ≅ G} {c : limits.cone F} : limits.cone_morphism.hom (iso.hom (map_cone_postcompose_equivalence_functor H)) = 𝟙 := Eq.refl 𝟙 /-- `functoriality F _ ⋙ precompose (whisker_left F _)` simplifies to `functoriality F _`. -/ @[simp] theorem functoriality_comp_precompose_inv_app_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {H : C ⥤ D} {H' : C ⥤ D} (α : H ≅ H') (X : limits.cocone F) : limits.cocone_morphism.hom (nat_trans.app (iso.inv (functoriality_comp_precompose α)) X) = nat_trans.app (iso.inv α) (limits.cocone.X X) := Eq.refl (nat_trans.app (iso.inv α) (limits.cocone.X X)) /-- For `F : J ⥤ C`, given a cocone `c : cocone F`, and a natural isomorphism `α : H ≅ H'` for functors `H H' : C ⥤ D`, the precomposition of the cocone `H.map_cocone` using the isomorphism `α` is isomorphic to the cocone `H'.map_cocone`. -/ def precompose_whisker_left_map_cocone {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {H : C ⥤ D} {H' : C ⥤ D} (α : H ≅ H') (c : limits.cocone F) : obj (limits.cocones.precompose (whisker_left F (iso.inv α))) (map_cocone H c) ≅ map_cocone H' c := iso.app (functoriality_comp_precompose α) c /-- `map_cocone` commutes with `precompose`. In particular, for `F : J ⥤ C`, given a cocone `c : cocone F`, a natural transformation `α : F ⟶ G` and a functor `H : C ⥤ D`, we have two obvious ways of producing a cocone over `G ⋙ H`, and they are both isomorphic. -/ @[simp] theorem map_cocone_precompose_hom_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) {α : F ⟶ G} {c : limits.cocone G} : limits.cocone_morphism.hom (iso.hom (map_cocone_precompose H)) = 𝟙 := Eq.refl 𝟙 /-- `map_cocone` commutes with `precompose_equivalence` -/ @[simp] theorem map_cocone_precompose_equivalence_functor_inv_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} {G : J ⥤ C} (H : C ⥤ D) {α : F ≅ G} {c : limits.cocone G} : limits.cocone_morphism.hom (iso.inv (map_cocone_precompose_equivalence_functor H)) = 𝟙 := Eq.refl 𝟙 /-- `map_cone` commutes with `whisker` -/ @[simp] theorem map_cone_whisker_inv_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) {K : Type v} [small_category K] {E : K ⥤ J} {c : limits.cone F} : limits.cone_morphism.hom (iso.inv (map_cone_whisker H)) = 𝟙 := Eq.refl 𝟙 /-- `map_cocone` commutes with `whisker` -/ @[simp] theorem map_cocone_whisker_inv_hom {J : Type v} [small_category J] {C : Type u} [category C] {D : Type u'} [category D] {F : J ⥤ C} (H : C ⥤ D) {K : Type v} [small_category K] {E : K ⥤ J} {c : limits.cocone F} : limits.cocone_morphism.hom (iso.inv (map_cocone_whisker H)) = 𝟙 := Eq.refl 𝟙 end functor end category_theory namespace category_theory.limits /-- Change a `cocone F` into a `cone F.op`. -/ @[simp] theorem cocone.op_X {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone F) : cone.X (cocone.op c) = opposite.op (cocone.X c) := Eq.refl (cone.X (cocone.op c)) /-- Change a `cone F` into a `cocone F.op`. -/ def cone.op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone F) : cocone (functor.op F) := cocone.mk (opposite.op (cone.X c)) (nat_trans.mk fun (j : Jᵒᵖ) => has_hom.hom.op (nat_trans.app (cone.π c) (opposite.unop j))) /-- Change a `cocone F.op` into a `cone F`. -/ def cocone.unop {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cocone (functor.op F)) : cone F := cone.mk (opposite.unop (cocone.X c)) (nat_trans.mk fun (j : J) => has_hom.hom.unop (nat_trans.app (cocone.ι c) (opposite.op j))) /-- Change a `cone F.op` into a `cocone F`. -/ @[simp] theorem cone.unop_X {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} (c : cone (functor.op F)) : cocone.X (cone.unop c) = opposite.unop (cone.X c) := Eq.refl (cocone.X (cone.unop c)) /-- The category of cocones on `F` is equivalent to the opposite category of the category of cones on the opposite of `F`. -/ @[simp] theorem cocone_equivalence_op_cone_op_unit_iso {J : Type v} [small_category J] {C : Type u} [category C] (F : J ⥤ C) : equivalence.unit_iso (cocone_equivalence_op_cone_op F) = nat_iso.of_components (fun (c : cocone F) => cocones.ext (iso.refl (cocone.X (functor.obj 𝟭 c))) (cocone_equivalence_op_cone_op._proof_7 F c)) (cocone_equivalence_op_cone_op._proof_8 F) := Eq.refl (equivalence.unit_iso (cocone_equivalence_op_cone_op F)) /-- Change a cocone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ -- Here and below we only automatically generate the `@[simp]` lemma for the `X` field, -- as we can write a simpler `rfl` lemma for the components of the natural transformation by hand. def cone_of_cocone_left_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ (Cᵒᵖ)} (c : cocone (functor.left_op F)) : cone F := cone.mk (opposite.op (cocone.X c)) (nat_trans.remove_left_op (cocone.ι c ≫ iso.hom (functor.const.op_obj_unop (opposite.op (cocone.X c))))) /-- Change a cone on `F : J ⥤ Cᵒᵖ` to a cocone on `F.left_op : Jᵒᵖ ⥤ C`. -/ def cocone_left_op_of_cone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ (Cᵒᵖ)} (c : cone F) : cocone (functor.left_op F) := cocone.mk (opposite.unop (cone.X c)) (nat_trans.left_op (cone.π c)) /-- Change a cone on `F.left_op : Jᵒᵖ ⥤ C` to a cocone on `F : J ⥤ Cᵒᵖ`. -/ /- When trying use `@[simps]` to generate the `ι_app` field of this definition, `@[simps]` tries to reduce the RHS using `expr.dsimp` and `expr.simp`, but for some reason the expression is not being simplified properly. -/ def cocone_of_cone_left_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ (Cᵒᵖ)} (c : cone (functor.left_op F)) : cocone F := cocone.mk (opposite.op (cone.X c)) (nat_trans.remove_left_op (iso.hom (functor.const.op_obj_unop (opposite.op (cone.X c))) ≫ cone.π c)) @[simp] theorem cocone_of_cone_left_op_ι_app {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ (Cᵒᵖ)} (c : cone (functor.left_op F)) (j : J) : nat_trans.app (cocone.ι (cocone_of_cone_left_op c)) j = has_hom.hom.op (nat_trans.app (cone.π c) (opposite.op j)) := sorry /-- Change a cocone on `F : J ⥤ Cᵒᵖ` to a cone on `F.left_op : Jᵒᵖ ⥤ C`. -/ def cone_left_op_of_cocone {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ (Cᵒᵖ)} (c : cocone F) : cone (functor.left_op F) := cone.mk (opposite.unop (cocone.X c)) (nat_trans.left_op (cocone.ι c)) end category_theory.limits namespace category_theory.functor /-- The opposite cocone of the image of a cone is the image of the opposite cocone. -/ def map_cone_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] (G : C ⥤ D) (t : limits.cone F) : limits.cone.op (map_cone G t) ≅ map_cocone (functor.op G) (limits.cone.op t) := limits.cocones.ext (iso.refl (limits.cocone.X (limits.cone.op (map_cone G t)))) sorry /-- The opposite cone of the image of a cocone is the image of the opposite cone. -/ def map_cocone_op {J : Type v} [small_category J] {C : Type u} [category C] {F : J ⥤ C} {D : Type u'} [category D] (G : C ⥤ D) {t : limits.cocone F} : limits.cocone.op (map_cocone G t) ≅ map_cone (functor.op G) (limits.cocone.op t) := limits.cones.ext (iso.refl (limits.cone.X (limits.cocone.op (map_cocone G t)))) sorry
87de8e4f4d5a9b6ef6388c73507107ac259e67ba
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/attribute.lean
675d5158158ac1a9a12c3ae26b17d845ce396421
[]
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
699
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.tactic import Mathlib.Lean3Lib.init.meta.rb_map import Mathlib.Lean3Lib.init.meta.has_reflect import Mathlib.Lean3Lib.init.meta.lean.parser namespace Mathlib /-- Get all of the declaration names that have the given attribute. Eg. ``get_instances `simp`` returns a list with the names of all of the lemmas in the environment tagged with the `@[simp]` attribute. -/ /-- Returns a hash of `get_instances`. You can use this to tell if your attribute instances have changed. -/
bca7d1a4368a091fe84a6655079d6332d3f1e33f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/submonoid/basic.lean
f32184deaf0587919c690a6cb2cb7d39e8b0b518
[]
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
16,621
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, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.set.lattice import Mathlib.PostPort universes u_3 l u_1 u_2 namespace Mathlib /-! # Submonoids: definition and `complete_lattice` structure This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mdense`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags submonoid, submonoids -/ /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type u_3) [monoid M] where carrier : set M one_mem' : 1 ∈ carrier mul_mem' : ∀ {a b : M}, a ∈ carrier → b ∈ carrier → a * b ∈ carrier /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type u_3) [add_monoid M] where carrier : set M zero_mem' : 0 ∈ carrier add_mem' : ∀ {a b : M}, a ∈ carrier → b ∈ carrier → a + b ∈ carrier namespace submonoid protected instance Mathlib.add_submonoid.set.has_coe {M : Type u_1} [add_monoid M] : has_coe (add_submonoid M) (set M) := has_coe.mk add_submonoid.carrier protected instance has_mem {M : Type u_1} [monoid M] : has_mem M (submonoid M) := has_mem.mk fun (m : M) (S : submonoid M) => m ∈ ↑S protected instance has_coe_to_sort {M : Type u_1} [monoid M] : has_coe_to_sort (submonoid M) := has_coe_to_sort.mk (Type u_1) fun (S : submonoid M) => Subtype fun (x : M) => x ∈ S @[simp] theorem mem_carrier {M : Type u_1} [monoid M] {s : submonoid M} {x : M} : x ∈ carrier s ↔ x ∈ s := iff.rfl @[simp] theorem mem_coe {M : Type u_1} [monoid M] {S : submonoid M} {m : M} : m ∈ ↑S ↔ m ∈ S := iff.rfl @[simp] theorem coe_coe {M : Type u_1} [monoid M] (s : submonoid M) : ↥↑s = ↥s := rfl protected theorem Mathlib.add_submonoid.exists {M : Type u_1} [add_monoid M] {s : add_submonoid M} {p : ↥s → Prop} : (∃ (x : ↥s), p x) ↔ ∃ (x : M), ∃ (H : x ∈ s), p { val := x, property := H } := set_coe.exists protected theorem forall {M : Type u_1} [monoid M] {s : submonoid M} {p : ↥s → Prop} : (∀ (x : ↥s), p x) ↔ ∀ (x : M) (H : x ∈ s), p { val := x, property := H } := set_coe.forall /-- Two submonoids are equal if the underlying subsets are equal. -/ theorem ext' {M : Type u_1} [monoid M] {S : submonoid M} {T : submonoid M} (h : ↑S = ↑T) : S = T := sorry /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {M : Type u_1} [monoid M] {S : submonoid M} {T : submonoid M} : S = T ↔ ↑S = ↑T := { mp := fun (h : S = T) => h ▸ rfl, mpr := fun (h : ↑S = ↑T) => ext' h } /-- Two submonoids are equal if they have the same elements. -/ theorem Mathlib.add_submonoid.ext {M : Type u_1} [add_monoid M] {S : add_submonoid M} {T : add_submonoid M} (h : ∀ (x : M), x ∈ S ↔ x ∈ T) : S = T := add_submonoid.ext' (set.ext h) /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ def copy {M : Type u_1} [monoid M] (S : submonoid M) (s : set M) (hs : s = ↑S) : submonoid M := mk s sorry sorry @[simp] theorem coe_copy {M : Type u_1} [monoid M] {S : submonoid M} {s : set M} (hs : s = ↑S) : ↑(copy S s hs) = s := rfl theorem copy_eq {M : Type u_1} [monoid M] {S : submonoid M} {s : set M} (hs : s = ↑S) : copy S s hs = S := ext' hs /-- A submonoid contains the monoid's 1. -/ theorem Mathlib.add_submonoid.zero_mem {M : Type u_1} [add_monoid M] (S : add_submonoid M) : 0 ∈ S := add_submonoid.zero_mem' S /-- A submonoid is closed under multiplication. -/ theorem mul_mem {M : Type u_1} [monoid M] (S : submonoid M) {x : M} {y : M} : x ∈ S → y ∈ S → x * y ∈ S := mul_mem' S theorem coe_injective {M : Type u_1} [monoid M] (S : submonoid M) : function.injective coe := subtype.val_injective @[simp] theorem coe_eq_coe {M : Type u_1} [monoid M] (S : submonoid M) (x : ↥S) (y : ↥S) : ↑x = ↑y ↔ x = y := set_coe.ext_iff protected instance has_le {M : Type u_1} [monoid M] : HasLessEq (submonoid M) := { LessEq := fun (S T : submonoid M) => ∀ {x : M}, x ∈ S → x ∈ T } theorem le_def {M : Type u_1} [monoid M] {S : submonoid M} {T : submonoid M} : S ≤ T ↔ ∀ {x : M}, x ∈ S → x ∈ T := iff.rfl @[simp] theorem Mathlib.add_submonoid.coe_subset_coe {M : Type u_1} [add_monoid M] {S : add_submonoid M} {T : add_submonoid M} : ↑S ⊆ ↑T ↔ S ≤ T := iff.rfl protected instance Mathlib.add_submonoid.partial_order {M : Type u_1} [add_monoid M] : partial_order (add_submonoid M) := partial_order.mk (fun (S T : add_submonoid M) => ∀ {x : M}, x ∈ S → x ∈ T) partial_order.lt sorry sorry sorry @[simp] theorem coe_ssubset_coe {M : Type u_1} [monoid M] {S : submonoid M} {T : submonoid M} : ↑S ⊂ ↑T ↔ S < T := iff.rfl /-- The submonoid `M` of the monoid `M`. -/ protected instance has_top {M : Type u_1} [monoid M] : has_top (submonoid M) := has_top.mk (mk set.univ sorry sorry) /-- The trivial submonoid `{1}` of an monoid `M`. -/ protected instance Mathlib.add_submonoid.has_bot {M : Type u_1} [add_monoid M] : has_bot (add_submonoid M) := has_bot.mk (add_submonoid.mk (singleton 0) sorry sorry) protected instance Mathlib.add_submonoid.inhabited {M : Type u_1} [add_monoid M] : Inhabited (add_submonoid M) := { default := ⊥ } @[simp] theorem mem_bot {M : Type u_1} [monoid M] {x : M} : x ∈ ⊥ ↔ x = 1 := set.mem_singleton_iff @[simp] theorem mem_top {M : Type u_1} [monoid M] (x : M) : x ∈ ⊤ := set.mem_univ x @[simp] theorem Mathlib.add_submonoid.coe_top {M : Type u_1} [add_monoid M] : ↑⊤ = set.univ := rfl @[simp] theorem coe_bot {M : Type u_1} [monoid M] : ↑⊥ = singleton 1 := rfl /-- The inf of two submonoids is their intersection. -/ protected instance has_inf {M : Type u_1} [monoid M] : has_inf (submonoid M) := has_inf.mk fun (S₁ S₂ : submonoid M) => mk (↑S₁ ∩ ↑S₂) sorry sorry @[simp] theorem coe_inf {M : Type u_1} [monoid M] (p : submonoid M) (p' : submonoid M) : ↑(p ⊓ p') = ↑p ∩ ↑p' := rfl @[simp] theorem mem_inf {M : Type u_1} [monoid M] {p : submonoid M} {p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl protected instance has_Inf {M : Type u_1} [monoid M] : has_Inf (submonoid M) := has_Inf.mk fun (s : set (submonoid M)) => mk (set.Inter fun (t : submonoid M) => set.Inter fun (H : t ∈ s) => ↑t) sorry sorry @[simp] theorem coe_Inf {M : Type u_1} [monoid M] (S : set (submonoid M)) : ↑(Inf S) = set.Inter fun (s : submonoid M) => set.Inter fun (H : s ∈ S) => ↑s := rfl theorem Mathlib.add_submonoid.mem_Inf {M : Type u_1} [add_monoid M] {S : set (add_submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ (p : add_submonoid M), p ∈ S → x ∈ p := set.mem_bInter_iff theorem mem_infi {M : Type u_1} [monoid M] {ι : Sort u_2} {S : ι → submonoid M} {x : M} : (x ∈ infi fun (i : ι) => S i) ↔ ∀ (i : ι), x ∈ S i := sorry @[simp] theorem Mathlib.add_submonoid.coe_infi {M : Type u_1} [add_monoid M] {ι : Sort u_2} {S : ι → add_submonoid M} : ↑(infi fun (i : ι) => S i) = set.Inter fun (i : ι) => ↑(S i) := sorry /-- Submonoids of a monoid form a complete lattice. -/ protected instance complete_lattice {M : Type u_1} [monoid M] : complete_lattice (submonoid M) := complete_lattice.mk complete_lattice.sup LessEq Less sorry sorry sorry sorry sorry sorry has_inf.inf sorry sorry sorry ⊤ sorry ⊥ sorry complete_lattice.Sup Inf sorry sorry sorry sorry theorem subsingleton_iff {M : Type u_1} [monoid M] : subsingleton M ↔ subsingleton (submonoid M) := sorry theorem nontrivial_iff {M : Type u_1} [monoid M] : nontrivial M ↔ nontrivial (submonoid M) := iff.mp not_iff_not (iff.trans (iff.trans not_nontrivial_iff_subsingleton subsingleton_iff) (iff.symm not_nontrivial_iff_subsingleton)) protected instance subsingleton {M : Type u_1} [monoid M] [subsingleton M] : subsingleton (submonoid M) := iff.mp subsingleton_iff _inst_3 protected instance nontrivial {M : Type u_1} [monoid M] [nontrivial M] : nontrivial (submonoid M) := iff.mp nontrivial_iff _inst_3 /-- The `submonoid` generated by a set. -/ def Mathlib.add_submonoid.closure {M : Type u_1} [add_monoid M] (s : set M) : add_submonoid M := Inf (set_of fun (S : add_submonoid M) => s ⊆ ↑S) theorem mem_closure {M : Type u_1} [monoid M] {s : set M} {x : M} : x ∈ closure s ↔ ∀ (S : submonoid M), s ⊆ ↑S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp] theorem subset_closure {M : Type u_1} [monoid M] {s : set M} : s ⊆ ↑(closure s) := fun (x : M) (hx : x ∈ s) => iff.mpr mem_closure fun (S : submonoid M) (hS : s ⊆ ↑S) => hS hx /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp] theorem closure_le {M : Type u_1} [monoid M] {s : set M} {S : submonoid M} : closure s ≤ S ↔ s ⊆ ↑S := { mp := set.subset.trans subset_closure, mpr := fun (h : s ⊆ ↑S) => Inf_le h } /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ theorem Mathlib.add_submonoid.closure_mono {M : Type u_1} [add_monoid M] {s : set M} {t : set M} (h : s ⊆ t) : add_submonoid.closure s ≤ add_submonoid.closure t := iff.mpr add_submonoid.closure_le (set.subset.trans h add_submonoid.subset_closure) theorem Mathlib.add_submonoid.closure_eq_of_le {M : Type u_1} [add_monoid M] {s : set M} {S : add_submonoid M} (h₁ : s ⊆ ↑S) (h₂ : S ≤ add_submonoid.closure s) : add_submonoid.closure s = S := le_antisymm (iff.mpr add_submonoid.closure_le h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ theorem closure_induction {M : Type u_1} [monoid M] {s : set M} {p : M → Prop} {x : M} (h : x ∈ closure s) (Hs : ∀ (x : M), x ∈ s → p x) (H1 : p 1) (Hmul : ∀ (x y : M), p x → p y → p (x * y)) : p x := iff.mpr closure_le Hs x h /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ theorem dense_induction {M : Type u_1} [monoid M] {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ (x : M), x ∈ s → p x) (H1 : p 1) (Hmul : ∀ (x y : M), p x → p y → p (x * y)) : p x := sorry /-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/ /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi (M : Type u_1) [monoid M] : galois_insertion closure coe := galois_insertion.mk (fun (s : set M) (_x : ↑(closure s) ≤ s) => closure s) sorry sorry sorry /-- Closure of a submonoid `S` equals `S`. -/ @[simp] theorem closure_eq {M : Type u_1} [monoid M] (S : submonoid M) : closure ↑S = S := galois_insertion.l_u_eq (submonoid.gi M) S @[simp] theorem closure_empty {M : Type u_1} [monoid M] : closure ∅ = ⊥ := galois_connection.l_bot (galois_insertion.gc (submonoid.gi M)) @[simp] theorem closure_univ {M : Type u_1} [monoid M] : closure set.univ = ⊤ := coe_top ▸ closure_eq ⊤ theorem Mathlib.add_submonoid.closure_union {M : Type u_1} [add_monoid M] (s : set M) (t : set M) : add_submonoid.closure (s ∪ t) = add_submonoid.closure s ⊔ add_submonoid.closure t := galois_connection.l_sup (galois_insertion.gc (add_submonoid.gi M)) theorem closure_Union {M : Type u_1} [monoid M] {ι : Sort u_2} (s : ι → set M) : closure (set.Union fun (i : ι) => s i) = supr fun (i : ι) => closure (s i) := galois_connection.l_supr (galois_insertion.gc (submonoid.gi M)) end submonoid /-- The submonoid consisting of the units of a monoid -/ def is_unit.submonoid (M : Type u_1) [monoid M] : submonoid M := submonoid.mk (set_of is_unit) sorry sorry theorem is_unit.mem_submonoid_iff {M : Type u_1} [monoid M] (a : M) : a ∈ is_unit.submonoid M ↔ is_unit a := id (eq.mpr (id (Eq._oldrec (Eq.refl (a ∈ set_of is_unit ↔ is_unit a)) set.mem_set_of_eq)) (iff.refl (is_unit a))) namespace monoid_hom /-- The submonoid of elements `x : M` such that `f x = g x` -/ def eq_mlocus {M : Type u_1} [monoid M] {N : Type u_3} [monoid N] (f : M →* N) (g : M →* N) : submonoid M := submonoid.mk (set_of fun (x : M) => coe_fn f x = coe_fn g x) sorry sorry /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ theorem Mathlib.add_monoid_hom.eq_on_mclosure {M : Type u_1} [add_monoid M] {N : Type u_3} [add_monoid N] {f : M →+ N} {g : M →+ N} {s : set M} (h : set.eq_on (⇑f) (⇑g) s) : set.eq_on ⇑f ⇑g ↑(add_submonoid.closure s) := (fun (this : add_submonoid.closure s ≤ add_monoid_hom.eq_mlocus f g) => this) (iff.mpr add_submonoid.closure_le h) theorem Mathlib.add_monoid_hom.eq_of_eq_on_mtop {M : Type u_1} [add_monoid M] {N : Type u_3} [add_monoid N] {f : M →+ N} {g : M →+ N} (h : set.eq_on ⇑f ⇑g ↑⊤) : f = g := add_monoid_hom.ext fun (x : M) => h trivial theorem eq_of_eq_on_mdense {M : Type u_1} [monoid M] {N : Type u_3} [monoid N] {s : set M} (hs : submonoid.closure s = ⊤) {f : M →* N} {g : M →* N} (h : set.eq_on (⇑f) (⇑g) s) : f = g := eq_of_eq_on_mtop (hs ▸ eq_on_mclosure h) /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ def of_mdense {M : Type u_1} [monoid M] {s : set M} {N : Type u_3} [monoid N] (f : M → N) (hs : submonoid.closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ (x y : M), y ∈ s → f (x * y) = f x * f y) : M →* N := mk f h1 sorry /-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ @[simp] theorem coe_of_mdense {M : Type u_1} [monoid M] {s : set M} {N : Type u_3} [monoid N] (f : M → N) (hs : submonoid.closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ (x y : M), y ∈ s → f (x * y) = f x * f y) : ⇑(of_mdense f hs h1 hmul) = f := rfl
c6ae883f78476b01c9277c1dc61b2d6481e3720b
bdb33f8b7ea65f7705fc342a178508e2722eb851
/group_theory/subgroup.lean
d0ff2c50502c6bb3bbe5ada9f11ebc30a672a3a8
[ "Apache-2.0" ]
permissive
rwbarton/mathlib
939ae09bf8d6eb1331fc2f7e067d39567e10e33d
c13c5ea701bb1eec057e0a242d9f480a079105e9
refs/heads/master
1,584,015,335,862
1,524,142,167,000
1,524,142,167,000
130,614,171
0
0
Apache-2.0
1,548,902,667,000
1,524,437,371,000
Lean
UTF-8
Lean
false
false
8,519
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, Mitchell Rowett, Scott Morrison -/ import group_theory.submonoid open set function variables {α : Type*} {β : Type*} {s : set α} {a a₁ a₂ b c: α} section group variable [group α] lemma injective_mul {a : α} : injective ((*) a) := assume a₁ a₂ h, have a⁻¹ * a * a₁ = a⁻¹ * a * a₂, by rw [mul_assoc, mul_assoc, h], by rwa [inv_mul_self, one_mul, one_mul] at this /-- `s` is a subgroup: a set containing 1 and closed under multiplication and inverse. -/ class is_subgroup [group α] (s : set α) extends is_submonoid s : Prop := (inv_mem {a} : a ∈ s → a⁻¹ ∈ s) instance subtype.group {s : set α} [is_subgroup s] : group s := { inv := λa, ⟨(a.1)⁻¹, is_subgroup.inv_mem a.2⟩, mul_left_inv := assume ⟨a, _⟩, subtype.eq $ mul_left_inv _, .. subtype.monoid } theorem is_subgroup.of_div [group α] (s : set α) (one_mem : (1:α) ∈ s) (div_mem : ∀{a b:α}, a ∈ s → b ∈ s → a * b⁻¹ ∈ s): is_subgroup s := have inv_mem : ∀a, a ∈ s → a⁻¹ ∈ s, from assume a ha, have 1 * a⁻¹ ∈ s, from div_mem one_mem ha, by simpa, { inv_mem := inv_mem, mul_mem := assume a b ha hb, have a * b⁻¹⁻¹ ∈ s, from div_mem ha (inv_mem b hb), by simpa, one_mem := one_mem } def gpowers (x : α) : set α := {y | ∃i:ℤ, x^i = y} instance gpowers.is_subgroup (x : α) : is_subgroup (gpowers x) := { one_mem := ⟨(0:ℤ), by simp⟩, mul_mem := assume x₁ x₂ ⟨i₁, h₁⟩ ⟨i₂, h₂⟩, ⟨i₁ + i₂, by simp [gpow_add, *]⟩, inv_mem := assume x₀ ⟨i, h⟩, ⟨-i, by simp [h.symm]⟩ } lemma is_subgroup.gpow_mem {a : α} {s : set α} [is_subgroup s] (h : a ∈ s) : ∀{i:ℤ}, a ^ i ∈ s | (n : ℕ) := is_submonoid.pow_mem h | -[1+ n] := is_subgroup.inv_mem (is_submonoid.pow_mem h) lemma mem_gpowers {a : α} : a ∈ gpowers a := ⟨1, by simp⟩ end group namespace is_subgroup open is_submonoid variable (s) variables [group α] [is_subgroup s] lemma inv_mem_iff : a⁻¹ ∈ s ↔ a ∈ s := iff.intro (assume h, have a⁻¹⁻¹ ∈ s, from inv_mem h, by simpa) inv_mem lemma mul_mem_cancel_left (h : a ∈ s) : b * a ∈ s ↔ b ∈ s := iff.intro (assume hba, have (b * a) * a⁻¹ ∈ s, from mul_mem hba (inv_mem h), by simpa) (assume hb, mul_mem hb h) lemma mul_mem_cancel_right (h : a ∈ s) : a * b ∈ s ↔ b ∈ s := iff.intro (assume hab, have a⁻¹ * (a * b) ∈ s, from mul_mem (inv_mem h) hab, by simpa) (mul_mem h) end is_subgroup namespace group open is_submonoid is_subgroup variable [group α] inductive in_closure (s : set α) : α → Prop | basic {a : α} : a ∈ s → in_closure a | one : in_closure 1 | inv {a : α} : in_closure a → in_closure a⁻¹ | mul {a b : α} : in_closure a → in_closure b → in_closure (a * b) /-- `group.closure s` is the subgroup closed over `s`, i.e. the smallest subgroup containg s. -/ def closure (s : set α) : set α := {a | in_closure s a } lemma mem_closure {a : α} : a ∈ s → a ∈ closure s := in_closure.basic instance closure.is_subgroup (s : set α) : is_subgroup (closure s) := { one_mem := in_closure.one s, mul_mem := assume a b, in_closure.mul, inv_mem := assume a, in_closure.inv } theorem subset_closure {s : set α} : s ⊆ closure s := assume a, in_closure.basic theorem closure_subset {s t : set α} [is_subgroup t] (h : s ⊆ t) : closure s ⊆ t := assume a ha, by induction ha; simp [h _, *, one_mem, mul_mem, inv_mem_iff] theorem gpowers_eq_closure {a : α} : gpowers a = closure {a} := subset.antisymm (assume x h, match x, h with _, ⟨i, rfl⟩ := gpow_mem (mem_closure $ by simp) end) (closure_subset $ by simp [mem_gpowers]) end group class normal_subgroup [group α] (s : set α) extends is_subgroup s : Prop := (normal : ∀ n ∈ s, ∀ g : α, g * n * g⁻¹ ∈ s) namespace is_subgroup variable [group α] -- Normal subgroup properties lemma mem_norm_comm {a b : α} {s : set α} [normal_subgroup s] (hab : a * b ∈ s) : b * a ∈ s := have h : a⁻¹ * (a * b) * a⁻¹⁻¹ ∈ s, from normal_subgroup.normal (a * b) hab a⁻¹, by simp at h; exact h lemma mem_norm_comm_iff {a b : α} {s : set α} [normal_subgroup s] : a * b ∈ s ↔ b * a ∈ s := iff.intro mem_norm_comm mem_norm_comm /-- The trivial subgroup -/ def trivial (α : Type*) [group α] : set α := {1} @[simp] lemma mem_trivial [group α] {g : α} : g ∈ trivial α ↔ g = 1 := by simp [trivial] instance trivial_normal : normal_subgroup (trivial α) := by refine {..}; simp [trivial] {contextual := tt} lemma trivial_eq_closure : trivial α = group.closure ∅ := subset.antisymm (by simp [set.subset_def, is_submonoid.one_mem]) (group.closure_subset $ by simp) instance univ_subgroup : normal_subgroup (@univ α) := by refine {..}; simp def center (α : Type*) [group α] : set α := {z | ∀ g, g * z = z * g} lemma mem_center {a : α} : a ∈ center α ↔ (∀g, g * a = a * g) := iff.refl _ instance center_normal : normal_subgroup (center α) := { one_mem := by simp [center], mul_mem := assume a b ha hb g, by rw [←mul_assoc, mem_center.2 ha g, mul_assoc, mem_center.2 hb g, ←mul_assoc], inv_mem := assume a ha g, calc g * a⁻¹ = a⁻¹ * (g * a) * a⁻¹ : by simp [ha g] ... = a⁻¹ * g : by rw [←mul_assoc, mul_assoc]; simp, normal := assume n ha g h, calc h * (g * n * g⁻¹) = h * n : by simp [ha g, mul_assoc] ... = g * g⁻¹ * n * h : by rw ha h; simp ... = g * n * g⁻¹ * h : by rw [mul_assoc g, ha g⁻¹, ←mul_assoc] } end is_subgroup -- Homomorphism subgroups namespace is_group_hom open is_submonoid is_subgroup variables [group α] [group β] def ker (f : α → β) [is_group_hom f] : set α := preimage f (trivial β) lemma mem_ker (f : α → β) [is_group_hom f] {x : α} : x ∈ ker f ↔ f x = 1 := mem_trivial lemma one_ker_inv (f : α → β) [is_group_hom f] {a b : α} (h : f (a * b⁻¹) = 1) : f a = f b := begin rw [mul f, inv f] at h, rw [←inv_inv (f b), eq_inv_of_mul_eq_one h] end lemma inv_ker_one (f : α → β) [is_group_hom f] {a b : α} (h : f a = f b) : f (a * b⁻¹) = 1 := have f a * (f b)⁻¹ = 1, by rw [h, mul_right_inv], by rwa [←inv f, ←mul f] at this lemma one_iff_ker_inv (f : α → β) [is_group_hom f] (a b : α) : f a = f b ↔ f (a * b⁻¹) = 1 := ⟨inv_ker_one f, one_ker_inv f⟩ lemma inv_iff_ker (f : α → β) [w : is_group_hom f] (a b : α) : f a = f b ↔ a * b⁻¹ ∈ ker f := by rw [mem_ker]; exact one_iff_ker_inv _ _ _ instance image_subgroup (f : α → β) [is_group_hom f] (s : set α) [is_subgroup s] : is_subgroup (f '' s) := { mul_mem := assume a₁ a₂ ⟨b₁, hb₁, eq₁⟩ ⟨b₂, hb₂, eq₂⟩, ⟨b₁ * b₂, mul_mem hb₁ hb₂, by simp [eq₁, eq₂, mul f]⟩, one_mem := ⟨1, one_mem s, one f⟩, inv_mem := assume a ⟨b, hb, eq⟩, ⟨b⁻¹, inv_mem hb, by rw inv f; simp *⟩ } local attribute [simp] one_mem inv_mem mul_mem normal_subgroup.normal instance preimage (f : α → β) [is_group_hom f] (s : set β) [is_subgroup s] : is_subgroup (f ⁻¹' s) := by refine {..}; simp [mul f, one f, inv f, @inv_mem β _ _ s] {contextual:=tt} instance preimage_normal (f : α → β) [is_group_hom f] (s : set β) [normal_subgroup s] : normal_subgroup (f ⁻¹' s) := ⟨by simp [mul f, inv f] {contextual:=tt}⟩ instance normal_subgroup_ker (f : α → β) [is_group_hom f] : normal_subgroup (ker f) := is_group_hom.preimage_normal f (trivial β) lemma inj_of_trivial_ker (f : α → β) [is_group_hom f] (h : ker f = trivial α) : function.injective f := begin intros a₁ a₂ hfa, simp [set_eq_def, ker, is_subgroup.trivial] at h, have ha : a₁ * a₂⁻¹ = 1, by rw ←h; exact inv_ker_one f hfa, rw [eq_inv_of_mul_eq_one ha, inv_inv a₂] end lemma trivial_ker_of_inj (f : α → β) [is_group_hom f] (h : function.injective f) : ker f = trivial α := set.ext $ assume x, iff.intro (assume hx, suffices f x = f 1, by simpa using h this, by simp [one f]; rwa [mem_ker] at hx) (by simp [mem_ker, is_group_hom.one f] {contextual := tt}) lemma inj_iff_trivial_ker (f : α → β) [is_group_hom f] : function.injective f ↔ ker f = trivial α := ⟨trivial_ker_of_inj f, inj_of_trivial_ker f⟩ end is_group_hom
b893f9626b23b7157e3ade3b8f1a536c713f6045
96338d06deb5f54f351493a71d6ecf6c546089a2
/priv/Lean/Completion.lean
0baabd7c15aa23994edc297779248fae07259cac
[]
no_license
silky/exe
5f9e4eea772d74852a1a2fac57d8d20588282d2b
e81690d6e16f2a83c105cce446011af6ae905b81
refs/heads/master
1,609,385,766,412
1,472,164,223,000
1,472,164,223,000
66,610,224
1
0
null
1,472,178,919,000
1,472,178,919,000
null
UTF-8
Lean
false
false
1,089
lean
/- Completion.lean -/ import Setoid import Cat import Functor namespace EXE namespace Completion record Ob (C : CatType) : Type := (atCat : CatType) (atFun : atCat ⟶ C) record HomType {C : CatType} (O1 O2 : Ob C) : Type := (onCat : Ob.atCat O2 ⟶ Ob.atCat O1) (onFun : (Ob.atFun O1 ⊗ onCat) ⟹ Ob.atFun O2) definition HomPreEqu {C : CatType} (O1 O2 : Ob C) : EquType (HomType O1 O2) := λ (m1 m2 : HomType O1 O2), ∃ (phi : HomType.onCat m1 ⟹ HomType.onCat m2), ((HomType.onFun m2) ⊙(Ob.atCat O2 ⟶ C)⊙ (Ob.atFun O1 ⊗/ phi)) ≡((Ob.atFun O1 ⊗ HomType.onCat m1) ⟹ Ob.atFun O2)≡ (HomType.onFun m1) definition HomSet (C : CatType) : Cat.HomType (Ob C) := λ (O1 O2 : Ob C), Setoid.Closure (HomPreEqu O1 O2) end Completion definition CompletionCat : CatType → CatType := λ (C : CatType), Cat.MkOb (Completion.Ob C) (Completion.HomSet C) (sorry) (sorry) (sorry) (sorry) (sorry) end EXE
5f3462e7f8ce2431280d3b8eb2c1797e4ed37cc5
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world06/level08.lean
d26974eaf71ea8474c39ad5a02d6d8a6d0ebe25a
[]
no_license
abdelq/natural-number-game
a1b5b8f1d52625a7addcefc97c966d3f06a48263
bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2
refs/heads/master
1,668,606,478,691
1,594,175,058,000
1,594,175,058,000
278,673,209
0
1
null
null
null
null
UTF-8
Lean
false
false
164
lean
lemma contrapositive (P Q : Prop) : (P → Q) → (¬ Q → ¬ P) := begin repeat {rw not_iff_imp_false}, intro f, intro q, intro p, apply q, apply f, exact p, end
3b87c40de9d7c65f68e6adbd695305d2458a50d7
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/category/Module/kernels.lean
558c9668b0878e73e18ac8caba42d8aa99f02ce2
[ "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
4,175
lean
/- Copyright (c) 2020 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import algebra.category.Module.epi_mono import category_theory.limits.concrete_category /-! # The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense. -/ open category_theory open category_theory.limits universes u v namespace Module variables {R : Type u} [ring R] section variables {M N : Module.{v} R} (f : M ⟶ N) /-- The kernel cone induced by the concrete kernel. -/ def kernel_cone : kernel_fork f := kernel_fork.of_ι (as_hom f.ker.subtype) $ by tidy /-- The kernel of a linear map is a kernel in the categorical sense. -/ def kernel_is_limit : is_limit (kernel_cone f) := fork.is_limit.mk _ (λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $ by { rw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition, has_zero_morphisms.comp_zero (fork.ι s) N], refl })) (λ s, linear_map.subtype_comp_cod_restrict _ _ _) (λ s m h, linear_map.ext $ λ x, subtype.ext_iff_val.2 (by simpa [←h])) /-- The cokernel cocone induced by the projection onto the quotient. -/ def cokernel_cocone : cokernel_cofork f := cokernel_cofork.of_π (as_hom f.range.mkq) $ linear_map.range_mkq_comp _ /-- The projection onto the quotient is a cokernel in the categorical sense. -/ def cokernel_is_colimit : is_colimit (cokernel_cocone f) := cofork.is_colimit.mk _ (λ s, f.range.liftq (cofork.π s) $ linear_map.range_le_ker_iff.2 $ cokernel_cofork.condition s) (λ s, f.range.liftq_mkq (cofork.π s) _) (λ s m h, begin haveI : epi (as_hom f.range.mkq) := (epi_iff_range_eq_top _).mpr (submodule.range_mkq _), apply (cancel_epi (as_hom f.range.mkq)).1, convert h, exact submodule.liftq_mkq _ _ _ end) end /-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/ lemma has_kernels_Module : has_kernels (Module R) := ⟨λ X Y f, has_limit.mk ⟨_, kernel_is_limit f⟩⟩ /-- The category or R-modules has cokernels, given by the projection onto the quotient. -/ lemma has_cokernels_Module : has_cokernels (Module R) := ⟨λ X Y f, has_colimit.mk ⟨_, cokernel_is_colimit f⟩⟩ open_locale Module local attribute [instance] has_kernels_Module local attribute [instance] has_cokernels_Module variables {G H : Module.{v} R} (f : G ⟶ H) /-- The categorical kernel of a morphism in `Module` agrees with the usual module-theoretical kernel. -/ noncomputable def kernel_iso_ker {G H : Module.{v} R} (f : G ⟶ H) : kernel f ≅ Module.of R (f.ker) := limit.iso_limit_cone ⟨_, kernel_is_limit f⟩ -- We now show this isomorphism commutes with the inclusion of the kernel into the source. @[simp, elementwise] lemma kernel_iso_ker_inv_kernel_ι : (kernel_iso_ker f).inv ≫ kernel.ι f = f.ker.subtype := limit.iso_limit_cone_inv_π _ _ @[simp, elementwise] lemma kernel_iso_ker_hom_ker_subtype : (kernel_iso_ker f).hom ≫ f.ker.subtype = kernel.ι f := is_limit.cone_point_unique_up_to_iso_inv_comp _ (limit.is_limit _) walking_parallel_pair.zero /-- The categorical cokernel of a morphism in `Module` agrees with the usual module-theoretical quotient. -/ noncomputable def cokernel_iso_range_quotient {G H : Module.{v} R} (f : G ⟶ H) : cokernel f ≅ Module.of R (H ⧸ f.range) := colimit.iso_colimit_cocone ⟨_, cokernel_is_colimit f⟩ -- We now show this isomorphism commutes with the projection of target to the cokernel. @[simp, elementwise] lemma cokernel_π_cokernel_iso_range_quotient_hom : cokernel.π f ≫ (cokernel_iso_range_quotient f).hom = f.range.mkq := by { convert colimit.iso_colimit_cocone_ι_hom _ _; refl, } @[simp, elementwise] lemma range_mkq_cokernel_iso_range_quotient_inv : ↿f.range.mkq ≫ (cokernel_iso_range_quotient f).inv = cokernel.π f := by { convert colimit.iso_colimit_cocone_ι_inv ⟨_, cokernel_is_colimit f⟩ _; refl, } lemma cokernel_π_ext {M N : Module.{u} R} (f : M ⟶ N) {x y : N} (m : M) (w : x = y + f m) : cokernel.π f x = cokernel.π f y := by { subst w, simp, } end Module
ff26abd5624b0324e495c6f9f80cc6bc94c0e39b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Compiler/ExportAttr.lean
aa14b0b48730fef470560a24ae08904216702da9
[ "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
1,331
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.Attributes namespace Lean private def isValidCppId (id : String) : Bool := let first := id.get 0; first.isAlpha && (id.toSubstring.drop 1).all (fun c => c.isAlpha || c.isDigit || c == '_') private def isValidCppName : Name → Bool | .str .anonymous s => isValidCppId s | .str p s => isValidCppId s && isValidCppName p | _ => false builtin_initialize exportAttr : ParametricAttribute Name ← registerParametricAttribute { name := `export, descr := "name to be used by code generators", getParam := fun _ stx => do let exportName ← Attribute.Builtin.getId stx unless isValidCppName exportName do throwError "invalid 'export' function name, is not a valid C++ identifier" return exportName } @[export lean_get_export_name_for] def getExportNameFor? (env : Environment) (n : Name) : Option Name := exportAttr.getParam? env n def isExport (env : Environment) (n : Name) : Bool := -- The main function morally is an exported function as well. In particular, -- it should not participate in borrow inference. (getExportNameFor? env n).isSome || n == `main end Lean
a482d8daab4159e14da6d90a6aa0a3de428f17ab
9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e
/src/exercises/misc_exercices_1.lean
bbeb738a836173ef068f7b716feee5c7b92b6744
[]
no_license
agusakov/lean_lib
c0e9cc29fc7d2518004e224376adeb5e69b5cc1a
f88d162da2f990b87c4d34f5f46bbca2bbc5948e
refs/heads/master
1,642,141,461,087
1,557,395,798,000
1,557,395,798,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,736
lean
import tactic.interactive tactic.ring tactic.fin_cases /- Exercise 1 Show that for every natural number n, there exists m with m > n Useful ingredients: nat.lt_succ_self; the tactics intro, use, apply -/ lemma exists_greater_a : ∀ (n : ℕ), ∃ (m : ℕ), m > n := begin intro n, use n + 1, apply nat.lt_succ_self, end lemma exists_greater_b (n : ℕ) : ∃ m, m > n := exists.intro (n + 1) n.lt_succ_self /- Exercise 2 Show that if we append a list to itself, then the length doubles. Useful ingredients: list.length_append, two_mul -/ lemma double_length_a {α : Type} (l : list α) : (l ++ l).length = 2 * l.length := begin rw[list.length_append l l],ring end lemma double_length_b {α : Type} (l : list α) : (l ++ l).length = 2 * l.length := (list.length_append l l).trans (two_mul l.length).symm /- Exercise 3 Show that 2 * (0 + 1 + ... + n) = n * (n + 1) Useful ingredients: finset.sum_range, finset.sum_range_succ; the tactics induction, rw and ring -/ lemma range_sum_a (n : ℕ) : 2 * ((finset.range (n + 1)).sum id) = n * (n + 1) := begin induction n with n ih, {refl}, {have e : nat.succ n = n + 1 := rfl, rw[finset.sum_range_succ id (n + 1),mul_add,ih,id,e], ring, } end lemma range_sum_b : ∀ n : ℕ, 2 * ((finset.range (n + 1)).sum id) = n * (n + 1) | 0 := rfl | (n + 1) := begin rw[finset.sum_range_succ id (n + 1),mul_add,range_sum_a n,id], ring, end /- Exercise 4 Show that every natural number can be written in the form 2 * m or 2 * m + 1. This one seems harder than it should be. Useful ingredients: the operations n / 2 and n % 2, the theorems nat.mod_add_div and nat.mod_lt, the fin_cases tactic. For a different approach: the functions nat.bodd and nat.div2 and the theorem nat.bodd_add_div2 -/ lemma even_odd_a : ∀ (n : ℕ), (∃ m, n = 2 * m) ∨ (∃ m, n = 2 * m + 1) | 0 := or.inl ⟨0,rfl⟩ | 1 := or.inr ⟨0,rfl⟩ | (n + 2) := begin rcases even_odd_a n with ⟨m,e⟩ | ⟨m,e⟩; rw[e], {left,use m + 1,ring}, {right,use m + 1,ring}, end lemma even_odd_b (n : ℕ) : (∃ m, n = 2 * m) ∨ (∃ m, n = 2 * m + 1) := begin let r := n % 2, let m := n / 2, have h : n = 2 * m + r := (nat.mod_add_div n 2).symm.trans (add_comm _ _), have r_lt_2 : r < 2 := nat.mod_lt n dec_trivial, let r0 : fin 2 := ⟨r,r_lt_2⟩, fin_cases r0, {left, use m, let e : r = 0 := congr_arg fin.val h_1, rw[e,add_zero] at h, exact h, },{ right, use m, let e : r = 1 := congr_arg fin.val h_1, rw[e] at h, exact h, }, end lemma even_odd_c_aux (n m : ℕ) (b : bool) (e : (cond b 1 0) + 2 * m = n) : (∃ m, n = 2 * m) ∨ (∃ m, n = 2 * m + 1) := begin cases b, {left ,exact ⟨m,(e.symm.trans (zero_add _))⟩,}, {right,exact ⟨m,e.symm.trans (add_comm _ _)⟩,}, end lemma even_odd_c (n : ℕ) : (∃ m, n = 2 * m) ∨ (∃ m, n = 2 * m + 1) := even_odd_c_aux n n.div2 (nat.bodd n) (nat.bodd_add_div2 n) /- Exercise 5 Given propositions p and q, show that p → q is equivalent to p → (p → q) Useful ingredients: The tactics split, intros and exact. Alternatively, you can use the tauto tactic, which will do all the work for you. -/ lemma ppq_a (p q : Prop) : (p → q) ↔ (p → p → q) := begin split, {intros hpq hp _,exact hpq hp,}, {intros hppq hp,exact hppq hp hp,} end lemma ppq_b (p q : Prop) : (p → q) ↔ (p → p → q) := ⟨λ hpq hp _,hpq hp,λ hppq hp,hppq hp hp⟩ lemma ppq_c (p q : Prop) : (p → q) ↔ (p → p → q) := by tauto /- Exercise 6 If G is a group where a^2 = 1 for all a, then G is commutative. Proof: for any a and b we have a^2 = 1 and b^2 = 1 and (ab)^2 = 1. Write the last of these as abab = 1, multiply on the left by a and on the right by b to get aababb = ab. Cancel aa = 1 and bb = 1 to get ba = ab. Useful ingredients: pow_two, calc, rw, mul_assoc, one_mul, mul_one -/ lemma elem_ab_a {G : Type*} [group G] (h : ∀ a : G, a ^ 2 = 1) : ∀ a b : G, a * b = b * a := begin intros a b, let ea : a * a = 1 := (pow_two a).symm.trans (h a), let eb : b * b = 1 := (pow_two b).symm.trans (h b), let eab : (a * b) * (a * b) = 1 := (pow_two (a * b)).symm.trans (h (a * b)), exact calc a * b = (a * 1) * b : by rw[mul_one] ... = (a * ((a * b) * (a * b))) * b : by rw[← eab] ... = ((a * (a * b)) * (a * b)) * b : by rw[← (mul_assoc a (a * b) (a * b))] ... = (b * (a * b)) * b : by rw[← (mul_assoc a a b),ea,one_mul b] ... = b * (a * (b * b)) : by rw[mul_assoc b (a * b) b,mul_assoc a b b] ... = b * a : by rw[eb,mul_one a] end /- Exercise 7 Encapsulate Exercise 6 as a typeclass instance -/ class elementary_two_group (G : Type*) extends (group G) := (square_one : ∀ a : G, a ^ 2 = 1) instance elementary_two_group_commutes (G : Type*) [e : elementary_two_group G] : comm_group G := { mul_comm := elem_ab_a e.square_one, ..e } /- Exercise 8 Define an inductive type of nonempty lists (which we will call pos_list). The basic structure will be similar to the definition of arbitrary lists, which can be done like this: inductive list (T : Type) | nil : list | cons : T → T → list However, instead of the constructor `nil`, which constructs the empty list, we should have a constructor called `const`, which constructs a list of length one. We can then give inductive definitions of functions that give the first and last element of a nonempty list, the length (normalised so that lists with one entry count as having length zero), the reverse and so on. -/ inductive pos_list (α : Type) : Type | const : α → pos_list | cons : α → pos_list → pos_list namespace pos_list variable {α : Type} def length : pos_list α → ℕ | (const a) := 0 | (cons a p) := p.length.succ def to_list : pos_list α → list α | (const a) := [a] | (cons a p) := list.cons a (to_list p) def head : pos_list α → α | (const a) := a | (cons a p) := a def foot : pos_list α → α | (const a) := a | (cons a p) := p.foot def append : pos_list α → pos_list α → pos_list α | (const a) q := cons a q | (cons a p) q := cons a (append p q) lemma head_append : ∀ (p q : pos_list α), head (append p q) = head p | (const a) q := rfl | (cons a p) q := rfl lemma foot_append : ∀ (p q : pos_list α), foot (append p q) = foot q | (const a) q := rfl | (cons a p) q := foot_append p q lemma append_assoc : ∀ (p q r : pos_list α), append (append p q) r = append p (append q r) | (const a) q r := rfl | (cons a p) q r := by {dsimp[append],rw[append_assoc p q r],} def reverse : pos_list α → pos_list α | (const a) := const a | (cons a p) := p.reverse.append (const a) lemma head_reverse : ∀ (p : pos_list α), p.reverse.head = p.foot | (const a) := rfl | (cons a p) := by {dsimp[reverse,foot],rw[head_append,head_reverse p],} lemma foot_reverse : ∀ (p : pos_list α), p.reverse.foot = p.head | (const a) := rfl | (cons a p) := by {dsimp[reverse,head],rw[foot_append],refl,} lemma reverse_append : ∀ (p q : pos_list α), reverse (append p q) = append (reverse q) (reverse p) | (const a) q := rfl | (cons a p) q := by {dsimp[append,reverse],rw[reverse_append p q,append_assoc],} lemma reverse_reverse : ∀ (p : pos_list α), p.reverse.reverse = p | (const a) := rfl | (cons a p) := begin dsimp[reverse],rw[reverse_append,reverse_reverse p],refl, end end pos_list /- Exercise 9 Set up some basic theory of graphs. In more detail, suppose we have a type V (to be considered as the vertex set). To make this a graph, we should have a predicate E so that E a b is true if there is an edge from a to b. We are considering simple undirected graphs with no loops, to this relation should be symmetric (ie E a b implies E b a) and irreflexive (so E a a is always false). Then define a type of paths in a graph. We can start by defining a predicate `is_path` on nonempty lists of vertices, which checks whether adjacent vertices in the list are linked by an edge. Using this, we can define paths as a subtype of nonempty lists. Now define a relation `are_connected` on V, which is satisfied by a pair of vertices if there is a path between them. Prove that this is an equivalence relation. -/ class graph (V : Type) : Type := (edge : V → V → Prop) (symm : ∀ {u v : V}, edge u v → edge v u) (asymm : ∀ v : V, ¬ edge v v) namespace graph variables {V : Type} [graph V] def is_path : pos_list V → Prop | (pos_list.const _) := true | (pos_list.cons v p) := (edge v p.head) ∧ is_path p lemma is_path_append (p q : pos_list V) : is_path (pos_list.append p q) ↔ is_path p ∧ edge p.foot q.head ∧ is_path q := begin induction p with a a p ih, {dsimp[is_path,pos_list.foot,pos_list.append,is_path], rw[true_and] }, {dsimp[pos_list.append,pos_list.foot,is_path], rw[pos_list.head_append,ih,and_assoc], } end lemma is_path_reverse : ∀ {p : pos_list V}, is_path p → is_path p.reverse | (pos_list.const a) _ := by {dsimp[pos_list.reverse,is_path],trivial} | (pos_list.cons a p) h := begin dsimp[pos_list.reverse,is_path], dsimp[is_path] at h, rw[is_path_append,pos_list.head,pos_list.foot_reverse,is_path,and_true], exact ⟨is_path_reverse h.right,symm h.left⟩, end variable (V) def path : Type := { p : pos_list V // is_path p } variable {V} def path_between (a b : V) : Type := { p : pos_list V // is_path p ∧ p.head = a ∧ p.foot = b } namespace path def head (p : path V) : V := p.val.head def foot (p : path V) : V := p.val.foot def length (p : path V) : ℕ := p.val.length def cons (v : V) (p : path V) (h : edge v p.head) : path V := ⟨pos_list.cons v p.val,⟨h,p.property⟩⟩ def const (v : V) : path_between v v := ⟨pos_list.const v,⟨trivial,rfl,rfl⟩⟩ def reverse {u v : V} : ∀ (p : path_between u v), path_between v u | ⟨p,⟨p_path,p_head,p_foot⟩⟩ := ⟨p.reverse,⟨is_path_reverse p_path, (pos_list.head_reverse p).trans p_foot, (pos_list.foot_reverse p).trans p_head⟩⟩ def splice {u v w : V} : ∀ (p : path_between u v) (q : path_between v w), path_between u w | ⟨p,⟨p_path,p_head,p_foot⟩⟩ ⟨pos_list.const x,⟨q_path,q_head,q_foot⟩⟩ := ⟨p,begin change x = v at q_head, change x = w at q_foot, replace p_foot := p_foot.trans (q_head.symm.trans q_foot), exact ⟨p_path,p_head,p_foot⟩ end⟩ | ⟨p,⟨p_path,p_head,p_foot⟩⟩ ⟨pos_list.cons x q,⟨q_path,q_head,q_foot⟩⟩ := ⟨pos_list.append p q, begin change x = v at q_head, change q.foot = w at q_foot, rw[pos_list.head_append,p_head,pos_list.foot_append,q_foot], split, {dsimp[is_path] at q_path,rw[is_path_append,p_foot,← q_head], exact ⟨p_path,q_path⟩}, {split;refl,} end ⟩ instance are_connected : setoid V := { r := λ a b, nonempty (path_between a b), iseqv := ⟨ λ a, nonempty.intro (const a), λ a b ⟨p⟩, nonempty.intro (reverse p), λ a b c ⟨p⟩ ⟨q⟩, nonempty.intro (splice p q) ⟩ } end path end graph /- Exercise 10 Construct an equivalence `ℕ ≃ E ⊕ O`, where `E` and `O` are the subtypes of even and odd natural numbers. Here `E ⊕ O` is alternative notation for `sum E O`, which is defined in the core lean library to be the disjoint union of E and O. Equivalences are defined in data.equiv: an equivalence from X to Y is a structure with four members: functions `to_fun : X → Y` and `inv_fun : Y → X`, and proofs that `inv_fun` is both left inverse and right inverse to `to_fun`. -/ def E := {n : ℕ // n.bodd = ff} def O := {n : ℕ // n.bodd = tt} lemma bool_elim {C : Sort*} {b : bool} : b ≠ ff → b ≠ tt → C := by {intros,cases b;contradiction} def f (n : ℕ) : E ⊕ O := begin by_cases n_even : n.bodd = ff, {exact sum.inl ⟨n,n_even⟩}, by_cases n_odd : n.bodd = tt, {exact sum.inr ⟨n,n_odd⟩}, exact bool_elim n_even n_odd end def g : E ⊕ O → ℕ | (sum.inl n) := n.val | (sum.inr n) := n.val lemma fg : ∀ x : E ⊕ O, f (g x) = x | (sum.inl ⟨n,n_even⟩) := by {dsimp[g,f],rw[dif_pos n_even]} | (sum.inr ⟨n,n_odd⟩) := begin have n_not_even : n.bodd ≠ ff := by {rw[n_odd],intro e,injection e,}, dsimp[g,f], rw[dif_neg n_not_even,dif_pos n_odd], end lemma gf (n : ℕ) : g (f n) = n := begin dsimp[f], by_cases n_even : n.bodd = ff, {rw[dif_pos n_even],refl}, by_cases n_odd : n.bodd = tt, {have n_not_even : n.bodd ≠ ff := by {rw[n_odd],intro e,injection e,}, rw[dif_neg n_not_even,dif_pos n_odd], refl, }, exact bool_elim n_even n_odd end def F : ℕ ≃ (E ⊕ O) := ⟨f,g,gf,fg⟩
5974d34a40638dbdff956dcd93777bcbed787231
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/functor_category.lean
f8a3ecf064a69afc7d7f23085e6a423917e6c173
[]
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,875
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.preserves.limits import Mathlib.PostPort universes v v₂ u namespace Mathlib namespace category_theory.limits @[simp] theorem limit.lift_π_app {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (H : J ⥤ K ⥤ C) [has_limit H] (c : cone H) (j : J) (k : K) : nat_trans.app (limit.lift H c) k ≫ nat_trans.app (limit.π H j) k = nat_trans.app (nat_trans.app (cone.π c) j) k := congr_app (limit.lift_π c j) k @[simp] theorem colimit.ι_desc_app_assoc {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (H : J ⥤ K ⥤ C) [has_colimit H] (c : cocone H) (j : J) (k : K) {X' : C} (f' : functor.obj (cocone.X c) k ⟶ X') : nat_trans.app (colimit.ι H j) k ≫ nat_trans.app (colimit.desc H c) k ≫ f' = nat_trans.app (nat_trans.app (cocone.ι c) j) k ≫ f' := sorry /-- The evaluation functors jointly reflect limits: that is, to show a cone is a limit of `F` it suffices to show that each evaluation cone is a limit. In other words, to prove a cone is limiting you can show it's pointwise limiting. -/ def evaluation_jointly_reflects_limits {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {F : J ⥤ K ⥤ C} (c : cone F) (t : (k : K) → is_limit (functor.map_cone (functor.obj (evaluation K C) k) c)) : is_limit c := is_limit.mk fun (s : cone F) => nat_trans.mk fun (k : K) => is_limit.lift (t k) (cone.mk (functor.obj (cone.X s) k) (whisker_right (cone.π s) (functor.obj (evaluation K C) k))) /-- Given a functor `F` and a collection of limit cones for each diagram `X ↦ F X k`, we can stitch them together to give a cone for the diagram `F`. `combined_is_limit` shows that the new cone is limiting, and `eval_combined` shows it is (essentially) made up of the original cones. -/ @[simp] theorem combine_cones_X_obj {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) (k : K) : functor.obj (cone.X (combine_cones F c)) k = cone.X (limit_cone.cone (c k)) := Eq.refl (functor.obj (cone.X (combine_cones F c)) k) /-- The stitched together cones each project down to the original given cones (up to iso). -/ def evaluate_combined_cones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) (k : K) : functor.map_cone (functor.obj (evaluation K C) k) (combine_cones F c) ≅ limit_cone.cone (c k) := cones.ext (iso.refl (cone.X (functor.map_cone (functor.obj (evaluation K C) k) (combine_cones F c)))) sorry /-- Stitching together limiting cones gives a limiting cone. -/ def combined_is_limit {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → limit_cone (functor.obj (functor.flip F) k)) : is_limit (combine_cones F c) := evaluation_jointly_reflects_limits (combine_cones F c) fun (k : K) => is_limit.of_iso_limit (limit_cone.is_limit (c k)) (iso.symm (evaluate_combined_cones F c k)) /-- The evaluation functors jointly reflect colimits: that is, to show a cocone is a colimit of `F` it suffices to show that each evaluation cocone is a colimit. In other words, to prove a cocone is colimiting you can show it's pointwise colimiting. -/ def evaluation_jointly_reflects_colimits {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {F : J ⥤ K ⥤ C} (c : cocone F) (t : (k : K) → is_colimit (functor.map_cocone (functor.obj (evaluation K C) k) c)) : is_colimit c := is_colimit.mk fun (s : cocone F) => nat_trans.mk fun (k : K) => is_colimit.desc (t k) (cocone.mk (functor.obj (cocone.X s) k) (whisker_right (cocone.ι s) (functor.obj (evaluation K C) k))) /-- Given a functor `F` and a collection of colimit cocones for each diagram `X ↦ F X k`, we can stitch them together to give a cocone for the diagram `F`. `combined_is_colimit` shows that the new cocone is colimiting, and `eval_combined` shows it is (essentially) made up of the original cocones. -/ def combine_cocones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) : cocone F := cocone.mk (functor.mk (fun (k : K) => cocone.X (colimit_cocone.cocone (c k))) fun (k₁ k₂ : K) (f : k₁ ⟶ k₂) => is_colimit.desc (colimit_cocone.is_colimit (c k₁)) (cocone.mk (cocone.X (colimit_cocone.cocone (c k₂))) (functor.map (functor.flip F) f ≫ cocone.ι (colimit_cocone.cocone (c k₂))))) (nat_trans.mk fun (j : J) => nat_trans.mk fun (k : K) => nat_trans.app (cocone.ι (colimit_cocone.cocone (c k))) j) /-- The stitched together cocones each project down to the original given cocones (up to iso). -/ def evaluate_combined_cocones {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) (k : K) : functor.map_cocone (functor.obj (evaluation K C) k) (combine_cocones F c) ≅ colimit_cocone.cocone (c k) := cocones.ext (iso.refl (cocone.X (functor.map_cocone (functor.obj (evaluation K C) k) (combine_cocones F c)))) sorry /-- Stitching together colimiting cocones gives a colimiting cocone. -/ def combined_is_colimit {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] (F : J ⥤ K ⥤ C) (c : (k : K) → colimit_cocone (functor.obj (functor.flip F) k)) : is_colimit (combine_cocones F c) := evaluation_jointly_reflects_colimits (combine_cocones F c) fun (k : K) => is_colimit.of_iso_colimit (colimit_cocone.is_colimit (c k)) (iso.symm (evaluate_combined_cocones F c k)) protected instance functor_category_has_limits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] : has_limits_of_shape J (K ⥤ C) := has_limits_of_shape.mk fun (F : J ⥤ K ⥤ C) => has_limit.mk (limit_cone.mk (combine_cones F fun (k : K) => get_limit_cone (functor.obj (functor.flip F) k)) (combined_is_limit F fun (k : K) => get_limit_cone (functor.obj (functor.flip F) k))) protected instance functor_category_has_colimits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] : has_colimits_of_shape J (K ⥤ C) := has_colimits_of_shape.mk fun (F : J ⥤ K ⥤ C) => has_colimit.mk (colimit_cocone.mk (combine_cocones F fun (k : K) => get_colimit_cocone (functor.obj (functor.flip F) k)) (combined_is_colimit F fun (k : K) => get_colimit_cocone (functor.obj (functor.flip F) k))) protected instance functor_category_has_limits {C : Type u} [category C] {K : Type v} [category K] [has_limits C] : has_limits (K ⥤ C) := has_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.functor_category_has_limits_of_shape protected instance functor_category_has_colimits {C : Type u} [category C] {K : Type v} [category K] [has_colimits C] : has_colimits (K ⥤ C) := has_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.functor_category_has_colimits_of_shape protected instance evaluation_preserves_limits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (k : K) : preserves_limits_of_shape J (functor.obj (evaluation K C) k) := preserves_limits_of_shape.mk fun (F : J ⥤ K ⥤ C) => preserves_limit_of_preserves_limit_cone (combined_is_limit F fun (k : K) => get_limit_cone (F ⋙ functor.obj (evaluation K C) k)) (is_limit.of_iso_limit (limit.is_limit (F ⋙ functor.obj (evaluation K C) k)) (iso.symm (evaluate_combined_cones F (fun (k : K) => get_limit_cone (F ⋙ functor.obj (evaluation K C) k)) k))) /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a limit, then the evaluation of that limit at `k` is the limit of the evaluations of `F.obj j` at `k`. -/ def limit_obj_iso_limit_comp_evaluation {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : functor.obj (limit F) k ≅ limit (F ⋙ functor.obj (evaluation K C) k) := preserves_limit_iso (functor.obj (evaluation K C) k) F @[simp] theorem limit_obj_iso_limit_comp_evaluation_hom_π {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : iso.hom (limit_obj_iso_limit_comp_evaluation F k) ≫ limit.π (F ⋙ functor.obj (evaluation K C) k) j = nat_trans.app (limit.π F j) k := sorry @[simp] theorem limit_obj_iso_limit_comp_evaluation_inv_π_app_assoc {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_limits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) {X' : C} (f' : functor.obj (functor.obj F j) k ⟶ X') : iso.inv (limit_obj_iso_limit_comp_evaluation F k) ≫ nat_trans.app (limit.π F j) k ≫ f' = limit.π (F ⋙ functor.obj (evaluation K C) k) j ≫ f' := sorry theorem limit_obj_ext {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {H : J ⥤ K ⥤ C} [has_limits_of_shape J C] {k : K} {W : C} {f : W ⟶ functor.obj (limit H) k} {g : W ⟶ functor.obj (limit H) k} (w : ∀ (j : J), f ≫ nat_trans.app (limit.π H j) k = g ≫ nat_trans.app (limit.π H j) k) : f = g := sorry protected instance evaluation_preserves_colimits_of_shape {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (k : K) : preserves_colimits_of_shape J (functor.obj (evaluation K C) k) := preserves_colimits_of_shape.mk fun (F : J ⥤ K ⥤ C) => preserves_colimit_of_preserves_colimit_cocone (combined_is_colimit F fun (k : K) => get_colimit_cocone (F ⋙ functor.obj (evaluation K C) k)) (is_colimit.of_iso_colimit (colimit.is_colimit (F ⋙ functor.obj (evaluation K C) k)) (iso.symm (evaluate_combined_cocones F (fun (k : K) => get_colimit_cocone (F ⋙ functor.obj (evaluation K C) k)) k))) /-- If `F : J ⥤ K ⥤ C` is a functor into a functor category which has a colimit, then the evaluation of that colimit at `k` is the colimit of the evaluations of `F.obj j` at `k`. -/ def colimit_obj_iso_colimit_comp_evaluation {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (k : K) : functor.obj (colimit F) k ≅ colimit (F ⋙ functor.obj (evaluation K C) k) := preserves_colimit_iso (functor.obj (evaluation K C) k) F @[simp] theorem colimit_obj_iso_colimit_comp_evaluation_ι_inv {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : colimit.ι (F ⋙ functor.obj (evaluation K C) k) j ≫ iso.inv (colimit_obj_iso_colimit_comp_evaluation F k) = nat_trans.app (colimit.ι F j) k := sorry @[simp] theorem colimit_obj_iso_colimit_comp_evaluation_ι_app_hom {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] [has_colimits_of_shape J C] (F : J ⥤ K ⥤ C) (j : J) (k : K) : nat_trans.app (colimit.ι F j) k ≫ iso.hom (colimit_obj_iso_colimit_comp_evaluation F k) = colimit.ι (F ⋙ functor.obj (evaluation K C) k) j := sorry theorem colimit_obj_ext {C : Type u} [category C] {J : Type v} {K : Type v} [small_category J] [category K] {H : J ⥤ K ⥤ C} [has_colimits_of_shape J C] {k : K} {W : C} {f : functor.obj (colimit H) k ⟶ W} {g : functor.obj (colimit H) k ⟶ W} (w : ∀ (j : J), nat_trans.app (colimit.ι H j) k ≫ f = nat_trans.app (colimit.ι H j) k ≫ g) : f = g := sorry protected instance evaluation_preserves_limits {C : Type u} [category C] {K : Type v} [category K] [has_limits C] (k : K) : preserves_limits (functor.obj (evaluation K C) k) := preserves_limits.mk fun (J : Type v) (𝒥 : small_category J) => limits.evaluation_preserves_limits_of_shape k protected instance evaluation_preserves_colimits {C : Type u} [category C] {K : Type v} [category K] [has_colimits C] (k : K) : preserves_colimits (functor.obj (evaluation K C) k) := preserves_colimits.mk fun (J : Type v) (𝒥 : small_category J) => limits.evaluation_preserves_colimits_of_shape k
cdbf9e97f3bce618293a898a676c5b29b2230f8c
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/auto_quote1.lean
6dcbdbddc4b854c89a3092e9c24c9a66f736d721
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
1,934
lean
example (a b c : nat) : a = b → b = c → c = a := begin intros, apply eq.symm, apply eq.trans, assumption, assumption end example (a b c : nat) : a = b → b = c → c = a := begin intro h1, intro h2, refine eq.symm (eq.trans h1 _), exact h2 end example (a b c : nat) : a = b → b = c → c = a := begin intros h1 h2, -- we can optionally provide the names refine eq.symm (eq.trans h1 _), exact h2 end example (a b c : nat) : a = b → b = c → c = a := begin intro h1, intro, -- optional argument refine eq.symm (eq.trans h1 _), assumption end constant addc {a b : nat} : a + b = b + a constant addassoc {a b c : nat} : (a + b) + c = a + (b + c) constant zadd (a : nat) : 0 + a = a example (a b c : nat) : b = 0 → 0 + a + b + c = c + a := begin intro h, rewrite h, -- single rewrite rewrite [zadd, @addc a 0, zadd, addc] -- sequence of rewrites end example (a b c : nat) : 0 = b → 0 + a + b + c = c + a := begin intro h, rewrite -h, -- single rewrite using symmetry rw [zadd, @addc a 0, zadd, addc] -- rw is shorthand for rewrite end open nat example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, { -- Remark: Used change here to make sure nat.zero is replaced with polymorphic zero. -- dsimp tactic should fix that in the future. change n + 0 = 0 + n, rw zadd n }, { change succ (n + m') = succ m' + n, rw [succ_add, ih] } end example (a b c : nat) : 0 = b → 0 + a + b + c = c + a := by do tactic.intro `h, `[rewrite -h, rw zadd, rw @addc a 0, rw zadd, rw addc] example : ∀ n m : ℕ, n + m = m + n := begin intros n m, induction m with m' ih, show n + 0 = 0 + n, begin change n + 0 = 0 + n, rw zadd n end, show n + succ m' = succ m' + n, { change succ (n + m') = succ m' + n, calc succ (n + m') = succ (m' + n) : by rw ih ... = succ m' + n : by rw succ_add } end
1e9d7b2614fbc59e3c424f8a9b7e284e22e78153
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/types/eq.hlean
b2c0c688a95f3b0834fe050438f7c7429f495aa3
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,510
hlean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn Partially ported from Coq HoTT Theorems about path types (identity types) -/ import types.sigma open eq sigma sigma.ops equiv is_equiv equiv.ops is_trunc -- TODO: Rename transport_eq_... and pathover_eq_... to eq_transport_... and eq_pathover_... namespace eq /- Path spaces -/ section variables {A B : Type} {a a₁ a₂ a₃ a₄ a' : A} {b b1 b2 : B} {f g : A → B} {h : B → A} {p p' p'' : a₁ = a₂} /- The path spaces of a path space are not, of course, determined; they are just the higher-dimensional structure of the original space. -/ /- some lemmas about whiskering or other higher paths -/ theorem whisker_left_con_right (p : a₁ = a₂) {q q' q'' : a₂ = a₃} (r : q = q') (s : q' = q'') : whisker_left p (r ⬝ s) = whisker_left p r ⬝ whisker_left p s := begin induction p, induction r, induction s, reflexivity end theorem whisker_right_con_right (q : a₂ = a₃) (r : p = p') (s : p' = p'') : whisker_right (r ⬝ s) q = whisker_right r q ⬝ whisker_right s q := begin induction q, induction r, induction s, reflexivity end theorem whisker_left_con_left (p : a₁ = a₂) (p' : a₂ = a₃) {q q' : a₃ = a₄} (r : q = q') : whisker_left (p ⬝ p') r = !con.assoc ⬝ whisker_left p (whisker_left p' r) ⬝ !con.assoc' := begin induction p', induction p, induction r, induction q, reflexivity end theorem whisker_right_con_left {p p' : a₁ = a₂} (q : a₂ = a₃) (q' : a₃ = a₄) (r : p = p') : whisker_right r (q ⬝ q') = !con.assoc' ⬝ whisker_right (whisker_right r q) q' ⬝ !con.assoc := begin induction q', induction q, induction r, induction p, reflexivity end theorem whisker_left_inv_left (p : a₂ = a₁) {q q' : a₂ = a₃} (r : q = q') : !con_inv_cancel_left⁻¹ ⬝ whisker_left p (whisker_left p⁻¹ r) ⬝ !con_inv_cancel_left = r := begin induction p, induction r, induction q, reflexivity end theorem whisker_left_inv (p : a₁ = a₂) {q q' : a₂ = a₃} (r : q = q') : whisker_left p r⁻¹ = (whisker_left p r)⁻¹ := by induction r; reflexivity theorem whisker_right_inv {p p' : a₁ = a₂} (q : a₂ = a₃) (r : p = p') : whisker_right r⁻¹ q = (whisker_right r q)⁻¹ := by induction r; reflexivity theorem ap_eq_ap10 {f g : A → B} (p : f = g) (a : A) : ap (λh, h a) p = ap10 p a := by induction p;reflexivity theorem inverse2_right_inv (r : p = p') : r ◾ inverse2 r ⬝ con.right_inv p' = con.right_inv p := by induction r;induction p;reflexivity theorem inverse2_left_inv (r : p = p') : inverse2 r ◾ r ⬝ con.left_inv p' = con.left_inv p := by induction r;induction p;reflexivity theorem ap_con_right_inv (f : A → B) (p : a₁ = a₂) : ap_con f p p⁻¹ ⬝ whisker_left _ (ap_inv f p) ⬝ con.right_inv (ap f p) = ap (ap f) (con.right_inv p) := by induction p;reflexivity theorem ap_con_left_inv (f : A → B) (p : a₁ = a₂) : ap_con f p⁻¹ p ⬝ whisker_right (ap_inv f p) _ ⬝ con.left_inv (ap f p) = ap (ap f) (con.left_inv p) := by induction p;reflexivity theorem idp_con_whisker_left {q q' : a₂ = a₃} (r : q = q') : !idp_con⁻¹ ⬝ whisker_left idp r = r ⬝ !idp_con⁻¹ := by induction r;induction q;reflexivity theorem whisker_left_idp_con {q q' : a₂ = a₃} (r : q = q') : whisker_left idp r ⬝ !idp_con = !idp_con ⬝ r := by induction r;induction q;reflexivity theorem idp_con_idp {p : a = a} (q : p = idp) : idp_con p ⬝ q = ap (λp, idp ⬝ p) q := by cases q;reflexivity definition ap_is_constant [unfold 8] {A B : Type} {f : A → B} {b : B} (p : Πx, f x = b) {x y : A} (q : x = y) : ap f q = p x ⬝ (p y)⁻¹ := by induction q;exact !con.right_inv⁻¹ definition inv2_inv {p q : a = a'} (r : p = q) : inverse2 r⁻¹ = (inverse2 r)⁻¹ := by induction r;reflexivity definition inv2_con {p p' p'' : a = a'} (r : p = p') (r' : p' = p'') : inverse2 (r ⬝ r') = inverse2 r ⬝ inverse2 r' := by induction r';induction r;reflexivity definition con2_inv {p₁ q₁ : a₁ = a₂} {p₂ q₂ : a₂ = a₃} (r₁ : p₁ = q₁) (r₂ : p₂ = q₂) : (r₁ ◾ r₂)⁻¹ = r₁⁻¹ ◾ r₂⁻¹ := by induction r₁;induction r₂;reflexivity theorem eq_con_inv_of_con_eq_whisker_left {A : Type} {a a₂ a₃ : A} {p : a = a₂} {q q' : a₂ = a₃} {r : a = a₃} (s' : q = q') (s : p ⬝ q' = r) : eq_con_inv_of_con_eq (whisker_left p s' ⬝ s) = eq_con_inv_of_con_eq s ⬝ whisker_left r (inverse2 s')⁻¹ := by induction s';induction q;induction s;reflexivity theorem right_inv_eq_idp {A : Type} {a : A} {p : a = a} (r : p = idpath a) : con.right_inv p = r ◾ inverse2 r := by cases r;reflexivity /- Transporting in path spaces. There are potentially a lot of these lemmas, so we adopt a uniform naming scheme: - `l` means the left endpoint varies - `r` means the right endpoint varies - `F` means application of a function to that (varying) endpoint. -/ definition transport_eq_l (p : a₁ = a₂) (q : a₁ = a₃) : transport (λx, x = a₃) p q = p⁻¹ ⬝ q := by induction p; induction q; reflexivity definition transport_eq_r (p : a₂ = a₃) (q : a₁ = a₂) : transport (λx, a₁ = x) p q = q ⬝ p := by induction p; induction q; reflexivity definition transport_eq_lr (p : a₁ = a₂) (q : a₁ = a₁) : transport (λx, x = x) p q = p⁻¹ ⬝ q ⬝ p := by induction p; rewrite [▸*,idp_con] definition transport_eq_Fl (p : a₁ = a₂) (q : f a₁ = b) : transport (λx, f x = b) p q = (ap f p)⁻¹ ⬝ q := by induction p; induction q; reflexivity definition transport_eq_Fr (p : a₁ = a₂) (q : b = f a₁) : transport (λx, b = f x) p q = q ⬝ (ap f p) := by induction p; reflexivity definition transport_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := by induction p; rewrite [▸*,idp_con] definition transport_eq_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : transport (λx, f x = g x) p q = (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) := by induction p; rewrite [▸*,idp_con,ap_id] definition transport_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : transport (λx, h (f x) = x) p q = (ap h (ap f p))⁻¹ ⬝ q ⬝ p := by induction p; rewrite [▸*,idp_con] definition transport_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : transport (λx, x = h (f x)) p q = p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := by induction p; rewrite [▸*,idp_con] /- Pathovers -/ -- In the comment we give the fibration of the pathover -- we should probably try to do everything just with pathover_eq (defined in cubical.square), -- the following definitions may be removed in future. definition pathover_eq_l (p : a₁ = a₂) (q : a₁ = a₃) : q =[p] p⁻¹ ⬝ q := /-(λx, x = a₃)-/ by induction p; induction q; exact idpo definition pathover_eq_r (p : a₂ = a₃) (q : a₁ = a₂) : q =[p] q ⬝ p := /-(λx, a₁ = x)-/ by induction p; induction q; exact idpo definition pathover_eq_lr (p : a₁ = a₂) (q : a₁ = a₁) : q =[p] p⁻¹ ⬝ q ⬝ p := /-(λx, x = x)-/ by induction p; rewrite [▸*,idp_con]; exact idpo definition pathover_eq_Fl (p : a₁ = a₂) (q : f a₁ = b) : q =[p] (ap f p)⁻¹ ⬝ q := /-(λx, f x = b)-/ by induction p; induction q; exact idpo definition pathover_eq_Fr (p : a₁ = a₂) (q : b = f a₁) : q =[p] q ⬝ (ap f p) := /-(λx, b = f x)-/ by induction p; exact idpo definition pathover_eq_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (ap f p)⁻¹ ⬝ q ⬝ (ap g p) := /-(λx, f x = g x)-/ by induction p; rewrite [▸*,idp_con]; exact idpo definition pathover_eq_FlFr_D {B : A → Type} {f g : Πa, B a} (p : a₁ = a₂) (q : f a₁ = g a₁) : q =[p] (apd f p)⁻¹ ⬝ ap (transport B p) q ⬝ (apd g p) := /-(λx, f x = g x)-/ by induction p; rewrite [▸*,idp_con,ap_id];exact idpo definition pathover_eq_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) : q =[p] (ap h (ap f p))⁻¹ ⬝ q ⬝ p := /-(λx, h (f x) = x)-/ by induction p; rewrite [▸*,idp_con];exact idpo definition pathover_eq_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) : q =[p] p⁻¹ ⬝ q ⬝ (ap h (ap f p)) := /-(λx, x = h (f x))-/ by induction p; rewrite [▸*,idp_con];exact idpo definition pathover_eq_r_idp (p : a₁ = a₂) : idp =[p] p := /-(λx, a₁ = x)-/ by induction p; exact idpo definition pathover_eq_l_idp (p : a₁ = a₂) : idp =[p] p⁻¹ := /-(λx, x = a₁)-/ by induction p; exact idpo definition pathover_eq_l_idp' (p : a₁ = a₂) : idp =[p⁻¹] p := /-(λx, x = a₂)-/ by induction p; exact idpo -- The Functorial action of paths is [ap]. /- Equivalences between path spaces -/ /- [ap_closed] is in init.equiv -/ definition equiv_ap (f : A → B) [H : is_equiv f] (a₁ a₂ : A) : (a₁ = a₂) ≃ (f a₁ = f a₂) := equiv.mk (ap f) _ /- Path operations are equivalences -/ definition is_equiv_eq_inverse (a₁ a₂ : A) : is_equiv (inverse : a₁ = a₂ → a₂ = a₁) := is_equiv.mk inverse inverse inv_inv inv_inv (λp, eq.rec_on p idp) local attribute is_equiv_eq_inverse [instance] definition eq_equiv_eq_symm (a₁ a₂ : A) : (a₁ = a₂) ≃ (a₂ = a₁) := equiv.mk inverse _ definition is_equiv_concat_left [constructor] [instance] (p : a₁ = a₂) (a₃ : A) : is_equiv (concat p : a₂ = a₃ → a₁ = a₃) := is_equiv.mk (concat p) (concat p⁻¹) (con_inv_cancel_left p) (inv_con_cancel_left p) abstract (λq, by induction p;induction q;reflexivity) end local attribute is_equiv_concat_left [instance] definition equiv_eq_closed_left [constructor] (a₃ : A) (p : a₁ = a₂) : (a₁ = a₃) ≃ (a₂ = a₃) := equiv.mk (concat p⁻¹) _ definition is_equiv_concat_right [constructor] [instance] (p : a₂ = a₃) (a₁ : A) : is_equiv (λq : a₁ = a₂, q ⬝ p) := is_equiv.mk (λq, q ⬝ p) (λq, q ⬝ p⁻¹) (λq, inv_con_cancel_right q p) (λq, con_inv_cancel_right q p) (λq, by induction p;induction q;reflexivity) local attribute is_equiv_concat_right [instance] definition equiv_eq_closed_right [constructor] (a₁ : A) (p : a₂ = a₃) : (a₁ = a₂) ≃ (a₁ = a₃) := equiv.mk (λq, q ⬝ p) _ definition eq_equiv_eq_closed [constructor] (p : a₁ = a₂) (q : a₃ = a₄) : (a₁ = a₃) ≃ (a₂ = a₄) := equiv.trans (equiv_eq_closed_left a₃ p) (equiv_eq_closed_right a₂ q) definition is_equiv_whisker_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃) : is_equiv (whisker_left p : q = r → p ⬝ q = p ⬝ r) := begin fapply adjointify, {intro s, apply (!cancel_left s)}, {intro s, apply concat, {apply whisker_left_con_right}, apply concat, rotate_left 1, apply (whisker_left_inv_left p s), apply concat2, {apply concat, {apply whisker_left_con_right}, apply concat2, {induction p, induction q, reflexivity}, {reflexivity}}, {induction p, induction r, reflexivity}}, {intro s, induction s, induction q, induction p, reflexivity} end definition eq_equiv_con_eq_con_left [constructor] (p : a₁ = a₂) (q r : a₂ = a₃) : (q = r) ≃ (p ⬝ q = p ⬝ r) := equiv.mk _ !is_equiv_whisker_left definition is_equiv_whisker_right [constructor] {p q : a₁ = a₂} (r : a₂ = a₃) : is_equiv (λs, whisker_right s r : p = q → p ⬝ r = q ⬝ r) := begin fapply adjointify, {intro s, apply (!cancel_right s)}, {intro s, induction r, cases s, induction q, reflexivity}, {intro s, induction s, induction r, induction p, reflexivity} end definition eq_equiv_con_eq_con_right [constructor] (p q : a₁ = a₂) (r : a₂ = a₃) : (p = q) ≃ (p ⬝ r = q ⬝ r) := equiv.mk _ !is_equiv_whisker_right /- The following proofs can be simplified a bit by concatenating previous equivalences. However, these proofs have the advantage that the inverse is definitionally equal to what we would expect -/ definition is_equiv_con_eq_of_eq_inv_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_inv_con : p = r⁻¹ ⬝ q → r ⬝ p = q) := begin fapply adjointify, { apply eq_inv_con_of_con_eq}, { intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq], con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]}, { intro s, induction r, rewrite [↑[con_eq_of_eq_inv_con,eq_inv_con_of_con_eq], con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] }, end definition eq_inv_con_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (p = r⁻¹ ⬝ q) ≃ (r ⬝ p = q) := equiv.mk _ !is_equiv_con_eq_of_eq_inv_con definition is_equiv_con_eq_of_eq_con_inv [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_eq_of_eq_con_inv : r = q ⬝ p⁻¹ → r ⬝ p = q) := begin fapply adjointify, { apply eq_con_inv_of_con_eq}, { intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]]}, { intro s, induction p, rewrite [↑[con_eq_of_eq_con_inv,eq_con_inv_of_con_eq]] }, end definition eq_con_inv_equiv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p⁻¹) ≃ (r ⬝ p = q) := equiv.mk _ !is_equiv_con_eq_of_eq_con_inv definition is_equiv_inv_con_eq_of_eq_con [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : is_equiv (inv_con_eq_of_eq_con : p = r ⬝ q → r⁻¹ ⬝ p = q) := begin fapply adjointify, { apply eq_con_of_inv_con_eq}, { intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq], con.assoc,con.assoc,con.left_inv,▸*,-con.assoc,con.right_inv,▸* at *,idp_con s]}, { intro s, induction r, rewrite [↑[inv_con_eq_of_eq_con,eq_con_of_inv_con_eq], con.assoc,con.assoc,con.right_inv,▸*,-con.assoc,con.left_inv,▸* at *,idp_con s] }, end definition eq_con_equiv_inv_con_eq [constructor] (p : a₁ = a₃) (q : a₂ = a₃) (r : a₁ = a₂) : (p = r ⬝ q) ≃ (r⁻¹ ⬝ p = q) := equiv.mk _ !is_equiv_inv_con_eq_of_eq_con definition is_equiv_con_inv_eq_of_eq_con [constructor] (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (con_inv_eq_of_eq_con : r = q ⬝ p → r ⬝ p⁻¹ = q) := begin fapply adjointify, { apply eq_con_of_con_inv_eq}, { intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]]}, { intro s, induction p, rewrite [↑[con_inv_eq_of_eq_con,eq_con_of_con_inv_eq]] }, end definition eq_con_equiv_con_inv_eq (p : a₃ = a₁) (q : a₂ = a₃) (r : a₂ = a₁) : (r = q ⬝ p) ≃ (r ⬝ p⁻¹ = q) := equiv.mk _ !is_equiv_con_inv_eq_of_eq_con local attribute is_equiv_inv_con_eq_of_eq_con is_equiv_con_inv_eq_of_eq_con is_equiv_con_eq_of_eq_con_inv is_equiv_con_eq_of_eq_inv_con [instance] definition is_equiv_eq_con_of_inv_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_inv_con_eq : r⁻¹ ⬝ q = p → q = r ⬝ p) := is_equiv_inv inv_con_eq_of_eq_con definition is_equiv_eq_con_of_con_inv_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_of_con_inv_eq : q ⬝ p⁻¹ = r → q = r ⬝ p) := is_equiv_inv con_inv_eq_of_eq_con definition is_equiv_eq_con_inv_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_con_inv_of_con_eq : r ⬝ p = q → r = q ⬝ p⁻¹) := is_equiv_inv con_eq_of_eq_con_inv definition is_equiv_eq_inv_con_of_con_eq (p : a₁ = a₃) (q : a₂ = a₃) (r : a₂ = a₁) : is_equiv (eq_inv_con_of_con_eq : r ⬝ p = q → p = r⁻¹ ⬝ q) := is_equiv_inv con_eq_of_eq_inv_con definition is_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : is_equiv (con_inv_eq_idp : p = q → p ⬝ q⁻¹ = idp) := begin fapply adjointify, { apply eq_of_con_inv_eq_idp}, { intro s, induction q, esimp at *, cases s, reflexivity}, { intro s, induction s, induction p, reflexivity}, end definition is_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : is_equiv (inv_con_eq_idp : p = q → q⁻¹ ⬝ p = idp) := begin fapply adjointify, { apply eq_of_inv_con_eq_idp}, { intro s, induction q, esimp [eq_of_inv_con_eq_idp] at *, eapply is_equiv_rect (eq_equiv_con_eq_con_left idp p idp), clear s, intro s, cases s, reflexivity}, { intro s, induction s, induction p, reflexivity}, end definition eq_equiv_con_inv_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (p ⬝ q⁻¹ = idp) := equiv.mk _ !is_equiv_con_inv_eq_idp definition eq_equiv_inv_con_eq_idp [constructor] (p q : a₁ = a₂) : (p = q) ≃ (q⁻¹ ⬝ p = idp) := equiv.mk _ !is_equiv_inv_con_eq_idp /- Pathover Equivalences -/ definition pathover_eq_equiv_l (p : a₁ = a₂) (q : a₁ = a₃) (r : a₂ = a₃) : q =[p] r ≃ q = p ⬝ r := /-(λx, x = a₃)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition pathover_eq_equiv_r (p : a₂ = a₃) (q : a₁ = a₂) (r : a₁ = a₃) : q =[p] r ≃ q ⬝ p = r := /-(λx, a₁ = x)-/ by induction p; apply pathover_idp definition pathover_eq_equiv_lr (p : a₁ = a₂) (q : a₁ = a₁) (r : a₂ = a₂) : q =[p] r ≃ q ⬝ p = p ⬝ r := /-(λx, x = x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition pathover_eq_equiv_Fl (p : a₁ = a₂) (q : f a₁ = b) (r : f a₂ = b) : q =[p] r ≃ q = ap f p ⬝ r := /-(λx, f x = b)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition pathover_eq_equiv_Fr (p : a₁ = a₂) (q : b = f a₁) (r : b = f a₂) : q =[p] r ≃ q ⬝ ap f p = r := /-(λx, b = f x)-/ by induction p; apply pathover_idp definition pathover_eq_equiv_FlFr (p : a₁ = a₂) (q : f a₁ = g a₁) (r : f a₂ = g a₂) : q =[p] r ≃ q ⬝ ap g p = ap f p ⬝ r := /-(λx, f x = g x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition pathover_eq_equiv_FFlr (p : a₁ = a₂) (q : h (f a₁) = a₁) (r : h (f a₂) = a₂) : q =[p] r ≃ q ⬝ p = ap h (ap f p) ⬝ r := /-(λx, h (f x) = x)-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ definition pathover_eq_equiv_lFFr (p : a₁ = a₂) (q : a₁ = h (f a₁)) (r : a₂ = h (f a₂)) : q =[p] r ≃ q ⬝ ap h (ap f p) = p ⬝ r := /-(λx, x = h (f x))-/ by induction p; exact !pathover_idp ⬝e !equiv_eq_closed_right !idp_con⁻¹ -- a lot of this library still needs to be ported from Coq HoTT -- the behavior of equality in other types is described in the corresponding type files -- encode decode method open is_trunc definition encode_decode_method' (a₀ a : A) (code : A → Type) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) (decode_encode : decode a₀ c₀ = idp) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { intro p, exact p ▸ c₀}, { apply decode}, { intro c, apply tr_eq_of_pathover, apply encode_decode}, { intro p, induction p, apply decode_encode}, end end section parameters {A : Type} (a₀ : A) (code : A → Type) (H : is_contr (Σa, code a)) (p : (center (Σa, code a)).1 = a₀) include p definition encode {a : A} (q : a₀ = a) : code a := (p ⬝ q) ▸ (center (Σa, code a)).2 definition decode' {a : A} (c : code a) : a₀ = a := (is_prop.elim ⟨a₀, encode idp⟩ ⟨a, c⟩)..1 definition decode {a : A} (c : code a) : a₀ = a := (decode' (encode idp))⁻¹ ⬝ decode' c definition total_space_method (a : A) : (a₀ = a) ≃ code a := begin fapply equiv.MK, { exact encode}, { exact decode}, { intro c, unfold [encode, decode, decode'], induction p, esimp, rewrite [is_prop_elim_self,▸*,+idp_con], apply tr_eq_of_pathover, eapply @sigma.rec_on _ _ (λx, x.2 =[(is_prop.elim ⟨x.1, x.2⟩ ⟨a, c⟩)..1] c) (center (sigma code)), -- BUG(?): induction fails intro a c, apply eq_pr2}, { intro q, induction q, esimp, apply con.left_inv, }, end end definition encode_decode_method {A : Type} (a₀ a : A) (code : A → Type) (c₀ : code a₀) (decode : Π(a : A) (c : code a), a₀ = a) (encode_decode : Π(a : A) (c : code a), c₀ =[decode a c] c) : (a₀ = a) ≃ code a := begin fapply total_space_method, { fapply @is_contr.mk, { exact ⟨a₀, c₀⟩}, { intro p, fapply sigma_eq, apply decode, exact p.2, apply encode_decode}}, { reflexivity} end end eq
cb9350b51b11059e689654a716556c6f15c2bcd4
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/measure_theory/giry_monad.lean
63b63487f6e4610838928a61645ae2ddd5df6d14
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
7,983
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 -/ import measure_theory.integration /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `Measure : Meas ⥤ Meas`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ noncomputable theory open_locale classical big_operators open classical set filter variables {α β γ δ ε : Type*} namespace measure_theory namespace measure variables [measurable_space α] [measurable_space β] /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ instance : measurable_space (measure α) := ⨆ (s : set α) (hs : is_measurable s), (borel ennreal).comap (λμ, μ s) lemma measurable_coe {s : set α} (hs : is_measurable s) : measurable (λμ : measure α, μ s) := measurable.of_comap_le $ le_supr_of_le s $ le_supr_of_le hs $ le_refl _ lemma measurable_of_measurable_coe (f : β → measure α) (h : ∀(s : set α) (hs : is_measurable s), measurable (λb, f b s)) : measurable f := measurable.of_le_map $ supr_le $ assume s, supr_le $ assume hs, measurable_space.comap_le_iff_le_map.2 $ by rw [measurable_space.map_comp]; exact h s hs lemma measurable_map (f : α → β) (hf : measurable f) : measurable (λμ : measure α, map f μ) := measurable_of_measurable_coe _ $ assume s hs, suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)), by simpa [map_apply, hs, hf], measurable_coe (hf hs) lemma measurable_dirac : measurable (measure.dirac : α → measure α) := measurable_of_measurable_coe _ $ assume s hs, begin simp only [dirac_apply, hs], exact measurable_one.indicator hs end lemma measurable_lintegral {f : α → ennreal} (hf : measurable f) : measurable (λμ : measure α, ∫⁻ x, f x ∂μ) := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, simple_func.lintegral], refine measurable_supr (λ n, finset.measurable_sum _ (λ i, _)), refine measurable_const.ennreal_mul _, exact measurable_coe ((simple_func.eapprox f n).is_measurable_preimage _) end /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join (m : measure (measure α)) : measure α := measure.of_measurable (λs hs, ∫⁻ μ, μ s ∂m) (by simp) begin assume f hf h, simp [measure_Union h hf], apply lintegral_tsum, assume i, exact measurable_coe (hf i) end @[simp] lemma join_apply {m : measure (measure α)} : ∀{s : set α}, is_measurable s → join m s = ∫⁻ μ, μ s ∂m := measure.of_measurable_apply lemma measurable_join : measurable (join : measure (measure α) → measure α) := measurable_of_measurable_coe _ $ assume s hs, by simp only [join_apply hs]; exact measurable_lintegral (measurable_coe hs) lemma lintegral_join {m : measure (measure α)} {f : α → ennreal} (hf : measurable f) : ∫⁻ x, f x ∂(join m) = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m := begin rw [lintegral_eq_supr_eapprox_lintegral hf], have : ∀n x, join m (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) = ∫⁻ μ, μ ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x})) ∂m := assume n x, join_apply (simple_func.is_measurable_preimage _ _), simp only [simple_func.lintegral, this], transitivity, have : ∀(s : ℕ → finset ennreal) (f : ℕ → ennreal → measure α → ennreal) (hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)), (⨆n:ℕ, ∑ r in s n, r * ∫⁻ μ, f n r μ ∂m) = ∫⁻ μ, ⨆n:ℕ, ∑ r in s n, r * f n r μ ∂m, { assume s f hf hm, symmetry, transitivity, apply lintegral_supr, { assume n, exact finset.measurable_sum _ (assume r, measurable_const.ennreal_mul (hf _ _)) }, { exact hm }, congr, funext n, transitivity, apply lintegral_finset_sum, { assume r, exact measurable_const.ennreal_mul (hf _ _) }, congr, funext r, apply lintegral_const_mul, exact hf _ _ }, specialize this (λn, simple_func.range (simple_func.eapprox f n)), specialize this (λn r μ, μ (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})), refine this _ _; clear this, { assume n r, apply measurable_coe, exact simple_func.is_measurable_preimage _ _ }, { change monotone (λn μ, (simple_func.eapprox f n).lintegral μ), assume n m h μ, refine simple_func.lintegral_mono _ (le_refl _), apply simple_func.monotone_eapprox, assumption }, congr, funext μ, symmetry, apply lintegral_eq_supr_eapprox_lintegral, exact hf end /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : measure α) (f : α → measure β) : measure β := join (map f m) @[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β} (hs : is_measurable s) (hf : measurable f) : bind m f s = ∫⁻ a, f a s ∂m := by rw [bind, join_apply hs, lintegral_map (measurable_coe hs) hf] lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) := measurable_join.comp (measurable_map _ hg) lemma lintegral_bind {m : measure α} {μ : α → measure β} {f : β → ennreal} (hμ : measurable μ) (hf : measurable f) : ∫⁻ x, f x ∂ (bind m μ) = ∫⁻ a, ∫⁻ x, f x ∂(μ a) ∂m:= (lintegral_join hf).trans (lintegral_map (measurable_lintegral hf) hμ) lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m (λa, bind (f a) g) := measure.ext $ assume s hs, begin rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), lintegral_bind hf], { congr, funext a, exact (bind_apply hs hg).symm }, exact (measurable_coe hs).comp hg end lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := measure.ext $ assume s hs, by rw [bind_apply hs hf, lintegral_dirac a ((measurable_coe hs).comp hf)] lemma dirac_bind {m : measure α} : bind m dirac = m := measure.ext $ assume s hs, by simp [bind_apply hs measurable_dirac, dirac_apply _ hs, lintegral_indicator 1 hs] lemma map_dirac {f : α → β} (hf : measurable f) (a : α) : map f (dirac a) = dirac (f a) := measure.ext $ assume s hs, by simp [hs, map_apply hf hs, hf hs, indicator_apply] lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id := by rw [bind, map_id] lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) : join (map (map f) μ) = map f (join μ) := measure.ext $ assume s hs, begin rw [join_apply hs, map_apply hf hs, join_apply, lintegral_map (measurable_coe hs) (measurable_map f hf)], { congr, funext ν, exact map_apply hf hs }, exact hf hs end lemma join_map_join (μ : measure (measure (measure α))) : join (map join μ) = join (join μ) := begin show bind μ join = join (join μ), rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id], apply congr_arg (bind μ), funext ν, exact join_eq_bind ν end lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ := dirac_bind lemma join_dirac (μ : measure α) : join (dirac μ) = μ := eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _) end measure end measure_theory
4084dbd1771750aef0cebda647be36dde38e4b3d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Data/Nat/Div.lean
821b0b26dd5b7c65462eca6d72e24efe0365d7b1
[ "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
4,822
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.WF import Init.Data.Nat.Basic namespace Nat private def div_rec_lemma {x y : Nat} : 0 < y ∧ y ≤ x → x - y < x := fun ⟨ypos, ylex⟩ => subLt (Nat.ltOfLtOfLe ypos ylex) ypos private def div.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y + 1 else zero @[extern "lean_nat_div"] protected def div (a b : @& Nat) : Nat := WellFounded.fix ltWf div.F a b instance : Div Nat := ⟨Nat.div⟩ private theorem div_eq_aux (x y : Nat) : x / y = if h : 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := congrFun (WellFounded.fixEq ltWf div.F x) y theorem div_eq (x y : Nat) : x / y = if 0 < y ∧ y ≤ x then (x - y) / y + 1 else 0 := difEqIf (0 < y ∧ y ≤ x) ((x - y) / y + 1) 0 ▸ div_eq_aux x y private theorem div.induction.F.{u} (C : Nat → Nat → Sort u) (ind : ∀ x y, 0 < y ∧ y ≤ x → C (x - y) y → C x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → C x y) (x : Nat) (f : ∀ (x₁ : Nat), x₁ < x → ∀ (y : Nat), C x₁ y) (y : Nat) : C x y := if h : 0 < y ∧ y ≤ x then ind x y h (f (x - y) (div_rec_lemma h) y) else base x y h theorem div.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := WellFounded.fix Nat.ltWf (div.induction.F motive ind base) x y private def mod.F (x : Nat) (f : ∀ x₁, x₁ < x → Nat → Nat) (y : Nat) : Nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y else x @[extern "lean_nat_mod"] protected def mod (a b : @& Nat) : Nat := WellFounded.fix ltWf mod.F a b instance : Mod Nat := ⟨Nat.mod⟩ private theorem mod_eq_aux (x y : Nat) : x % y = if h : 0 < y ∧ y ≤ x then (x - y) % y else x := congrFun (WellFounded.fixEq ltWf mod.F x) y theorem mod_eq (x y : Nat) : x % y = if 0 < y ∧ y ≤ x then (x - y) % y else x := difEqIf (0 < y ∧ y ≤ x) ((x - y) % y) x ▸ mod_eq_aux x y theorem mod.inductionOn.{u} {motive : Nat → Nat → Sort u} (x y : Nat) (ind : ∀ x y, 0 < y ∧ y ≤ x → motive (x - y) y → motive x y) (base : ∀ x y, ¬(0 < y ∧ y ≤ x) → motive x y) : motive x y := div.inductionOn x y ind base theorem mod_zero (a : Nat) : a % 0 = a := have (if 0 < 0 ∧ 0 ≤ a then (a - 0) % 0 else a) = a from have h : ¬ (0 < 0 ∧ 0 ≤ a) from fun ⟨h₁, _⟩ => absurd h₁ (Nat.ltIrrefl _) ifNeg h (mod_eq a 0).symm ▸ this theorem mod_eq_of_lt {a b : Nat} (h : a < b) : a % b = a := have (if 0 < b ∧ b ≤ a then (a - b) % b else a) = a from have h' : ¬(0 < b ∧ b ≤ a) from fun ⟨_, h₁⟩ => absurd h₁ (Nat.notLeOfGt h) ifNeg h' (mod_eq a b).symm ▸ this theorem mod_eq_sub_mod {a b : Nat} (h : a ≥ b) : a % b = (a - b) % b := match eqZeroOrPos b with | Or.inl h₁ => h₁.symm ▸ (Nat.sub_zero a).symm ▸ rfl | Or.inr h₁ => (mod_eq a b).symm ▸ ifPos ⟨h₁, h⟩ theorem mod_lt (x : Nat) {y : Nat} : y > 0 → x % y < y := by refine mod.inductionOn (motive := fun x y => y > 0 → x % y < y) x y ?k1 ?k2 case k1 => intro x y ⟨_, h₁⟩ h₂ h₃ rw [mod_eq_sub_mod h₁] exact h₂ h₃ case k2 => intro x y h₁ h₂ have h₁ : ¬ 0 < y ∨ ¬ y ≤ x from Iff.mp (Decidable.notAndIffOrNot _ _) h₁ match h₁ with | Or.inl h₁ => exact absurd h₂ h₁ | Or.inr h₁ => have hgt : y > x from gtOfNotLe h₁ have heq : x % y = x from mod_eq_of_lt hgt rw [← heq] at hgt exact hgt theorem mod_le (x y : Nat) : x % y ≤ x := by match Nat.ltOrGe x y with | Or.inl h₁ => rw [mod_eq_of_lt h₁]; apply Nat.leRefl | Or.inr h₁ => match eqZeroOrPos y with | Or.inl h₂ => rw [h₂, Nat.mod_zero x]; apply Nat.leRefl | Or.inr h₂ => exact Nat.leTrans (Nat.leOfLt (mod_lt _ h₂)) h₁ @[simp] theorem zero_mod (b : Nat) : 0 % b = 0 := by rw [mod_eq] have ¬ (0 < b ∧ b ≤ 0) by intro ⟨h₁, h₂⟩ exact absurd (Nat.ltOfLtOfLe h₁ h₂) (Nat.ltIrrefl 0) simp [this] @[simp] theorem mod_self (n : Nat) : n % n = 0 := by rw [mod_eq_sub_mod (Nat.leRefl _), Nat.sub_self, zero_mod] theorem mod_one (x : Nat) : x % 1 = 0 := by have h : x % 1 < 1 from mod_lt x (by decide) have (y : Nat) → y < 1 → y = 0 by intro y cases y with | zero => intro h; rfl | succ y => intro h; apply absurd (Nat.lt_of_succ_lt_succ h) (Nat.notLtZero y) exact this _ h end Nat
87a0f19d7b59c146d53e8aeea1a297dd15011629
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/uniform_space/pi.lean
68bb7a6f33c0de556f6c05bc384814d1b4c1c752
[ "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
1,768
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.cauchy import topology.uniform_space.separation /-! # Indexed product of uniform spaces -/ noncomputable theory open_locale uniformity topological_space section open filter uniform_space universe u variables {ι : Type*} (α : ι → Type u) [U : Πi, uniform_space (α i)] include U instance Pi.uniform_space : uniform_space (Πi, α i) := uniform_space.of_core_eq (⨅i, uniform_space.comap (λ a : Πi, α i, a i) (U i)).to_core Pi.topological_space $ eq.symm to_topological_space_infi lemma Pi.uniformity : 𝓤 (Π i, α i) = ⨅ i : ι, filter.comap (λ a, (a.1 i, a.2 i)) $ 𝓤 (α i) := infi_uniformity lemma Pi.uniform_continuous_proj (i : ι) : uniform_continuous (λ (a : Π (i : ι), α i), a i) := begin rw uniform_continuous_iff, exact infi_le (λ j, uniform_space.comap (λ (a : Π (i : ι), α i), a j) (U j)) i end instance Pi.complete [∀ i, complete_space (α i)] : complete_space (Π i, α i) := ⟨begin intros f hf, haveI := hf.1, have : ∀ i, ∃ x : α i, filter.map (λ a : Πi, α i, a i) f ≤ 𝓝 x, { intro i, have key : cauchy (map (λ (a : Π (i : ι), α i), a i) f), from hf.map (Pi.uniform_continuous_proj α i), exact cauchy_iff_exists_le_nhds.1 key }, choose x hx using this, use x, rw [nhds_pi, le_infi_iff], exact λ i, map_le_iff_le_comap.mp (hx i), end⟩ instance Pi.separated [∀ i, separated_space (α i)] : separated_space (Π i, α i) := separated_def.2 $ assume x y H, begin ext i, apply eq_of_separated_of_uniform_continuous (Pi.uniform_continuous_proj α i), apply H, end end
d40b7174ff7135d29d9d80d9898293c52c830c36
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/polynomial/ring_division.lean
a9c8a85e0f496c5c38ad117ffe935875ddf5b649
[ "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
46,077
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, Johan Commelin -/ import algebra.char_zero.infinite import data.polynomial.algebra_map import data.polynomial.degree.lemmas import data.polynomial.div import ring_theory.localization.fraction_ring import algebra.polynomial.big_operators /-! # Theory of univariate polynomials > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file starts looking like the ring theory of $ R[X] $ ## Main definitions * `polynomial.roots p`: The multiset containing all the roots of `p`, including their multiplicities. * `polynomial.root_set p E`: The set of distinct roots of `p` in an algebra `E`. ## Main statements * `polynomial.C_leading_coeff_mul_prod_multiset_X_sub_C`: If a polynomial has as many roots as its degree, it can be written as the product of its leading coefficient with `∏ (X - a)` where `a` ranges through its roots. -/ noncomputable theory open_locale polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {a b : R} {n : ℕ} section comm_ring variables [comm_ring R] {p q : R[X]} section variables [semiring S] lemma nat_degree_pos_of_aeval_root [algebra R S] {p : R[X]} (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 : R[X]} (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) lemma mod_by_monic_eq_of_dvd_sub (hq : q.monic) {p₁ p₂ : R[X]} (h : q ∣ (p₁ - p₂)) : p₁ %ₘ q = p₂ %ₘ q := begin nontriviality R, obtain ⟨f, sub_eq⟩ := h, refine (div_mod_by_monic_unique (p₂ /ₘ q + f) _ hq ⟨_, degree_mod_by_monic_lt _ hq⟩).2, rw [sub_eq_iff_eq_add.mp sub_eq, mul_add, ← add_assoc, mod_by_monic_add_div _ hq, add_comm] end lemma add_mod_by_monic (p₁ p₂ : R[X]) : (p₁ + p₂) %ₘ q = p₁ %ₘ q + p₂ %ₘ q := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (p₁ /ₘ q + p₂ /ₘ q) _ hq ⟨by rw [mul_add, add_left_comm, add_assoc, mod_by_monic_add_div _ hq, ← add_assoc, add_comm (q * _), mod_by_monic_add_div _ hq], (degree_add_le _ _).trans_lt (max_lt (degree_mod_by_monic_lt _ hq) (degree_mod_by_monic_lt _ hq))⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end lemma smul_mod_by_monic (c : R) (p : R[X]) : (c • p) %ₘ q = c • (p %ₘ q) := begin by_cases hq : q.monic, { nontriviality R, exact (div_mod_by_monic_unique (c • (p /ₘ q)) (c • (p %ₘ q)) hq ⟨by rw [mul_smul_comm, ← smul_add, mod_by_monic_add_div p hq], (degree_smul_le _ _).trans_lt (degree_mod_by_monic_lt _ hq)⟩).2 }, { simp_rw mod_by_monic_eq_of_not_monic _ hq } end /-- `_ %ₘ q` as an `R`-linear map. -/ @[simps] def mod_by_monic_hom (q : R[X]) : R[X] →ₗ[R] R[X] := { to_fun := λ p, p %ₘ q, map_add' := add_mod_by_monic, map_smul' := smul_mod_by_monic } end section variables [ring S] lemma aeval_mod_by_monic_eq_self_of_root [algebra R S] {p q : R[X]} (hq : q.monic) {x : S} (hx : aeval x q = 0) : aeval x (p %ₘ q) = aeval x p := -- `eval₂_mod_by_monic_eq_self_of_root` doesn't work here as it needs commutativity by rw [mod_by_monic_eq_sub_mul_div p hq, _root_.map_sub, _root_.map_mul, hx, zero_mul, sub_zero] end end comm_ring section no_zero_divisors variables [semiring R] [no_zero_divisors R] {p q : R[X]} instance : no_zero_divisors R[X] := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], refine eq_zero_or_eq_zero_of_mul_eq_zero _, rw [← leading_coeff_zero, ← leading_coeff_mul, h], end } 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] lemma trailing_degree_mul : (p * q).trailing_degree = p.trailing_degree + q.trailing_degree := begin by_cases hp : p = 0, { rw [hp, zero_mul, trailing_degree_zero, top_add] }, by_cases hq : q = 0, { rw [hq, mul_zero, trailing_degree_zero, add_top] }, rw [trailing_degree_eq_nat_trailing_degree hp, trailing_degree_eq_nat_trailing_degree hq, trailing_degree_eq_nat_trailing_degree (mul_ne_zero hp hq), nat_trailing_degree_mul hp hq, with_top.coe_add], end @[simp] lemma nat_degree_pow (p : R[X]) (n : ℕ) : nat_degree (p ^ n) = n * nat_degree p := by classical; exact 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 degree_le_mul_left (p : R[X]) (hq : q ≠ 0) : degree p ≤ degree (p * q) := by classical; exact 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 : R[X]} (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 degree_le_of_dvd {p q : R[X]} (h1 : p ∣ q) (h2 : q ≠ 0) : degree p ≤ degree q := begin rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2, exact degree_le_mul_left p h2.2, end lemma eq_zero_of_dvd_of_degree_lt {p q : R[X]} (h₁ : p ∣ q) (h₂ : degree q < degree p) : q = 0 := begin by_contradiction hc, exact (lt_iff_not_ge _ _ ).mp h₂ (degree_le_of_dvd h₁ hc), end lemma eq_zero_of_dvd_of_nat_degree_lt {p q : R[X]} (h₁ : p ∣ q) (h₂ : nat_degree q < nat_degree p) : q = 0 := begin by_contradiction hc, exact (lt_iff_not_ge _ _ ).mp h₂ (nat_degree_le_of_dvd h₁ hc), end theorem not_dvd_of_degree_lt {p q : R[X]} (h0 : q ≠ 0) (hl : q.degree < p.degree) : ¬ p ∣ q := begin by_contra hcontra, exact h0 (eq_zero_of_dvd_of_degree_lt hcontra hl), end theorem not_dvd_of_nat_degree_lt {p q : R[X]} (h0 : q ≠ 0) (hl : q.nat_degree < p.nat_degree) : ¬ p ∣ q := begin by_contra hcontra, exact h0 (eq_zero_of_dvd_of_nat_degree_lt hcontra hl), end /-- This lemma is useful for working with the `int_degree` of a rational function. -/ lemma nat_degree_sub_eq_of_prod_eq {p₁ p₂ q₁ q₂ : R[X]} (hp₁ : p₁ ≠ 0) (hq₁ : q₁ ≠ 0) (hp₂ : p₂ ≠ 0) (hq₂ : q₂ ≠ 0) (h_eq : p₁ * q₂ = p₂ * q₁) : (p₁.nat_degree : ℤ) - q₁.nat_degree = (p₂.nat_degree : ℤ) - q₂.nat_degree := begin rw sub_eq_sub_iff_add_eq_add, norm_cast, rw [← nat_degree_mul hp₁ hq₂, ← nat_degree_mul hp₂ hq₁, h_eq] end lemma nat_degree_eq_zero_of_is_unit (h : is_unit p) : nat_degree p = 0 := begin nontriviality R, obtain ⟨q, hq⟩ := h.exists_right_inv, have := nat_degree_mul (left_ne_zero_of_mul_eq_one hq) (right_ne_zero_of_mul_eq_one hq), rw [hq, nat_degree_one, eq_comm, add_eq_zero_iff] at this, exact this.1, end lemma degree_eq_zero_of_is_unit [nontrivial R] (h : is_unit p) : degree p = 0 := (nat_degree_eq_zero_iff_degree_le_zero.mp $ nat_degree_eq_zero_of_is_unit h).antisymm (zero_le_degree_iff.mpr h.ne_zero) @[simp] lemma degree_coe_units [nontrivial R] (u : R[X]ˣ) : degree (u : R[X]) = 0 := degree_eq_zero_of_is_unit ⟨u, rfl⟩ theorem is_unit_iff : is_unit p ↔ ∃ r : R, is_unit r ∧ C r = p := ⟨λ hp, ⟨p.coeff 0, let h := eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_is_unit hp) in ⟨is_unit_C.1 (h ▸ hp), h.symm⟩⟩, λ ⟨r, hr, hrp⟩, hrp ▸ is_unit_C.2 hr⟩ variables [char_zero R] @[simp] lemma degree_bit0_eq (p : R[X]) : degree (bit0 p) = degree p := by rw [bit0_eq_two_mul, degree_mul, (by simp : (2 : R[X]) = C 2), @polynomial.degree_C R _ _ two_ne_zero, zero_add] @[simp] lemma nat_degree_bit0_eq (p : R[X]) : nat_degree (bit0 p) = nat_degree p := nat_degree_eq_of_degree_eq $ degree_bit0_eq p @[simp] lemma nat_degree_bit1_eq (p : R[X]) : nat_degree (bit1 p) = nat_degree p := begin rw bit1, apply le_antisymm, convert nat_degree_add_le _ _, { simp, }, by_cases h : p.nat_degree = 0, { simp [h], }, apply le_nat_degree_of_ne_zero, intro hh, apply h, simp [*, coeff_one, if_neg (ne.symm h)] at *, end lemma degree_bit1_eq {p : R[X]} (hp : 0 < degree p) : degree (bit1 p) = degree p := begin rw [bit1, degree_add_eq_left_of_degree_lt, degree_bit0_eq], rwa [degree_one, degree_bit0_eq] end end no_zero_divisors section no_zero_divisors variables [comm_semiring R] [no_zero_divisors R] {p q : R[X]} lemma irreducible_of_monic (hp : p.monic) (hp1 : p ≠ 1) : irreducible p ↔ ∀ f g : R[X], f.monic → g.monic → f * g = p → f = 1 ∨ g = 1 := begin refine ⟨λ h f g hf hg hp, (h.2 f g hp.symm).imp hf.eq_one_of_is_unit hg.eq_one_of_is_unit, λ h, ⟨hp1 ∘ hp.eq_one_of_is_unit, λ f g hfg, (h (g * C f.leading_coeff) (f * C g.leading_coeff) _ _ _).symm.imp (is_unit_of_mul_eq_one f _) (is_unit_of_mul_eq_one g _)⟩⟩, { rwa [monic, leading_coeff_mul, leading_coeff_C, ←leading_coeff_mul, mul_comm, ←hfg, ←monic] }, { rwa [monic, leading_coeff_mul, leading_coeff_C, ←leading_coeff_mul, ←hfg, ←monic] }, { rw [mul_mul_mul_comm, ←C_mul, ←leading_coeff_mul, ←hfg, hp.leading_coeff, C_1, mul_one, mul_comm, ←hfg] }, end lemma monic.irreducible_iff_nat_degree (hp : p.monic) : irreducible p ↔ p ≠ 1 ∧ ∀ f g : R[X], f.monic → g.monic → f * g = p → f.nat_degree = 0 ∨ g.nat_degree = 0 := begin by_cases hp1 : p = 1, { simp [hp1] }, rw [irreducible_of_monic hp hp1, and_iff_right hp1], refine forall₄_congr (λ a b ha hb, _), rw [ha.nat_degree_eq_zero_iff_eq_one, hb.nat_degree_eq_zero_iff_eq_one], end lemma monic.irreducible_iff_nat_degree' (hp : p.monic) : irreducible p ↔ p ≠ 1 ∧ ∀ f g : R[X], f.monic → g.monic → f * g = p → g.nat_degree ∉ Ioc 0 (p.nat_degree / 2) := begin simp_rw [hp.irreducible_iff_nat_degree, mem_Ioc, nat.le_div_iff_mul_le zero_lt_two, mul_two], apply and_congr_right', split; intros h f g hf hg he; subst he, { rw [hf.nat_degree_mul hg, add_le_add_iff_right], exact λ ha, (h f g hf hg rfl).elim (ha.1.trans_le ha.2).ne' ha.1.ne' }, { simp_rw [hf.nat_degree_mul hg, pos_iff_ne_zero] at h, contrapose! h, obtain hl|hl := le_total f.nat_degree g.nat_degree, { exact ⟨g, f, hg, hf, mul_comm g f, h.1, add_le_add_left hl _⟩ }, { exact ⟨f, g, hf, hg, rfl, h.2, add_le_add_right hl _⟩ } }, end lemma monic.not_irreducible_iff_exists_add_mul_eq_coeff (hm : p.monic) (hnd : p.nat_degree = 2) : ¬ irreducible p ↔ ∃ c₁ c₂, p.coeff 0 = c₁ * c₂ ∧ p.coeff 1 = c₁ + c₂ := begin casesI subsingleton_or_nontrivial R, { simpa only [nat_degree_of_subsingleton] using hnd }, rw [hm.irreducible_iff_nat_degree', and_iff_right, hnd], push_neg, split, { rintros ⟨a, b, ha, hb, rfl, hdb|⟨⟨⟩⟩⟩, have hda := hnd, rw [ha.nat_degree_mul hb, hdb] at hda, use [a.coeff 0, b.coeff 0, mul_coeff_zero a b], simpa only [next_coeff, hnd, add_right_cancel hda, hdb] using ha.next_coeff_mul hb }, { rintros ⟨c₁, c₂, hmul, hadd⟩, refine ⟨X + C c₁, X + C c₂, monic_X_add_C _, monic_X_add_C _, _, or.inl $ nat_degree_X_add_C _⟩, rw [p.as_sum_range_C_mul_X_pow, hnd, finset.sum_range_succ, finset.sum_range_succ, finset.sum_range_one, ← hnd, hm.coeff_nat_degree, hnd, hmul, hadd, C_mul, C_add, C_1], ring }, { rintro rfl, simpa only [nat_degree_one] using hnd }, end 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 end no_zero_divisors section ring variables [ring R] [is_domain R] {p q : R[X]} instance : is_domain R[X] := no_zero_divisors.to_is_domain _ end ring section comm_ring variable [comm_ring R] /-- The multiplicity of `a` as root of a nonzero polynomial `p` is at least `n` iff `(X - a) ^ n` divides `p`. -/ lemma le_root_multiplicity_iff {p : R[X]} (p0 : p ≠ 0) {a : R} {n : ℕ} : n ≤ root_multiplicity a p ↔ (X - C a) ^ n ∣ p := begin classical, simp_rw [root_multiplicity, dif_neg p0, nat.le_find_iff, not_not], refine ⟨λ h, _, λ h m hm, (pow_dvd_pow _ hm).trans h⟩, cases n, { rw pow_zero, apply one_dvd }, { exact h n n.lt_succ_self }, end lemma root_multiplicity_le_iff {p : R[X]} (p0 : p ≠ 0) (a : R) (n : ℕ) : root_multiplicity a p ≤ n ↔ ¬ (X - C a) ^ (n + 1) ∣ p := by rw [← (le_root_multiplicity_iff p0).not, not_le, nat.lt_add_one_iff] lemma pow_root_multiplicity_not_dvd {p : R[X]} (p0 : p ≠ 0) (a : R) : ¬ (X - C a) ^ (root_multiplicity a p + 1) ∣ p := by rw [← root_multiplicity_le_iff p0] /-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/ lemma root_multiplicity_add {p q : R[X]} (a : R) (hzero : p + q ≠ 0) : min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) := begin rw le_root_multiplicity_iff hzero, have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a, have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a, exact min_pow_dvd_add hdivp hdivq end variables [is_domain R] {p q : R[X]} section roots open multiset theorem prime_X_sub_C (r : R) : prime (X - C r) := ⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C r, λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩ theorem prime_X : prime (X : R[X]) := by { convert (prime_X_sub_C (0 : R)), simp } lemma monic.prime_of_degree_eq_one (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) := (prime_X_sub_C r).irreducible theorem irreducible_X : irreducible (X : R[X]) := prime.irreducible prime_X lemma monic.irreducible_of_degree_eq_one (hp1 : degree p = 1) (hm : monic p) : irreducible p := (hm.prime_of_degree_eq_one hp1).irreducible theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q := begin obtain ⟨u, hu⟩ := hpq, unfold monic at hp hq, rw eq_C_of_degree_le_zero (degree_coe_units _).le at hu, rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq, rwa [hq, C_1, mul_one] at hu, all_goals { apply_instance }, end lemma root_multiplicity_mul {p q : R[X]} {x : R} (hpq : p * q ≠ 0) : root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q := begin classical, have hp : p ≠ 0 := left_ne_zero_of_mul hpq, have hq : q ≠ 0 := right_ne_zero_of_mul hpq, rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq, root_multiplicity_eq_multiplicity p, dif_neg hp, root_multiplicity_eq_multiplicity q, dif_neg hq, multiplicity.mul' (prime_X_sub_C x)], end lemma root_multiplicity_X_sub_C_self {x : R} : root_multiplicity x (X - C x) = 1 := by classical; rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x), multiplicity.get_multiplicity_self] lemma root_multiplicity_X_sub_C {x y : R} [decidable_eq R] : root_multiplicity x (X - C y) = if x = y then 1 else 0 := begin split_ifs with hxy, { rw hxy, exact root_multiplicity_X_sub_C_self }, exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy)) end /-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/ lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n := begin induction n with n hn, { refine root_multiplicity_eq_zero _, simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] }, have hzero := pow_ne_zero n.succ (X_sub_C_ne_zero a), rw pow_succ (X - C a) n at hzero ⊢, simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add] end lemma exists_multiset_roots [decidable_eq R] : ∀ {p : R[X]} (hp : p ≠ 0), ∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p | 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_multiset_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)).1 $ not_lt.2 hdeg, ⟨x ::ₘ t, calc (card (x ::ₘ t) : with_bot ℕ) = t.card + 1 : by exact_mod_cast card_cons _ _ ... ≤ 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 a, conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx }, rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero x) hdiv0), root_multiplicity_X_sub_C, ← htr a], split_ifs with ha, { rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] }, { rw [count_cons_of_ne ha, zero_add] }, end⟩ else ⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a multiset containing all the roots of `p`, including their multiplicities. -/ noncomputable def roots (p : R[X]) : multiset R := by haveI := classical.dec_eq R; haveI := classical.dec (p = 0); exact if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) lemma roots_def [decidable_eq R] (p : R[X]) [decidable (p = 0)] : p.roots = if h : p = 0 then ∅ else classical.some (exists_multiset_roots h) := begin unfreezingI { obtain rfl := subsingleton.elim ‹_› (classical.dec_eq R), obtain rfl := subsingleton.elim ‹_› (classical.dec (p = 0)),}, refl, end @[simp] lemma roots_zero : (0 : R[X]).roots = 0 := by apply dif_pos rfl lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin classical, unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_multiset_roots hp0)).1 end lemma card_roots' (p : R[X]) : p.roots.card ≤ nat_degree p := begin by_cases hp0 : p = 0, { simp [hp0], }, exact with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0)) end lemma card_roots_sub_C {p : R[X]} {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 : R[X]} {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 count_roots [decidable_eq R] (p : R[X]) : p.roots.count a = root_multiplicity a p := begin classical, by_cases hp : p = 0, { simp [hp], }, rw [roots_def, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a, end @[simp] lemma mem_roots' : a ∈ p.roots ↔ p ≠ 0 ∧ is_root p a := by classical; rw [← count_pos, count_roots p, root_multiplicity_pos'] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := mem_roots'.trans $ and_iff_right hp lemma ne_zero_of_mem_roots (h : a ∈ p.roots) : p ≠ 0 := (mem_roots'.1 h).1 lemma is_root_of_mem_roots (h : a ∈ p.roots) : is_root p a := (mem_roots'.1 h).2 theorem card_le_degree_of_subset_roots {p : R[X]} {Z : finset R} (h : Z.val ⊆ p.roots) : Z.card ≤ p.nat_degree := (multiset.card_le_of_le (finset.val_le_iff_val_subset.2 h)).trans (polynomial.card_roots' p) lemma finite_set_of_is_root {p : R[X]} (hp : p ≠ 0) : set.finite {x | is_root p x} := by classical; simpa only [← finset.set_of_mem, mem_to_finset, mem_roots hp] using p.roots.to_finset.finite_to_set lemma eq_zero_of_infinite_is_root (p : R[X]) (h : set.infinite {x | is_root p x}) : p = 0 := not_imp_comm.mp finite_set_of_is_root h lemma exists_max_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x ≤ x₀ := set.exists_upper_bound_image _ _ $ finite_set_of_is_root hp lemma exists_min_root [linear_order R] (p : R[X]) (hp : p ≠ 0) : ∃ x₀, ∀ x, p.is_root x → x₀ ≤ x := set.exists_lower_bound_image _ _ $ finite_set_of_is_root hp lemma eq_of_infinite_eval_eq (p q : R[X]) (h : set.infinite {x | eval x p = eval x q}) : p = q := begin rw [← sub_eq_zero], apply eq_zero_of_infinite_is_root, simpa only [is_root, eval_sub, sub_eq_zero] end lemma roots_mul {p q : R[X]} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots := by classical; exact (multiset.ext.mpr $ λ r, by rw [count_add, count_roots, count_roots, count_roots, root_multiplicity_mul hpq]) lemma roots.le_of_dvd (h : q ≠ 0) : p ∣ q → roots p ≤ roots q := begin rintro ⟨k, rfl⟩, exact multiset.le_iff_exists_add.mpr ⟨k.roots, roots_mul h⟩ end lemma mem_roots_sub_C' {p : R[X]} {a x : R} : x ∈ (p - C a).roots ↔ p ≠ C a ∧ p.eval x = a := by rw [mem_roots', is_root.def, sub_ne_zero, eval_sub, sub_eq_zero, eval_C] lemma mem_roots_sub_C {p : R[X]} {a x : R} (hp0 : 0 < degree p) : x ∈ (p - C a).roots ↔ p.eval x = a := mem_roots_sub_C'.trans $ and_iff_right $ λ hp, hp0.not_le $ hp.symm ▸ degree_C_le @[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = {r} := begin classical, ext s, rw [count_roots, root_multiplicity_X_sub_C, count_singleton], end @[simp] lemma roots_X : roots (X : R[X]) = {0} := by rw [← roots_X_sub_C, C_0, sub_zero] @[simp] lemma roots_C (x : R) : (C x).roots = 0 := by classical; exact if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r, by rw [count_roots, count_zero, root_multiplicity_eq_zero (not_is_root_C _ _ H)] @[simp] lemma roots_one : (1 : R[X]).roots = ∅ := roots_C 1 @[simp] lemma roots_C_mul (p : R[X]) (ha : a ≠ 0) : (C a * p).roots = p.roots := by by_cases hp : p = 0; simp only [roots_mul, *, ne.def, mul_eq_zero, C_eq_zero, or_self, not_false_iff, roots_C, zero_add, mul_zero] @[simp] lemma roots_smul_nonzero (p : R[X]) (ha : a ≠ 0) : (a • p).roots = p.roots := by rw [smul_eq_C_mul, roots_C_mul _ ha] lemma roots_list_prod (L : list R[X]) : ((0 : R[X]) ∉ L) → L.prod.roots = (L : multiset R[X]).bind roots := list.rec_on L (λ _, roots_one) $ λ hd tl ih H, begin rw [list.mem_cons_iff, not_or_distrib] at H, rw [list.prod_cons, roots_mul (mul_ne_zero (ne.symm H.1) $ list.prod_ne_zero H.2), ← multiset.cons_coe, multiset.cons_bind, ih H.2] end lemma roots_multiset_prod (m : multiset R[X]) : (0 : R[X]) ∉ m → m.prod.roots = m.bind roots := by { rcases m with ⟨L⟩, simpa only [multiset.coe_prod, quot_mk_to_coe''] using roots_list_prod L } lemma roots_prod {ι : Type*} (f : ι → R[X]) (s : finset ι) : s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) := begin rcases s with ⟨m, hm⟩, simpa [multiset.prod_eq_zero_iff, bind_map] using roots_multiset_prod (m.map f) end @[simp] lemma roots_pow (p : R[X]) (n : ℕ) : (p ^ n).roots = n • p.roots := begin induction n with n ihn, { rw [pow_zero, roots_one, zero_smul, empty_eq_zero] }, { rcases eq_or_ne p 0 with rfl | hp, { rw [zero_pow n.succ_pos, roots_zero, smul_zero] }, { rw [pow_succ', roots_mul (mul_ne_zero (pow_ne_zero _ hp) hp), ihn, nat.succ_eq_add_one, add_smul, one_smul] } } end lemma roots_X_pow (n : ℕ) : (X ^ n : R[X]).roots = n • {0} := by rw [roots_pow, roots_X] lemma roots_C_mul_X_pow (ha : a ≠ 0) (n : ℕ) : (C a * X ^ n).roots = n • {0} := by rw [roots_C_mul _ ha, roots_X_pow] @[simp] lemma roots_monomial (ha : a ≠ 0) (n : ℕ) : (monomial n a).roots = n • {0} := by rw [← C_mul_X_pow_eq_monomial, roots_C_mul_X_pow ha] lemma roots_prod_X_sub_C (s : finset R) : (s.prod (λ a, X - C a)).roots = s.val := (roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans (by simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id']) @[simp] lemma roots_multiset_prod_X_sub_C (s : multiset R) : (s.map (λ a, X - C a)).prod.roots = s := begin rw [roots_multiset_prod, multiset.bind_map], { simp_rw [roots_X_sub_C, multiset.bind_singleton, multiset.map_id'] }, { rw [multiset.mem_map], rintro ⟨a, -, h⟩, exact X_sub_C_ne_zero a h }, end @[simp] lemma nat_degree_multiset_prod_X_sub_C_eq_card (s : multiset R): (s.map (λ a, X - C a)).prod.nat_degree = s.card := begin rw [nat_degree_multiset_prod_of_monic, multiset.map_map], { simp only [(∘), nat_degree_X_sub_C, multiset.map_const, multiset.sum_replicate, smul_eq_mul, mul_one] }, { exact multiset.forall_mem_map_iff.2 (λ a _, monic_X_sub_C a) }, end lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) : (roots ((X : R[X]) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : R[X]) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : R[X]) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a section nth_roots /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ def nth_roots (n : ℕ) (a : R) : multiset R := roots ((X : R[X]) ^ n - C a) @[simp] lemma mem_nth_roots {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] @[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 := by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C] lemma card_nth_roots (n : ℕ) (a : R) : (nth_roots n a).card ≤ n := by classical; exactI if hn : n = 0 then if h : (X : R[X]) ^ n - C a = 0 then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, multiset.card_zero] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by { rw [hn, pow_zero, ← C_1, ← ring_hom.map_sub ], 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) @[simp] lemma nth_roots_two_eq_zero_iff {r : R} : nth_roots 2 r = 0 ↔ ¬ is_square r := by simp_rw [is_square_iff_exists_sq, eq_zero_iff_forall_not_mem, mem_nth_roots (by norm_num : 0 < 2), ← not_exists, eq_comm] /-- The multiset `nth_roots ↑n (1 : R)` as a finset. -/ def nth_roots_finset (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : finset R := by haveI := classical.dec_eq R; exact multiset.to_finset (nth_roots n (1 : R)) @[simp] lemma mem_nth_roots_finset {n : ℕ} (h : 0 < n) {x : R} : x ∈ nth_roots_finset n R ↔ x ^ (n : ℕ) = 1 := by rw [nth_roots_finset, mem_to_finset, mem_nth_roots h] @[simp] lemma nth_roots_finset_zero : nth_roots_finset 0 R = ∅ := by simp [nth_roots_finset] end nth_roots lemma monic.comp (hp : p.monic) (hq : q.monic) (h : q.nat_degree ≠ 0) : (p.comp q).monic := by rw [monic.def, leading_coeff_comp h, monic.def.1 hp, monic.def.1 hq, one_pow, one_mul] lemma monic.comp_X_add_C (hp : p.monic) (r : R) : (p.comp (X + C r)).monic := begin refine hp.comp (monic_X_add_C _) (λ ha, _), rw [nat_degree_X_add_C] at ha, exact one_ne_zero ha end lemma monic.comp_X_sub_C (hp : p.monic) (r : R) : (p.comp (X - C r)).monic := by simpa using hp.comp_X_add_C (-r) lemma units_coeff_zero_smul (c : R[X]ˣ) (p : R[X]) : (c : R[X]).coeff 0 • p = c * p := by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)] @[simp] lemma nat_degree_coe_units (u : R[X]ˣ) : nat_degree (u : R[X]) = 0 := nat_degree_eq_of_degree_eq_some (degree_coe_units u) lemma comp_eq_zero_iff : p.comp q = 0 ↔ p = 0 ∨ (p.eval (q.coeff 0) = 0 ∧ q = C (q.coeff 0)) := begin split, { intro h, have key : p.nat_degree = 0 ∨ q.nat_degree = 0, { rw [←mul_eq_zero, ←nat_degree_comp, h, nat_degree_zero] }, replace key := or.imp eq_C_of_nat_degree_eq_zero eq_C_of_nat_degree_eq_zero key, cases key, { rw [key, C_comp] at h, exact or.inl (key.trans h) }, { rw [key, comp_C, C_eq_zero] at h, exact or.inr ⟨h, key⟩ }, }, { exact λ h, or.rec (λ h, by rw [h, zero_comp]) (λ h, by rw [h.2, comp_C, h.1, C_0]) h }, end lemma zero_of_eval_zero [infinite R] (p : R[X]) (h : ∀ x, p.eval x = 0) : p = 0 := by classical; by_contradiction hp; exact fintype.false ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩ lemma funext [infinite R] {p q : R[X]} (ext : ∀ r : R, p.eval r = q.eval r) : p = q := begin rw ← sub_eq_zero, apply zero_of_eval_zero, intro x, rw [eval_sub, sub_eq_zero, ext], end variables [comm_ring T] /-- The set of distinct roots of `p` in `E`. If you have a non-separable polynomial, use `polynomial.roots` for the multiset where multiple roots have the appropriate multiplicity. -/ def root_set (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] : set S := by haveI := classical.dec_eq S; exact (p.map (algebra_map T S)).roots.to_finset lemma root_set_def (p : T[X]) (S) [comm_ring S] [is_domain S] [algebra T S] [decidable_eq S] : p.root_set S = (p.map (algebra_map T S)).roots.to_finset := by convert rfl @[simp] lemma root_set_C [comm_ring S] [is_domain S] [algebra T S] (a : T) : (C a).root_set S = ∅ := by classical; rw [root_set_def, map_C, roots_C, multiset.to_finset_zero, finset.coe_empty] @[simp] lemma root_set_zero (S) [comm_ring S] [is_domain S] [algebra T S] : (0 : T[X]).root_set S = ∅ := by rw [← C_0, root_set_C] instance root_set_fintype (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : fintype (p.root_set S) := finset_coe.fintype _ lemma root_set_finite (p : T[X]) (S : Type*) [comm_ring S] [is_domain S] [algebra T S] : (p.root_set S).finite := set.to_finite _ /-- The set of roots of all polynomials of bounded degree and having coefficients in a finite set is finite. -/ lemma bUnion_roots_finite {R S : Type*} [semiring R] [comm_ring S] [is_domain S] [decidable_eq S] (m : R →+* S) (d : ℕ) {U : set R} (h : U.finite) : (⋃ (f : R[X]) (hf : f.nat_degree ≤ d ∧ ∀ i, (f.coeff i) ∈ U), ((f.map m).roots.to_finset : set S)).finite := set.finite.bUnion begin -- We prove that the set of polynomials under consideration is finite because its -- image by the injective map `π` is finite let π : R[X] → fin (d+1) → R := λ f i, f.coeff i, refine ((set.finite.pi $ λ e, h).subset $ _).of_finite_image (_ : set.inj_on π _), { exact set.image_subset_iff.2 (λ f hf i _, hf.2 i) }, { refine λ x hx y hy hxy, (ext_iff_nat_degree_le hx.1 hy.1).2 (λ i hi, _), exact id congr_fun hxy ⟨i, nat.lt_succ_of_le hi⟩ }, end $ λ i hi, finset.finite_to_set _ theorem mem_root_set' {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] {a : S} : a ∈ p.root_set S ↔ p.map (algebra_map T S) ≠ 0 ∧ aeval a p = 0 := by rw [root_set, finset.mem_coe, mem_to_finset, mem_roots', is_root.def, ← eval₂_eq_eval_map, aeval_def] theorem mem_root_set {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] {a : S} : a ∈ p.root_set S ↔ p ≠ 0 ∧ aeval a p = 0 := by rw [mem_root_set', (map_injective _ (no_zero_smul_divisors.algebra_map_injective T S)).ne_iff' (polynomial.map_zero _)] theorem mem_root_set_of_ne {p : T[X]} {S : Type*} [comm_ring S] [is_domain S] [algebra T S] [no_zero_smul_divisors T S] (hp : p ≠ 0) {a : S} : a ∈ p.root_set S ↔ aeval a p = 0 := mem_root_set.trans $ and_iff_right hp lemma root_set_maps_to' {p : T[X]} {S S'} [comm_ring S] [is_domain S] [algebra T S] [comm_ring S'] [is_domain S'] [algebra T S'] (hp : p.map (algebra_map T S') = 0 → p.map (algebra_map T S) = 0) (f : S →ₐ[T] S') : (p.root_set S).maps_to f (p.root_set S') := λ x hx, begin rw [mem_root_set'] at hx ⊢, rw [aeval_alg_hom, alg_hom.comp_apply, hx.2, _root_.map_zero], exact ⟨mt hp hx.1, rfl⟩ end lemma ne_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] {a : S} (h : a ∈ p.root_set S) : p ≠ 0 := λ hf, by rwa [hf, root_set_zero] at h lemma aeval_eq_zero_of_mem_root_set {p : T[X]} [comm_ring S] [is_domain S] [algebra T S] {a : S} (hx : a ∈ p.root_set S) : aeval a p = 0 := (mem_root_set'.1 hx).2 lemma root_set_maps_to {p : T[X]} {S S'} [comm_ring S] [is_domain S] [algebra T S] [comm_ring S'] [is_domain S'] [algebra T S'] [no_zero_smul_divisors T S'] (f : S →ₐ[T] S') : (p.root_set S).maps_to f (p.root_set S') := begin refine root_set_maps_to' (λ h₀, _) f, obtain rfl : p = 0 := map_injective _ (no_zero_smul_divisors.algebra_map_injective T S') (by rwa [polynomial.map_zero]), exact polynomial.map_zero _ end end roots lemma coeff_coe_units_zero_ne_zero (u : R[X]ˣ) : coeff (u : R[X]) 0 ≠ 0 := begin conv in (0) { rw [← nat_degree_coe_units u] }, rw [← leading_coeff, ne.def, leading_coeff_eq_zero], exact units.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.is_unit_or_is_unit 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]) /-- Division by a monic polynomial doesn't change the leading coefficient. -/ lemma leading_coeff_div_by_monic_of_monic {R : Type u} [comm_ring R] {p q : R[X]} (hmonic : q.monic) (hdegree : q.degree ≤ p.degree) : (p /ₘ q).leading_coeff = p.leading_coeff := begin nontriviality, have h : q.leading_coeff * (p /ₘ q).leading_coeff ≠ 0, { simpa [div_by_monic_eq_zero_iff hmonic, hmonic.leading_coeff, nat.with_bot.one_le_iff_zero_lt] using hdegree }, nth_rewrite_rhs 0 ←mod_by_monic_add_div p hmonic, rw [leading_coeff_add_of_degree_lt, leading_coeff_monic_mul hmonic], rw [degree_mul' h, degree_add_div_by_monic hmonic hdegree], exact (degree_mod_by_monic_lt p hmonic).trans_le hdegree end lemma leading_coeff_div_by_monic_X_sub_C (p : R[X]) (hp : degree p ≠ 0) (a : R) : leading_coeff (p /ₘ (X - C a)) = leading_coeff p := begin nontriviality, cases hp.lt_or_lt with hd hd, { rw [degree_eq_bot.mp $ (nat.with_bot.lt_zero_iff _).mp hd, zero_div_by_monic] }, refine leading_coeff_div_by_monic_of_monic (monic_X_sub_C a) _, rwa [degree_X_sub_C, nat.with_bot.one_le_iff_zero_lt] end lemma eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = C q.leading_coeff * p := begin obtain ⟨r, hr⟩ := hdiv, obtain (rfl|hq) := eq_or_ne q 0, {simp}, have rzero : r ≠ 0 := λ h, by simpa [h, hq] using hr, rw [hr, nat_degree_mul'] at hdeg, swap, { rw [hp.leading_coeff, one_mul, leading_coeff_ne_zero], exact rzero }, rw [mul_comm, @eq_C_of_nat_degree_eq_zero _ _ r] at hr, { convert hr, convert leading_coeff_C _ using 1, rw [hr, leading_coeff_mul_monic hp] }, { exact (add_right_inj _).1 (le_antisymm hdeg $ nat.le.intro rfl) }, end lemma eq_of_monic_of_dvd_of_nat_degree_le {R} [comm_ring R] {p q : R[X]} (hp : p.monic) (hq : q.monic) (hdiv : p ∣ q) (hdeg : q.nat_degree ≤ p.nat_degree) : q = p := begin convert eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le hp hdiv hdeg, rw [hq.leading_coeff, C_1, one_mul], end lemma is_coprime_X_sub_C_of_is_unit_sub {R} [comm_ring R] {a b : R} (h : is_unit (a - b)) : is_coprime (X - C a) (X - C b) := ⟨-C h.unit⁻¹.val, C h.unit⁻¹.val, by { rw [neg_mul_comm, ← left_distrib, neg_add_eq_sub, sub_sub_sub_cancel_left, ← C_sub, ← C_mul], convert C_1, exact h.coe_inv_mul }⟩ theorem pairwise_coprime_X_sub_C {K} [field K] {I : Type v} {s : I → K} (H : function.injective s) : pairwise (is_coprime on (λ i : I, X - C (s i))) := λ i j hij, is_coprime_X_sub_C_of_is_unit_sub (sub_ne_zero_of_ne $ H.ne hij).is_unit lemma monic_prod_multiset_X_sub_C : monic (p.roots.map (λ a, X - C a)).prod := monic_multiset_prod_of_monic _ _ (λ a _, monic_X_sub_C a) lemma prod_multiset_root_eq_finset_root [decidable_eq R] : (p.roots.map (λ a, X - C a)).prod = p.roots.to_finset.prod (λ a, (X - C a) ^ root_multiplicity a p) := by simp only [count_roots, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : R[X]) : (p.roots.map (λ a, X - C a)).prod ∣ p := begin classical, rw ← map_dvd_map _ (is_fraction_ring.injective R $ fraction_ring R) monic_prod_multiset_X_sub_C, rw [prod_multiset_root_eq_finset_root, polynomial.map_prod], refine finset.prod_dvd_of_coprime (λ a _ b _ h, _) (λ a _, _), { simp_rw [polynomial.map_pow, polynomial.map_sub, map_C, map_X], exact (pairwise_coprime_X_sub_C (is_fraction_ring.injective R $ fraction_ring R) h).pow }, { exact polynomial.map_dvd _ (pow_root_multiplicity_dvd p a) }, end /-- A Galois connection. -/ lemma _root_.multiset.prod_X_sub_C_dvd_iff_le_roots {p : R[X]} (hp : p ≠ 0) (s : multiset R) : (s.map (λ a, X - C a)).prod ∣ p ↔ s ≤ p.roots := by classical; exact ⟨λ h, multiset.le_iff_count.2 $ λ r, begin rw [count_roots, le_root_multiplicity_iff hp, ← multiset.prod_replicate, ← multiset.map_replicate (λ a, X - C a), ← multiset.filter_eq], exact (multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ s.filter_le _).trans h, end, λ h, (multiset.prod_dvd_prod_of_le $ multiset.map_le_map h).trans p.prod_multiset_X_sub_C_dvd⟩ lemma exists_prod_multiset_X_sub_C_mul (p : R[X]) : ∃ q, (p.roots.map (λ a, X - C a)).prod * q = p ∧ p.roots.card + q.nat_degree = p.nat_degree ∧ q.roots = 0 := begin obtain ⟨q, he⟩ := p.prod_multiset_X_sub_C_dvd, use [q, he.symm], obtain (rfl|hq) := eq_or_ne q 0, { rw mul_zero at he, subst he, simp }, split, { conv_rhs { rw he }, rw [monic_prod_multiset_X_sub_C.nat_degree_mul' hq, nat_degree_multiset_prod_X_sub_C_eq_card] }, { replace he := congr_arg roots he.symm, rw [roots_mul, roots_multiset_prod_X_sub_C] at he, exacts [add_right_eq_self.1 he, mul_ne_zero monic_prod_multiset_X_sub_C.ne_zero hq] }, end /-- A polynomial `p` that has as many roots as its degree can be written `p = p.leading_coeff * ∏(X - a)`, for `a` in `p.roots`. -/ lemma C_leading_coeff_mul_prod_multiset_X_sub_C (hroots : p.roots.card = p.nat_degree) : C p.leading_coeff * (p.roots.map (λ a, X - C a)).prod = p := (eq_leading_coeff_mul_of_monic_of_dvd_of_nat_degree_le monic_prod_multiset_X_sub_C p.prod_multiset_X_sub_C_dvd ((nat_degree_multiset_prod_X_sub_C_eq_card _).trans hroots).ge).symm /-- A monic polynomial `p` that has as many roots as its degree can be written `p = ∏(X - a)`, for `a` in `p.roots`. -/ lemma prod_multiset_X_sub_C_of_monic_of_roots_card_eq (hp : p.monic) (hroots : p.roots.card = p.nat_degree) : (p.roots.map (λ a, X - C a)).prod = p := by { convert C_leading_coeff_mul_prod_multiset_X_sub_C hroots, rw [hp.leading_coeff, C_1, one_mul] } end comm_ring section variables {A B : Type*} [comm_ring A] [comm_ring B] lemma le_root_multiplicity_map {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (a : A) : root_multiplicity a p ≤ root_multiplicity (f a) (p.map f) := begin rw [le_root_multiplicity_iff hmap], refine trans _ ((map_ring_hom f).map_dvd (pow_root_multiplicity_dvd p a)), rw [map_pow, map_sub, coe_map_ring_hom, map_X, map_C], end lemma eq_root_multiplicity_map {p : A[X]} {f : A →+* B} (hf : function.injective f) (a : A) : root_multiplicity a p = root_multiplicity (f a) (p.map f) := begin by_cases hp0 : p = 0, { simp only [hp0, root_multiplicity_zero, polynomial.map_zero], }, apply le_antisymm (le_root_multiplicity_map ((polynomial.map_ne_zero_iff hf).mpr hp0) a), rw [le_root_multiplicity_iff hp0, ← map_dvd_map f hf ((monic_X_sub_C a).pow _), polynomial.map_pow, polynomial.map_sub, map_X, map_C], apply pow_root_multiplicity_dvd, end lemma count_map_roots [is_domain A] [decidable_eq B] {p : A[X]} {f : A →+* B} (hmap : map f p ≠ 0) (b : B) : (p.roots.map f).count b ≤ root_multiplicity b (p.map f) := begin rw [le_root_multiplicity_iff hmap, ← multiset.prod_replicate, ← multiset.map_replicate (λ a, X - C a)], rw ← multiset.filter_eq, refine (multiset.prod_dvd_prod_of_le $ multiset.map_le_map $ multiset.filter_le _ _).trans _, convert polynomial.map_dvd _ p.prod_multiset_X_sub_C_dvd, simp only [polynomial.map_multiset_prod, multiset.map_map], congr, ext1, simp only [function.comp_app, polynomial.map_sub, map_X, map_C], end lemma count_map_roots_of_injective [is_domain A] [decidable_eq B] (p : A[X]) {f : A →+* B} (hf : function.injective f) (b : B) : (p.roots.map f).count b ≤ root_multiplicity b (p.map f) := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, multiset.count_zero, polynomial.map_zero, root_multiplicity_zero] }, { exact count_map_roots ((polynomial.map_ne_zero_iff hf).mpr hp0) b }, end lemma map_roots_le [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (h : p.map f ≠ 0) : p.roots.map f ≤ (p.map f).roots := by classical; exact (multiset.le_iff_count.2 $ λ b, by { rw count_roots, apply count_map_roots h }) lemma map_roots_le_of_injective [is_domain A] [is_domain B] (p : A[X]) {f : A →+* B} (hf : function.injective f) : p.roots.map f ≤ (p.map f).roots := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, multiset.map_zero, polynomial.map_zero], }, exact map_roots_le ((polynomial.map_ne_zero_iff hf).mpr hp0), end lemma card_roots_le_map [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (h : p.map f ≠ 0) : p.roots.card ≤ (p.map f).roots.card := by { rw ← p.roots.card_map f, exact multiset.card_le_of_le (map_roots_le h) } lemma card_roots_le_map_of_injective [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) : p.roots.card ≤ (p.map f).roots.card := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, polynomial.map_zero, multiset.card_zero], }, exact card_roots_le_map ((polynomial.map_ne_zero_iff hf).mpr hp0), end lemma roots_map_of_injective_of_card_eq_nat_degree [is_domain A] [is_domain B] {p : A[X]} {f : A →+* B} (hf : function.injective f) (hroots : p.roots.card = p.nat_degree) : p.roots.map f = (p.map f).roots := begin apply multiset.eq_of_le_of_card_le (map_roots_le_of_injective p hf), simpa only [multiset.card_map, hroots] using (card_roots' _).trans (nat_degree_map_le f p), end end section variables [semiring R] [comm_ring S] [is_domain S] (φ : R →+* S) lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map {f : R[X]} (hf : is_unit f.leading_coeff) (H : is_unit (map φ f)) : is_unit f := begin have dz := degree_eq_zero_of_is_unit H, rw degree_map_eq_of_leading_coeff_ne_zero at dz, { rw eq_C_of_degree_eq_zero dz, refine is_unit.map C _, convert hf, rw (degree_eq_iff_nat_degree_eq _).1 dz, rintro rfl, simpa using H, }, { intro h, have u : is_unit (φ f.leading_coeff) := is_unit.map φ hf, rw h at u, simpa using u, } end end section variables [comm_ring R] [is_domain R] [comm_ring S] [is_domain S] (φ : R →+* S) /-- A polynomial over an integral domain `R` is irreducible if it is monic and irreducible after mapping into an integral domain `S`. A special case of this lemma is that a polynomial over `ℤ` is irreducible if it is monic and irreducible over `ℤ/pℤ` for some prime `p`. -/ lemma monic.irreducible_of_irreducible_map (f : R[X]) (h_mon : monic f) (h_irr : irreducible (map φ f)) : irreducible f := begin refine ⟨h_irr.not_unit ∘ is_unit.map (map_ring_hom φ), λ a b h, _⟩, dsimp [monic] at h_mon, have q := (leading_coeff_mul a b).symm, rw [←h, h_mon] at q, refine (h_irr.is_unit_or_is_unit $ (congr_arg (map φ) h).trans (polynomial.map_mul φ)).imp _ _; apply is_unit_of_is_unit_leading_coeff_of_is_unit_map; apply is_unit_of_mul_eq_one, { exact q }, { rw mul_comm, exact q }, end end end polynomial
7e7240531cf18cadaa9a48587a78d411e8366836
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/rossel1.lean
a62747d9568c72ef343f2c9166ac2cd5105d568b
[ "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
1,136
lean
opaque ID : Type -- A `Reactor` contains "things" identified by an `ID`. It also contains other `Reactor`s, thereby giving us a tree structure of reactors. inductive Reactor | mk (things : ID → Option Nat) (nested : ID → Option Reactor) -- Structure projections. def Reactor.things : Reactor → ID → Option Nat | mk t _ => t def Reactor.nested : Reactor → ID → Option Reactor | mk _ n => n inductive Lineage : Reactor → ID → Type | thing {rtr i} : (∃ t, rtr.things i = some t) → Lineage rtr i | nested {rtr' i' rtr i} : (Lineage rtr' i) → (rtr.nested i' = some rtr') → Lineage rtr i def Lineage.container' {rtr i} : Lineage rtr i → (Option ID × Reactor) | .nested (.nested l h) _ => (Lineage.nested l h).container' | @nested rtr' i' .. => (i', rtr') | _ => (none, rtr) attribute [simp] Lineage.container' #check @Lineage.container'._eq_1 #check @Lineage.container'._eq_2 #check @Lineage.container'._eq_3 @[simp] def Lineage.container : Lineage rtr i → (Option ID × Reactor) | nested l@h:(nested ..) _ => l.container | @nested rtr' i' .. => (i', rtr') | _ => (none, rtr)
fa8a9a661066b51134241212703deb8acdf6b831
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/tests/lean/crash.lean
db7e8bd4ad4dbd286449e973755c54475a828cae
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
155
lean
import logic context hypothesis P : Prop. definition crash := assume H : P, have H' : ¬ P, from H, _. end
e0e13b2fd9fff3753402a61ca24daff040044cbc
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/pp_binder_types.lean
e2c158acc0dc181284a617cc0a002f25105e8130
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
113
lean
open nat definition f (n : nat) (H : n = n) := λm, id (n + m) print f set_option pp.binder_types true print f
7d759b8a019109123943f3e1992de91ada0640c5
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast8.lean
0d311deb3222c47852796a268ab204904fc31d37
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
473
lean
open nat set_option blast.init_depth 10 set_option blast.max_depth 10 lemma l1 (a : nat) : zero = succ a → a = a → false := by blast lemma l2 (p : Prop) (a : nat) : zero = succ a → a = a → p := by blast lemma l3 (a b : nat) : succ (succ a) = succ (succ b) → a = b := by blast lemma l4 (a b : nat) : succ a = succ b → a = b := by blast lemma l5 (a b c : nat) : succ (succ a) = succ (succ b) → c = c := by blast reveal l3 l4 l5 print l3 print l4 print l5
ee689108b3b09c4ed1762d06031c0f4042e4e076
1717bcbca047a0d25d687e7e9cd482fba00d058f
/src/measure_theory/measurable_space.lean
061483d7dabdae4a6c4a8a2cd1adcee2a25a083b
[ "Apache-2.0" ]
permissive
swapnilkapoor22/mathlib
51ad5804e6a0635ed5c7611cee73e089ab271060
3e7efd4ecd5d379932a89212eebd362beb01309e
refs/heads/master
1,676,467,741,465
1,610,301,556,000
1,610,301,556,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
60,759
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 data.set.disjointed import data.set.countable import data.indicator_function import data.equiv.encodable.lattice import data.tprod import order.filter.basic /-! # Measurable spaces and measurable functions This file defines measurable spaces and the functions and isomorphisms between them. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. A function `f : α → β` induces a Galois connection between the lattices of σ-algebras on `α` and `β`. A measurable equivalence between measurable spaces is an equivalence which respects the σ-algebras, that is, for which both directions of the equivalence are measurable functions. We say that a filter `f` is measurably generated if every set `s ∈ f` includes a measurable set `t ∈ f`. This property is useful, e.g., to extract a measurable witness of `filter.eventually`. ## Main statements The main theorem of this file is Dynkin's π-λ theorem, which appears here as an induction principle `induction_on_inter`. Suppose `s` is a collection of subsets of `α` such that the intersection of two members of `s` belongs to `s` whenever it is nonempty. Let `m` be the σ-algebra generated by `s`. In order to check that a predicate `C` holds on every member of `m`, it suffices to check that `C` holds on the members of `s` and that `C` is preserved by complementation and *disjoint* countable unions. ## Notation * We write `α ≃ᵐ β` for measurable equivalences between the measurable spaces `α` and `β`. This should not be confused with `≃ₘ` which is used for diffeomorphisms between manifolds. ## Implementation notes Measurability of a function `f : α → β` between measurable spaces is defined in terms of the Galois connection induced by f. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function, measurable equivalence, dynkin system, π-λ theorem, π-system -/ open set encodable function equiv open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (is_measurable' : set α → Prop) (is_measurable_empty : is_measurable' ∅) (is_measurable_compl : ∀ s, is_measurable' s → is_measurable' sᶜ) (is_measurable_Union : ∀ f : ℕ → set α, (∀ i, is_measurable' (f i)) → is_measurable' (⋃ i, f i)) attribute [class] measurable_space section variable [measurable_space α] /-- `is_measurable s` means that `s` is measurable (in the ambient measure space on `α`) -/ def is_measurable : set α → Prop := ‹measurable_space α›.is_measurable' @[simp] lemma is_measurable.empty : is_measurable (∅ : set α) := ‹measurable_space α›.is_measurable_empty lemma is_measurable.compl : is_measurable s → is_measurable sᶜ := ‹measurable_space α›.is_measurable_compl s lemma is_measurable.of_compl (h : is_measurable sᶜ) : is_measurable s := s.compl_compl ▸ h.compl @[simp] lemma is_measurable.compl_iff : is_measurable sᶜ ↔ is_measurable s := ⟨is_measurable.of_compl, is_measurable.compl⟩ @[simp] lemma is_measurable.univ : is_measurable (univ : set α) := by simpa using (@is_measurable.empty α _).compl lemma subsingleton.is_measurable [subsingleton α] {s : set α} : is_measurable s := subsingleton.set_cases is_measurable.empty is_measurable.univ s lemma is_measurable.congr {s t : set α} (hs : is_measurable s) (h : s = t) : is_measurable t := by rwa ← h lemma is_measurable.bUnion_decode2 [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) (n : ℕ) : is_measurable (⋃ b ∈ decode2 β n, f b) := encodable.Union_decode2_cases is_measurable.empty h lemma is_measurable.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := begin rw ← encodable.Union_decode2, exact ‹measurable_space α›.is_measurable_Union _ (is_measurable.bUnion_decode2 h) end lemma is_measurable.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact is_measurable.Union (by simpa using h) end lemma set.finite.is_measurable_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := is_measurable.bUnion hs.countable h lemma finset.is_measurable_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋃ b ∈ s, f b) := s.finite_to_set.is_measurable_bUnion h lemma is_measurable.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := by { rw sUnion_eq_bUnion, exact is_measurable.bUnion hs h } lemma set.finite.is_measurable_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋃₀ s) := is_measurable.sUnion hs.countable h lemma is_measurable.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := by { by_cases p; simp [h, hf, is_measurable.empty] } lemma is_measurable.Inter [encodable β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.compl_iff.1 $ by { rw compl_Inter, exact is_measurable.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.encodable lemma is_measurable.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋃ b, f b) := is_measurable.Union h lemma is_measurable.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := is_measurable.Inter h end fintype lemma is_measurable.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.compl_iff.1 $ by { rw compl_bInter, exact is_measurable.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.is_measurable_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := is_measurable.bInter hs.countable h lemma finset.is_measurable_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, is_measurable (f b)) : is_measurable (⋂ b ∈ s, f b) := s.finite_to_set.is_measurable_bInter h lemma is_measurable.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := by { rw sInter_eq_bInter, exact is_measurable.bInter hs h } lemma set.finite.is_measurable_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, is_measurable t) : is_measurable (⋂₀ s) := is_measurable.sInter hs.countable h lemma is_measurable.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, is_measurable (f b)) : is_measurable (⋂ b, f b) := by { by_cases p; simp [h, hf, is_measurable.univ] } @[simp] lemma is_measurable.union {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∪ s₂) := by { rw union_eq_Union, exact is_measurable.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma is_measurable.inter {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma is_measurable.diff {s₁ s₂ : set α} (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) : is_measurable (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma is_measurable.disjointed {f : ℕ → set α} (h : ∀ i, is_measurable (f i)) (n) : is_measurable (disjointed f n) := disjointed_induct (h n) (assume t i ht, is_measurable.diff ht $ h _) @[simp] lemma is_measurable.const (p : Prop) : is_measurable {a : α | p} := by { by_cases p; simp [h, is_measurable.empty]; apply is_measurable.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ is_measurable t} := ⟨⟨univ, subset_univ s, is_measurable.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.is_measurable' s ↔ m₂.is_measurable' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (is_measurable_singleton : ∀ x, is_measurable ({x} : set α)) export measurable_singleton_class (is_measurable_singleton) attribute [simp] is_measurable_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma is_measurable_eq {a : α} : is_measurable {x | x = a} := is_measurable_singleton a lemma is_measurable.insert {s : set α} (hs : is_measurable s) (a : α) : is_measurable (insert a s) := (is_measurable_singleton a).union hs @[simp] lemma is_measurable_insert {a : α} {s : set α} : is_measurable (insert a s) ↔ is_measurable s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (is_measurable_singleton _), λ h, h.insert a⟩ lemma set.finite.is_measurable {s : set α} (hs : finite s) : is_measurable s := finite.induction_on hs is_measurable.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.is_measurable (s : finset α) : is_measurable (↑s : set α) := s.finite_to_set.is_measurable end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.is_measurable' ≤ m₂.is_measurable', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { is_measurable' := generate_measurable s, is_measurable_empty := generate_measurable.empty, is_measurable_compl := generate_measurable.compl, is_measurable_Union := generate_measurable.union } lemma is_measurable_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).is_measurable' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.is_measurable' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (is_measurable_empty m) (assume s _ hs, is_measurable_compl m s hs) (assume f _ hf, is_measurable_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.is_measurable' t} := iff.intro (assume h u hu, h _ $ is_measurable_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_is_measurable [measurable_space α] : generate_from {s : set α | is_measurable s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, is_measurable_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).is_measurable' t} = g) : measurable_space α := { is_measurable' := λ s, s ∈ g, is_measurable_empty := hg ▸ is_measurable_empty _, is_measurable_compl := hg ▸ is_measurable_compl _, is_measurable_Union := hg ▸ is_measurable_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).is_measurable' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @is_measurable α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, is_measurable_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma is_measurable_bot_iff {s : set α} : @is_measurable α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { is_measurable' := λ s, s = ∅ ∨ s = univ, is_measurable_empty := or.inl rfl, is_measurable_compl := by simp [or_imp_distrib] {contextual := tt}, is_measurable_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @is_measurable_empty _ ⊥) (λ s, s.symm ▸ @is_measurable.univ _ ⊥), this ▸ iff.rfl @[simp] theorem is_measurable_top {s : set α} : @is_measurable _ ⊤ s := trivial @[simp] theorem is_measurable_inf {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊓ m₂) s ↔ @is_measurable _ m₁ s ∧ @is_measurable _ m₂ s := iff.rfl @[simp] theorem is_measurable_Inf {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Inf ms) s ↔ ∀ m ∈ ms, @is_measurable _ m s := show s ∈ (⋂ m ∈ ms, {t | @is_measurable _ m t }) ↔ _, by simp @[simp] theorem is_measurable_infi {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (infi m) s ↔ ∀ i, @is_measurable _ (m i) s := show s ∈ (λ m, {s | @is_measurable _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem is_measurable_sup {m₁ m₂ : measurable_space α} {s : set α} : @is_measurable _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.is_measurable' ∪ m₂.is_measurable') s := iff.refl _ theorem is_measurable_Sup {ms : set (measurable_space α)} {s : set α} : @is_measurable _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @is_measurable _ m s} s := begin change @is_measurable' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem is_measurable_supr {ι} {m : ι → measurable_space α} {s : set α} : @is_measurable _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @is_measurable _ (m i) s} s := begin convert @is_measurable_Sup _ (range m) s, simp, end end complete_lattice section functors variables {m m₁ m₂ : measurable_space α} {m' : measurable_space β} {f : α → β} {g : β → α} /-- The forward image of a measure space under a function. `map f m` contains the sets `s : set β` whose preimage under `f` is measurable. -/ protected def map (f : α → β) (m : measurable_space α) : measurable_space β := { is_measurable' := λ s, m.is_measurable' $ f ⁻¹' s, is_measurable_empty := m.is_measurable_empty, is_measurable_compl := assume s hs, m.is_measurable_compl _ hs, is_measurable_Union := assume f hf, by { rw [preimage_Union], exact m.is_measurable_Union _ hf }} @[simp] lemma map_id : m.map id = m := measurable_space.ext $ assume s, iff.rfl @[simp] lemma map_comp {f : α → β} {g : β → γ} : (m.map f).map g = m.map (g ∘ f) := measurable_space.ext $ assume s, iff.rfl /-- The reverse image of a measure space under a function. `comap f m` contains the sets `s : set α` such that `s` is the `f`-preimage of a measurable set in `β`. -/ protected def comap (f : α → β) (m : measurable_space β) : measurable_space α := { is_measurable' := λ s, ∃s', m.is_measurable' s' ∧ f ⁻¹' s' = s, is_measurable_empty := ⟨∅, m.is_measurable_empty, rfl⟩, is_measurable_compl := assume s ⟨s', h₁, h₂⟩, ⟨s'ᶜ, m.is_measurable_compl _ h₁, h₂ ▸ rfl⟩, is_measurable_Union := assume s hs, let ⟨s', hs'⟩ := classical.axiom_of_choice hs in ⟨⋃ i, s' i, m.is_measurable_Union _ (λ i, (hs' i).left), by simp [hs'] ⟩ } @[simp] lemma comap_id : m.comap id = m := measurable_space.ext $ assume s, ⟨assume ⟨s', hs', h⟩, h ▸ hs', assume h, ⟨s, h, rfl⟩⟩ @[simp] lemma comap_comp {f : β → α} {g : γ → β} : (m.comap f).comap g = m.comap (f ∘ g) := measurable_space.ext $ assume s, ⟨assume ⟨t, ⟨u, h, hu⟩, ht⟩, ⟨u, h, ht ▸ hu ▸ rfl⟩, assume ⟨t, h, ht⟩, ⟨f ⁻¹' t, ⟨_, h, rfl⟩, ht⟩⟩ lemma comap_le_iff_le_map {f : α → β} : m'.comap f ≤ m ↔ m' ≤ m.map f := ⟨assume h s hs, h _ ⟨_, hs, rfl⟩, assume h s ⟨t, ht, heq⟩, heq ▸ h _ ht⟩ lemma gc_comap_map (f : α → β) : galois_connection (measurable_space.comap f) (measurable_space.map f) := assume f g, comap_le_iff_le_map lemma map_mono (h : m₁ ≤ m₂) : m₁.map f ≤ m₂.map f := (gc_comap_map f).monotone_u h lemma monotone_map : monotone (measurable_space.map f) := assume a b h, map_mono h lemma comap_mono (h : m₁ ≤ m₂) : m₁.comap g ≤ m₂.comap g := (gc_comap_map g).monotone_l h lemma monotone_comap : monotone (measurable_space.comap g) := assume a b h, comap_mono h @[simp] lemma comap_bot : (⊥ : measurable_space α).comap g = ⊥ := (gc_comap_map g).l_bot @[simp] lemma comap_sup : (m₁ ⊔ m₂).comap g = m₁.comap g ⊔ m₂.comap g := (gc_comap_map g).l_sup @[simp] lemma comap_supr {m : ι → measurable_space α} : (⨆i, m i).comap g = (⨆i, (m i).comap g) := (gc_comap_map g).l_supr @[simp] lemma map_top : (⊤ : measurable_space α).map f = ⊤ := (gc_comap_map f).u_top @[simp] lemma map_inf : (m₁ ⊓ m₂).map f = m₁.map f ⊓ m₂.map f := (gc_comap_map f).u_inf @[simp] lemma map_infi {m : ι → measurable_space α} : (⨅i, m i).map f = (⨅i, (m i).map f) := (gc_comap_map f).u_infi lemma comap_map_le : (m.map f).comap f ≤ m := (gc_comap_map f).l_u_le _ lemma le_map_comap : m ≤ (m.comap g).map g := (gc_comap_map g).le_u_l _ end functors lemma generate_from_le_generate_from {s t : set (set α)} (h : s ⊆ t) : generate_from s ≤ generate_from t := gi_generate_from.gc.monotone_l h lemma generate_from_sup_generate_from {s t : set (set α)} : generate_from s ⊔ generate_from t = generate_from (s ∪ t) := (@gi_generate_from α).gc.l_sup.symm lemma comap_generate_from {f : α → β} {s : set (set β)} : (generate_from s).comap f = generate_from (preimage f '' s) := le_antisymm (comap_le_iff_le_map.2 $ generate_from_le $ assume t hts, generate_measurable.basic _ $ mem_image_of_mem _ $ hts) (generate_from_le $ assume t ⟨u, hu, eq⟩, eq ▸ ⟨u, generate_measurable.basic _ hu, rfl⟩) end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, is_measurable t → is_measurable (f ⁻¹' t) lemma measurable_iff_le_map {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂ ≤ m₁.map f := iff.rfl alias measurable_iff_le_map ↔ measurable.le_map measurable.of_le_map lemma measurable_iff_comap_le {m₁ : measurable_space α} {m₂ : measurable_space β} {f : α → β} : measurable f ↔ m₂.comap f ≤ m₁ := comap_le_iff_le_map.symm alias measurable_iff_comap_le ↔ measurable.comap_le measurable.of_comap_le lemma measurable.mono {ma ma' : measurable_space α} {mb mb' : measurable_space β} {f : α → β} (hf : @measurable α β ma mb f) (ha : ma ≤ ma') (hb : mb' ≤ mb) : @measurable α β ma' mb' f := λ t ht, ha _ $ hf $ hb _ ht lemma measurable_from_top [measurable_space β] {f : α → β} : @measurable _ _ ⊤ _ f := λ s hs, trivial lemma measurable_generate_from [measurable_space α] {s : set (set β)} {f : α → β} (h : ∀ t ∈ s, is_measurable (f ⁻¹' t)) : @measurable _ _ _ (generate_from s) f := measurable.of_le_map $ generate_from_le h variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) lemma subsingleton.measurable [subsingleton α] {f : α → β} : measurable f := λ s hs, @subsingleton.is_measurable α _ _ _ lemma measurable.piecewise {s : set α} {_ : decidable_pred s} {f g : α → β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : measurable (piecewise s f g) := begin intros t ht, simp only [piecewise_preimage], exact (hs.inter $ hf ht).union (hs.compl.inter $ hg ht) end /-- this is slightly different from `measurable.piecewise`. It can be used to show `measurable (ite (x=0) 0 1)` by `exact measurable.ite (is_measurable_singleton 0) measurable_const measurable_const`, but replacing `measurable.ite` by `measurable.piecewise` in that example proof does not work. -/ lemma measurable.ite {p : α → Prop} {_ : decidable_pred p} {f g : α → β} (hp : is_measurable {a : α | p a}) (hf : measurable f) (hg : measurable g) : measurable (λ x, ite (p x) (f x) (g x)) := measurable.piecewise hp hf hg @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, is_measurable.const (a ∈ s) lemma measurable.indicator [has_zero β] {s : set α} {f : α → β} (hf : measurable f) (hs : is_measurable s) : measurable (s.indicator f) := hf.piecewise hs measurable_const @[to_additive] lemma measurable_one [has_one α] : measurable (1 : β → α) := @measurable_const _ _ _ _ 1 lemma measurable_of_not_nonempty (h : ¬ nonempty α) (f : α → β) : measurable f := begin assume s hs, convert is_measurable.empty, exact eq_empty_of_not_nonempty h _, end end measurable_functions section constructions variables [measurable_space α] [measurable_space β] [measurable_space γ] instance : measurable_space empty := ⊤ instance : measurable_space punit := ⊤ -- this also works for `unit` instance : measurable_space bool := ⊤ instance : measurable_space ℕ := ⊤ instance : measurable_space ℤ := ⊤ instance : measurable_space ℚ := ⊤ lemma measurable_to_encodable [encodable α] {f : β → α} (h : ∀ y, is_measurable (f ⁻¹' {f y})) : measurable f := begin assume s hs, rw [← bUnion_preimage_singleton], refine is_measurable.Union (λ y, is_measurable.Union_Prop $ λ hy, _), by_cases hyf : y ∈ range f, { rcases hyf with ⟨y, rfl⟩, apply h }, { simp only [preimage_singleton_eq_empty.2 hyf, is_measurable.empty] } end lemma measurable_unit (f : unit → α) : measurable f := measurable_from_top section nat lemma measurable_from_nat {f : ℕ → α} : measurable f := measurable_from_top lemma measurable_to_nat {f : α → ℕ} : (∀ y, is_measurable (f ⁻¹' {f y})) → measurable f := measurable_to_encodable lemma measurable_find_greatest' {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | nat.find_greatest (p x) N = k}) : measurable (λ x, nat.find_greatest (p x) N) := measurable_to_nat $ λ x, hN _ nat.find_greatest_le lemma measurable_find_greatest {p : α → ℕ → Prop} {N} (hN : ∀ k ≤ N, is_measurable {x | p x k}) : measurable (λ x, nat.find_greatest (p x) N) := begin refine measurable_find_greatest' (λ k hk, _), simp only [nat.find_greatest_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, is_measurable.const, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl, hN]; try { intros } } end lemma measurable_find {p : α → ℕ → Prop} (hp : ∀ x, ∃ N, p x N) (hm : ∀ k, is_measurable {x | p x k}) : measurable (λ x, nat.find (hp x)) := begin refine measurable_to_nat (λ x, _), simp only [set.preimage, mem_singleton_iff, nat.find_eq_iff, set_of_and, set_of_forall, ← compl_set_of], repeat { apply_rules [is_measurable.inter, hm, is_measurable.Inter, is_measurable.Inter_Prop, is_measurable.compl]; try { intros } } end end nat section subtype instance {α} {p : α → Prop} [m : measurable_space α] : measurable_space (subtype p) := m.comap (coe : _ → α) lemma measurable_subtype_coe {p : α → Prop} : measurable (coe : subtype p → α) := measurable_space.le_map_comap lemma measurable.subtype_coe {p : β → Prop} {f : α → subtype p} (hf : measurable f) : measurable (λ a : α, (f a : β)) := measurable_subtype_coe.comp hf lemma measurable.subtype_mk {p : β → Prop} {f : α → β} (hf : measurable f) {h : ∀ x, p (f x)} : measurable (λ x, (⟨f x, h x⟩ : subtype p)) := λ t ⟨s, hs⟩, hs.2 ▸ by simp only [← preimage_comp, (∘), subtype.coe_mk, hf hs.1] lemma is_measurable.subtype_image {s : set α} {t : set s} (hs : is_measurable s) : is_measurable t → is_measurable ((coe : s → α) '' t) | ⟨u, (hu : is_measurable u), (eq : coe ⁻¹' u = t)⟩ := begin rw [← eq, subtype.image_preimage_coe], exact hu.inter hs end lemma measurable_of_measurable_union_cover {f : α → β} (s t : set α) (hs : is_measurable s) (ht : is_measurable t) (h : univ ⊆ s ∪ t) (hc : measurable (λ a : s, f a)) (hd : measurable (λ a : t, f a)) : measurable f := begin intros u hu, convert (hs.subtype_image (hc hu)).union (ht.subtype_image (hd hu)), change f ⁻¹' u = coe '' (coe ⁻¹' (f ⁻¹' u) : set s) ∪ coe '' (coe ⁻¹' (f ⁻¹' u) : set t), rw [image_preimage_eq_inter_range, image_preimage_eq_inter_range, subtype.range_coe, subtype.range_coe, ← inter_distrib_left, univ_subset_iff.1 h, inter_univ], end lemma measurable_of_measurable_on_compl_singleton [measurable_singleton_class α] {f : α → β} (a : α) (hf : measurable (set.restrict f {x | x ≠ a})) : measurable f := measurable_of_measurable_union_cover _ _ is_measurable_eq is_measurable_eq.compl (λ x hx, classical.em _) (@subsingleton.measurable {x | x = a} _ _ _ ⟨λ x y, subtype.eq $ x.2.trans y.2.symm⟩ _) hf end subtype section prod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α × β) := m₁.comap prod.fst ⊔ m₂.comap prod.snd lemma measurable_fst : measurable (prod.fst : α × β → α) := measurable.of_comap_le le_sup_left lemma measurable.fst {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).1) := measurable_fst.comp hf lemma measurable_snd : measurable (prod.snd : α × β → β) := measurable.of_comap_le le_sup_right lemma measurable.snd {f : α → β × γ} (hf : measurable f) : measurable (λ a : α, (f a).2) := measurable_snd.comp hf lemma measurable.prod {f : α → β × γ} (hf₁ : measurable (λ a, (f a).1)) (hf₂ : measurable (λ a, (f a).2)) : measurable f := measurable.of_le_map $ sup_le (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₁ }) (by { rw [measurable_space.comap_le_iff_le_map, measurable_space.map_comp], exact hf₂ }) lemma measurable_prod {f : α → β × γ} : measurable f ↔ measurable (λ a, (f a).1) ∧ measurable (λ a, (f a).2) := ⟨λ hf, ⟨measurable_fst.comp hf, measurable_snd.comp hf⟩, λ h, measurable.prod h.1 h.2⟩ lemma measurable.prod_mk {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ a : α, (f a, g a)) := measurable.prod hf hg lemma measurable_prod_mk_left {x : α} : measurable (@prod.mk _ β x) := measurable_const.prod_mk measurable_id lemma measurable_prod_mk_right {y : β} : measurable (λ x : α, (x, y)) := measurable_id.prod_mk measurable_const lemma measurable.of_uncurry_left {f : α → β → γ} (hf : measurable (uncurry f)) {x : α} : measurable (f x) := hf.comp measurable_prod_mk_left lemma measurable.of_uncurry_right {f : α → β → γ} (hf : measurable (uncurry f)) {y : β} : measurable (λ x, f x y) := hf.comp measurable_prod_mk_right lemma measurable_swap : measurable (prod.swap : α × β → β × α) := measurable.prod measurable_snd measurable_fst lemma measurable_swap_iff {f : α × β → γ} : measurable (f ∘ prod.swap) ↔ measurable f := ⟨λ hf, by { convert hf.comp measurable_swap, ext ⟨x, y⟩, refl }, λ hf, hf.comp measurable_swap⟩ lemma is_measurable.prod {s : set α} {t : set β} (hs : is_measurable s) (ht : is_measurable t) : is_measurable (s.prod t) := is_measurable.inter (measurable_fst hs) (measurable_snd ht) lemma is_measurable_prod_of_nonempty {s : set α} {t : set β} (h : (s.prod t).nonempty) : is_measurable (s.prod t) ↔ is_measurable s ∧ is_measurable t := begin rcases h with ⟨⟨x, y⟩, hx, hy⟩, refine ⟨λ hst, _, λ h, h.1.prod h.2⟩, have : is_measurable ((λ x, (x, y)) ⁻¹' s.prod t) := measurable_id.prod_mk measurable_const hst, have : is_measurable (prod.mk x ⁻¹' s.prod t) := measurable_const.prod_mk measurable_id hst, simp * at * end lemma is_measurable_prod {s : set α} {t : set β} : is_measurable (s.prod t) ↔ (is_measurable s ∧ is_measurable t) ∨ s = ∅ ∨ t = ∅ := begin cases (s.prod t).eq_empty_or_nonempty with h h, { simp [h, prod_eq_empty_iff.mp h] }, { simp [←not_nonempty_iff_eq_empty, prod_nonempty_iff.mp h, is_measurable_prod_of_nonempty h] } end lemma is_measurable_swap_iff {s : set (α × β)} : is_measurable (prod.swap ⁻¹' s) ↔ is_measurable s := ⟨λ hs, by { convert measurable_swap hs, ext ⟨x, y⟩, refl }, λ hs, measurable_swap hs⟩ end prod section pi variables {π : δ → Type*} instance measurable_space.pi [m : Π a, measurable_space (π a)] : measurable_space (Π a, π a) := ⨆ a, (m a).comap (λ b, b a) variables [Π a, measurable_space (π a)] [measurable_space γ] lemma measurable_pi_iff {g : α → Π a, π a} : measurable g ↔ ∀ a, measurable (λ x, g x a) := by simp_rw [measurable_iff_comap_le, measurable_space.pi, measurable_space.comap_supr, measurable_space.comap_comp, function.comp, supr_le_iff] lemma measurable_pi_apply (a : δ) : measurable (λ f : Π a, π a, f a) := measurable.of_comap_le $ le_supr _ a lemma measurable.eval {a : δ} {g : α → Π a, π a} (hg : measurable g) : measurable (λ x, g x a) := (measurable_pi_apply a).comp hg lemma measurable_pi_lambda (f : α → Π a, π a) (hf : ∀ a, measurable (λ c, f c a)) : measurable f := measurable_pi_iff.mpr hf /-- The function `update f a : π a → Π a, π a` is always measurable. This doesn't require `f` to be measurable. This should not be confused with the statement that `update f a x` is measurable. -/ lemma measurable_update (f : Π (a : δ), π a) {a : δ} : measurable (update f a) := begin apply measurable_pi_lambda, intro x, by_cases hx : x = a, { cases hx, convert measurable_id, ext, simp }, simp_rw [update_noteq hx], apply measurable_const, end /- Even though we cannot use projection notation, we still keep a dot to be consistent with similar lemmas, like `is_measurable.prod`. -/ lemma is_measurable.pi {s : set δ} {t : Π i : δ, set (π i)} (hs : countable s) (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (s.pi t) := by { rw [pi_def], exact is_measurable.bInter hs (λ i hi, measurable_pi_apply _ (ht i hi)) } lemma is_measurable.pi_univ [encodable δ] {t : Π i : δ, set (π i)} (ht : ∀ i, is_measurable (t i)) : is_measurable (pi univ t) := is_measurable.pi (countable_encodable _) (λ i _, ht i) lemma is_measurable_pi_of_nonempty {s : set δ} {t : Π i, set (π i)} (hs : countable s) (h : (pi s t).nonempty) : is_measurable (pi s t) ↔ ∀ i ∈ s, is_measurable (t i) := begin rcases h with ⟨f, hf⟩, refine ⟨λ hst i hi, _, is_measurable.pi hs⟩, convert measurable_update f hst, rw [update_preimage_pi hi], exact λ j hj _, hf j hj end lemma is_measurable_pi {s : set δ} {t : Π i, set (π i)} (hs : countable s) : is_measurable (pi s t) ↔ (∀ i ∈ s, is_measurable (t i)) ∨ pi s t = ∅ := begin cases (pi s t).eq_empty_or_nonempty with h h, { simp [h] }, { simp [is_measurable_pi_of_nonempty hs, h, ← not_nonempty_iff_eq_empty] } end section fintype local attribute [instance] fintype.encodable lemma is_measurable.pi_fintype [fintype δ] {s : set δ} {t : Π i, set (π i)} (ht : ∀ i ∈ s, is_measurable (t i)) : is_measurable (pi s t) := is_measurable.pi (countable_encodable _) ht end fintype end pi instance tprod.measurable_space (π : δ → Type*) [∀ x, measurable_space (π x)] : ∀ (l : list δ), measurable_space (list.tprod π l) | [] := punit.measurable_space | (i :: is) := @prod.measurable_space _ _ _ (tprod.measurable_space is) section tprod open list variables {π : δ → Type*} [∀ x, measurable_space (π x)] lemma measurable_tprod_mk (l : list δ) : measurable (@tprod.mk δ π l) := begin induction l with i l ih, { exact measurable_const }, { exact (measurable_pi_apply i).prod_mk ih } end lemma measurable_tprod_elim : ∀ {l : list δ} {i : δ} (hi : i ∈ l), measurable (λ (v : tprod π l), v.elim hi) | (i :: is) j hj := begin by_cases hji : j = i, { subst hji, simp [measurable_fst] }, { rw [funext $ tprod.elim_of_ne _ hji], exact (measurable_tprod_elim (hj.resolve_left hji)).comp measurable_snd } end lemma measurable_tprod_elim' {l : list δ} (h : ∀ i, i ∈ l) : measurable (tprod.elim' h : tprod π l → Π i, π i) := measurable_pi_lambda _ (λ i, measurable_tprod_elim (h i)) lemma is_measurable.tprod (l : list δ) {s : ∀ i, set (π i)} (hs : ∀ i, is_measurable (s i)) : is_measurable (set.tprod l s) := by { induction l with i l ih, exact is_measurable.univ, exact (hs i).prod ih } end tprod instance {α β} [m₁ : measurable_space α] [m₂ : measurable_space β] : measurable_space (α ⊕ β) := m₁.map sum.inl ⊓ m₂.map sum.inr section sum lemma measurable_inl : measurable (@sum.inl α β) := measurable.of_le_map inf_le_left lemma measurable_inr : measurable (@sum.inr α β) := measurable.of_le_map inf_le_right lemma measurable_sum {f : α ⊕ β → γ} (hl : measurable (f ∘ sum.inl)) (hr : measurable (f ∘ sum.inr)) : measurable f := measurable.of_comap_le $ le_inf (measurable_space.comap_le_iff_le_map.2 $ hl) (measurable_space.comap_le_iff_le_map.2 $ hr) lemma measurable.sum_elim {f : α → γ} {g : β → γ} (hf : measurable f) (hg : measurable g) : measurable (sum.elim f g) := measurable_sum hf hg lemma is_measurable.inl_image {s : set α} (hs : is_measurable s) : is_measurable (sum.inl '' s : set (α ⊕ β)) := ⟨show is_measurable (sum.inl ⁻¹' _), by { rwa [preimage_image_eq], exact (λ a b, sum.inl.inj) }, have sum.inr ⁻¹' (sum.inl '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inr ⁻¹' _), by { rw [this], exact is_measurable.empty }⟩ lemma is_measurable_range_inl : is_measurable (range sum.inl : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable.univ.inl_image } lemma is_measurable_inr_image {s : set β} (hs : is_measurable s) : is_measurable (sum.inr '' s : set (α ⊕ β)) := ⟨ have sum.inl ⁻¹' (sum.inr '' s : set (α ⊕ β)) = ∅ := eq_empty_of_subset_empty $ assume x ⟨y, hy, eq⟩, by contradiction, show is_measurable (sum.inl ⁻¹' _), by { rw [this], exact is_measurable.empty }, show is_measurable (sum.inr ⁻¹' _), by { rwa [preimage_image_eq], exact λ a b, sum.inr.inj }⟩ lemma is_measurable_range_inr : is_measurable (range sum.inr : set (α ⊕ β)) := by { rw [← image_univ], exact is_measurable_inr_image is_measurable.univ } end sum instance {α} {β : α → Type*} [m : Πa, measurable_space (β a)] : measurable_space (sigma β) := ⨅a, (m a).map (sigma.mk a) end constructions /-- Equivalences between measurable spaces. Main application is the simplification of measurability statements along measurable equivalences. -/ structure measurable_equiv (α β : Type*) [measurable_space α] [measurable_space β] extends α ≃ β := (measurable_to_fun : measurable to_fun) (measurable_inv_fun : measurable inv_fun) infix ` ≃ᵐ `:25 := measurable_equiv namespace measurable_equiv variables (α β) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] instance : has_coe_to_fun (α ≃ᵐ β) := ⟨λ _, α → β, λ e, e.to_equiv⟩ variables {α β} lemma coe_eq (e : α ≃ᵐ β) : (e : α → β) = e.to_equiv := rfl protected lemma measurable (e : α ≃ᵐ β) : measurable (e : α → β) := e.measurable_to_fun @[simp] lemma coe_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β) : α → β) = e := rfl /-- Any measurable space is equivalent to itself. -/ def refl (α : Type*) [measurable_space α] : α ≃ᵐ α := { to_equiv := equiv.refl α, measurable_to_fun := measurable_id, measurable_inv_fun := measurable_id } instance : inhabited (α ≃ᵐ α) := ⟨refl α⟩ /-- The composition of equivalences between measurable spaces. -/ @[simps] def trans (ab : α ≃ᵐ β) (bc : β ≃ᵐ γ) : α ≃ᵐ γ := { to_equiv := ab.to_equiv.trans bc.to_equiv, measurable_to_fun := bc.measurable_to_fun.comp ab.measurable_to_fun, measurable_inv_fun := ab.measurable_inv_fun.comp bc.measurable_inv_fun } /-- The inverse of an equivalence between measurable spaces. -/ @[simps] def symm (ab : α ≃ᵐ β) : β ≃ᵐ α := { to_equiv := ab.to_equiv.symm, measurable_to_fun := ab.measurable_inv_fun, measurable_inv_fun := ab.measurable_to_fun } @[simp] lemma coe_symm_mk (e : α ≃ β) (h1 : measurable e) (h2 : measurable e.symm) : ((⟨e, h1, h2⟩ : α ≃ᵐ β).symm : β → α) = e.symm := rfl @[simp] theorem symm_comp_self (e : α ≃ᵐ β) : e.symm ∘ e = id := funext e.left_inv @[simp] theorem self_comp_symm (e : α ≃ᵐ β) : e ∘ e.symm = id := funext e.right_inv /-- Equal measurable spaces are equivalent. -/ protected def cast {α β} [i₁ : measurable_space α] [i₂ : measurable_space β] (h : α = β) (hi : i₁ == i₂) : α ≃ᵐ β := { to_equiv := equiv.cast h, measurable_to_fun := by { substI h, substI hi, exact measurable_id }, measurable_inv_fun := by { substI h, substI hi, exact measurable_id }} protected lemma measurable_coe_iff {f : β → γ} (e : α ≃ᵐ β) : measurable (f ∘ e) ↔ measurable f := iff.intro (assume hfe, have measurable (f ∘ (e.symm.trans e).to_equiv) := hfe.comp e.symm.measurable, by rwa [trans_to_equiv, symm_to_equiv, equiv.symm_trans] at this) (λ h, h.comp e.measurable) /-- Products of equivalent measurable spaces are equivalent. -/ def prod_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α × γ ≃ᵐ β × δ := { to_equiv := prod_congr ab.to_equiv cd.to_equiv, measurable_to_fun := (ab.measurable_to_fun.comp measurable_id.fst).prod_mk (cd.measurable_to_fun.comp measurable_id.snd), measurable_inv_fun := (ab.measurable_inv_fun.comp measurable_id.fst).prod_mk (cd.measurable_inv_fun.comp measurable_id.snd) } /-- Products of measurable spaces are symmetric. -/ def prod_comm : α × β ≃ᵐ β × α := { to_equiv := prod_comm α β, measurable_to_fun := measurable_id.snd.prod_mk measurable_id.fst, measurable_inv_fun := measurable_id.snd.prod_mk measurable_id.fst } /-- Products of measurable spaces are associative. -/ def prod_assoc : (α × β) × γ ≃ᵐ α × (β × γ) := { to_equiv := prod_assoc α β γ, measurable_to_fun := measurable_fst.fst.prod_mk $ measurable_fst.snd.prod_mk measurable_snd, measurable_inv_fun := (measurable_fst.prod_mk measurable_snd.fst).prod_mk measurable_snd.snd } /-- Sums of measurable spaces are symmetric. -/ def sum_congr (ab : α ≃ᵐ β) (cd : γ ≃ᵐ δ) : α ⊕ γ ≃ᵐ β ⊕ δ := { to_equiv := sum_congr ab.to_equiv cd.to_equiv, measurable_to_fun := begin cases ab with ab' abm, cases ab', cases cd with cd' cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end, measurable_inv_fun := begin cases ab with ab' _ abm, cases ab', cases cd with cd' _ cdm, cases cd', refine measurable_sum (measurable_inl.comp abm) (measurable_inr.comp cdm) end } /-- `set.prod s t ≃ (s × t)` as measurable spaces. -/ def set.prod (s : set α) (t : set β) : s.prod t ≃ᵐ s × t := { to_equiv := equiv.set.prod s t, measurable_to_fun := measurable_id.subtype_coe.fst.subtype_mk.prod_mk measurable_id.subtype_coe.snd.subtype_mk, measurable_inv_fun := measurable.subtype_mk $ measurable_id.fst.subtype_coe.prod_mk measurable_id.snd.subtype_coe } /-- `univ α ≃ α` as measurable spaces. -/ def set.univ (α : Type*) [measurable_space α] : (univ : set α) ≃ᵐ α := { to_equiv := equiv.set.univ α, measurable_to_fun := measurable_id.subtype_coe, measurable_inv_fun := measurable_id.subtype_mk } /-- `{a} ≃ unit` as measurable spaces. -/ def set.singleton (a : α) : ({a} : set α) ≃ᵐ unit := { to_equiv := equiv.set.singleton a, measurable_to_fun := measurable_const, measurable_inv_fun := measurable_const } /-- A set is equivalent to its image under a function `f` as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.image (f : α → β) (s : set α) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : s ≃ᵐ (f '' s) := { to_equiv := equiv.set.image f s hf, measurable_to_fun := (hfm.comp measurable_id.subtype_coe).subtype_mk, measurable_inv_fun := begin rintro t ⟨u, hu, rfl⟩, simp [preimage_preimage, set.image_symm_preimage hf], exact measurable_subtype_coe (hfi u hu) end } /-- The domain of `f` is equivalent to its range as measurable spaces, if `f` is an injective measurable function that sends measurable sets to measurable sets. -/ noncomputable def set.range (f : α → β) (hf : injective f) (hfm : measurable f) (hfi : ∀ s, is_measurable s → is_measurable (f '' s)) : α ≃ᵐ (range f) := (measurable_equiv.set.univ _).symm.trans $ (measurable_equiv.set.image f univ hf hfm hfi).trans $ measurable_equiv.cast (by rw image_univ) (by rw image_univ) /-- `α` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inl : (range sum.inl : set (α ⊕ β)) ≃ᵐ α := { to_fun := λ ab, match ab with | ⟨sum.inl a, _⟩ := a | ⟨sum.inr b, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ a, ⟨sum.inl a, a, rfl⟩, left_inv := by { rintro ⟨ab, a, rfl⟩, refl }, right_inv := assume a, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, hs.inl_image, set.ext _⟩, rintros ⟨ab, a, rfl⟩, simp [set.range_inl._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inl } /-- `β` is equivalent to its image in `α ⊕ β` as measurable spaces. -/ def set.range_inr : (range sum.inr : set (α ⊕ β)) ≃ᵐ β := { to_fun := λ ab, match ab with | ⟨sum.inr b, _⟩ := b | ⟨sum.inl a, p⟩ := have false, by { cases p, contradiction }, this.elim end, inv_fun := λ b, ⟨sum.inr b, b, rfl⟩, left_inv := by { rintro ⟨ab, b, rfl⟩, refl }, right_inv := assume b, rfl, measurable_to_fun := assume s (hs : is_measurable s), begin refine ⟨_, is_measurable_inr_image hs, set.ext _⟩, rintros ⟨ab, b, rfl⟩, simp [set.range_inr._match_1] end, measurable_inv_fun := measurable.subtype_mk measurable_inr } /-- Products distribute over sums (on the right) as measurable spaces. -/ def sum_prod_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : (α ⊕ β) × γ ≃ᵐ (α × γ) ⊕ (β × γ) := { to_equiv := sum_prod_distrib α β γ, measurable_to_fun := begin refine measurable_of_measurable_union_cover ((range sum.inl).prod univ) ((range sum.inr).prod univ) (is_measurable_range_inl.prod is_measurable.univ) (is_measurable_range_inr.prod is_measurable.univ) (by { rintro ⟨a|b, c⟩; simp [set.prod_eq] }) _ _, { refine (set.prod (range sum.inl) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inl (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inl, ext ⟨a, c⟩, refl }, { refine (set.prod (range sum.inr) univ).symm.measurable_coe_iff.1 _, refine (prod_congr set.range_inr (set.univ _)).symm.measurable_coe_iff.1 _, dsimp [(∘)], convert measurable_inr, ext ⟨b, c⟩, refl } end, measurable_inv_fun := measurable_sum ((measurable_inl.comp measurable_fst).prod_mk measurable_snd) ((measurable_inr.comp measurable_fst).prod_mk measurable_snd) } /-- Products distribute over sums (on the left) as measurable spaces. -/ def prod_sum_distrib (α β γ) [measurable_space α] [measurable_space β] [measurable_space γ] : α × (β ⊕ γ) ≃ᵐ (α × β) ⊕ (α × γ) := prod_comm.trans $ (sum_prod_distrib _ _ _).trans $ sum_congr prod_comm prod_comm /-- Products distribute over sums as measurable spaces. -/ def sum_prod_sum (α β γ δ) [measurable_space α] [measurable_space β] [measurable_space γ] [measurable_space δ] : (α ⊕ β) × (γ ⊕ δ) ≃ᵐ ((α × γ) ⊕ (α × δ)) ⊕ ((β × γ) ⊕ (β × δ)) := (sum_prod_distrib _ _ _).trans $ sum_congr (prod_sum_distrib _ _ _) (prod_sum_distrib _ _ _) variables {π π' : δ' → Type*} [∀ x, measurable_space (π x)] [∀ x, measurable_space (π' x)] /-- A family of measurable equivalences `Π a, β₁ a ≃ᵐ β₂ a` generates a measurable equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right (e : Π a, π a ≃ᵐ π' a) : (Π a, π a) ≃ᵐ (Π a, π' a) := { to_equiv := Pi_congr_right (λ a, (e a).to_equiv), measurable_to_fun := measurable_pi_lambda _ (λ i, (e i).measurable_to_fun.comp (measurable_pi_apply i)), measurable_inv_fun := measurable_pi_lambda _ (λ i, (e i).measurable_inv_fun.comp (measurable_pi_apply i)) } /-- Pi-types are measurably equivalent to iterated products. -/ noncomputable def pi_measurable_equiv_tprod {l : list δ'} (hnd : l.nodup) (h : ∀ i, i ∈ l) : (Π i, π i) ≃ᵐ list.tprod π l := { to_equiv := list.tprod.pi_equiv_tprod hnd h, measurable_to_fun := measurable_tprod_mk l, measurable_inv_fun := measurable_tprod_elim' h } end measurable_equiv /-- A pi-system is a collection of subsets of `α` that is closed under intersections of sets that are not disjoint. Usually it is also required that the collection is nonempty, but we don't do that here. -/ def is_pi_system {α} (C : set (set α)) : Prop := ∀ s t ∈ C, (s ∩ t : set α).nonempty → s ∩ t ∈ C namespace measurable_space lemma is_pi_system_is_measurable [measurable_space α] : is_pi_system {s : set α | is_measurable s} := λ s t hs ht _, hs.inter ht /-- A Dynkin system is a collection of subsets of a type `α` that contains the empty set, is closed under complementation and under countable union of pairwise disjoint sets. The disjointness condition is the only difference with `σ`-algebras. The main purpose of Dynkin systems is to provide a powerful induction rule for σ-algebras generated by intersection stable set systems. A Dynkin system is also known as a "λ-system" or a "d-system". -/ structure dynkin_system (α : Type*) := (has : set α → Prop) (has_empty : has ∅) (has_compl : ∀ {a}, has a → has aᶜ) (has_Union_nat : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, has (f i)) → has (⋃ i, f i)) namespace dynkin_system @[ext] lemma ext : ∀ {d₁ d₂ : dynkin_system α}, (∀ s : set α, d₁.has s ↔ d₂.has s) → d₁ = d₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this variable (d : dynkin_system α) lemma has_compl_iff {a} : d.has aᶜ ↔ d.has a := ⟨λ h, by simpa using d.has_compl h, λ h, d.has_compl h⟩ lemma has_univ : d.has univ := by simpa using d.has_compl d.has_empty theorem has_Union {β} [encodable β] {f : β → set α} (hd : pairwise (disjoint on f)) (h : ∀ i, d.has (f i)) : d.has (⋃ i, f i) := by { rw ← encodable.Union_decode2, exact d.has_Union_nat (Union_decode2_disjoint_on hd) (λ n, encodable.Union_decode2_cases d.has_empty h) } theorem has_union {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₁ ∩ s₂ ⊆ ∅) : d.has (s₁ ∪ s₂) := by { rw union_eq_Union, exact d.has_Union (pairwise_disjoint_on_bool.2 h) (bool.forall_bool.2 ⟨h₂, h₁⟩) } lemma has_diff {s₁ s₂ : set α} (h₁ : d.has s₁) (h₂ : d.has s₂) (h : s₂ ⊆ s₁) : d.has (s₁ \ s₂) := begin apply d.has_compl_iff.1, simp [diff_eq, compl_inter], exact d.has_union (d.has_compl h₁) h₂ (λ x ⟨h₁, h₂⟩, h₁ (h h₂)), end instance : partial_order (dynkin_system α) := { le := λ m₁ m₂, m₁.has ≤ m₂.has, le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- Every measurable space (σ-algebra) forms a Dynkin system -/ def of_measurable_space (m : measurable_space α) : dynkin_system α := { has := m.is_measurable', has_empty := m.is_measurable_empty, has_compl := m.is_measurable_compl, has_Union_nat := assume f _ hf, m.is_measurable_Union f hf } lemma of_measurable_space_le_of_measurable_space_iff {m₁ m₂ : measurable_space α} : of_measurable_space m₁ ≤ of_measurable_space m₂ ↔ m₁ ≤ m₂ := iff.rfl /-- The least Dynkin system containing a collection of basic sets. This inductive type gives the underlying collection of sets. -/ inductive generate_has (s : set (set α)) : set α → Prop | basic : ∀ t ∈ s, generate_has t | empty : generate_has ∅ | compl : ∀ {a}, generate_has a → generate_has aᶜ | Union : ∀ {f : ℕ → set α}, pairwise (disjoint on f) → (∀ i, generate_has (f i)) → generate_has (⋃ i, f i) lemma generate_has_compl {C : set (set α)} {s : set α} : generate_has C sᶜ ↔ generate_has C s := by { refine ⟨_, generate_has.compl⟩, intro h, convert generate_has.compl h, simp } /-- The least Dynkin system containing a collection of basic sets. -/ def generate (s : set (set α)) : dynkin_system α := { has := generate_has s, has_empty := generate_has.empty, has_compl := assume a, generate_has.compl, has_Union_nat := assume f, generate_has.Union } lemma generate_has_def {C : set (set α)} : (generate C).has = generate_has C := rfl instance : inhabited (dynkin_system α) := ⟨generate univ⟩ /-- If a Dynkin system is closed under binary intersection, then it forms a `σ`-algebra. -/ def to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) := { measurable_space . is_measurable' := d.has, is_measurable_empty := d.has_empty, is_measurable_compl := assume s h, d.has_compl h, is_measurable_Union := assume f hf, have ∀ n, d.has (disjointed f n), from assume n, disjointed_induct (hf n) (assume t i h, h_inter _ _ h $ d.has_compl $ hf i), have d.has (⋃ n, disjointed f n), from d.has_Union disjoint_disjointed this, by rwa [Union_disjointed] at this } lemma of_measurable_space_to_measurable_space (h_inter : ∀ s₁ s₂, d.has s₁ → d.has s₂ → d.has (s₁ ∩ s₂)) : of_measurable_space (d.to_measurable_space h_inter) = d := ext $ assume s, iff.rfl /-- If `s` is in a Dynkin system `d`, we can form the new Dynkin system `{s ∩ t | t ∈ d}`. -/ def restrict_on {s : set α} (h : d.has s) : dynkin_system α := { has := λ t, d.has (t ∩ s), has_empty := by simp [d.has_empty], has_compl := assume t hts, have tᶜ ∩ s = ((t ∩ s)ᶜ) \ sᶜ, from set.ext $ assume x, by { by_cases x ∈ s; simp [h] }, by { rw [this], exact d.has_diff (d.has_compl hts) (d.has_compl h) (compl_subset_compl.mpr $ inter_subset_right _ _) }, has_Union_nat := assume f hd hf, begin rw [inter_comm, inter_Union], apply d.has_Union_nat, { exact λ i j h x ⟨⟨_, h₁⟩, _, h₂⟩, hd i j h ⟨h₁, h₂⟩ }, { simpa [inter_comm] using hf }, end } lemma generate_le {s : set (set α)} (h : ∀ t ∈ s, d.has t) : generate s ≤ d := λ t ht, ht.rec_on h d.has_empty (assume a _ h, d.has_compl h) (assume f hd _ hf, d.has_Union hd hf) lemma generate_has_subset_generate_measurable {C : set (set α)} {s : set α} (hs : (generate C).has s) : (generate_from C).is_measurable' s := generate_le (of_measurable_space (generate_from C)) (λ t, is_measurable_generate_from) s hs lemma generate_inter {s : set (set α)} (hs : is_pi_system s) {t₁ t₂ : set α} (ht₁ : (generate s).has t₁) (ht₂ : (generate s).has t₂) : (generate s).has (t₁ ∩ t₂) := have generate s ≤ (generate s).restrict_on ht₂, from generate_le _ $ assume s₁ hs₁, have (generate s).has s₁, from generate_has.basic s₁ hs₁, have generate s ≤ (generate s).restrict_on this, from generate_le _ $ assume s₂ hs₂, show (generate s).has (s₂ ∩ s₁), from (s₂ ∩ s₁).eq_empty_or_nonempty.elim (λ h, h.symm ▸ generate_has.empty) (λ h, generate_has.basic _ (hs _ _ hs₂ hs₁ h)), have (generate s).has (t₂ ∩ s₁), from this _ ht₂, show (generate s).has (s₁ ∩ t₂), by rwa [inter_comm], this _ ht₁ /-- If we have a collection of sets closed under binary intersections, then the Dynkin system it generates is equal to the σ-algebra it generates. This result is known as the π-λ theorem. A collection of sets closed under binary intersection is called a "π-system" if it is non-empty. -/ lemma generate_from_eq {s : set (set α)} (hs : is_pi_system s) : generate_from s = (generate s).to_measurable_space (assume t₁ t₂, generate_inter hs) := le_antisymm (generate_from_le $ assume t ht, generate_has.basic t ht) (of_measurable_space_le_of_measurable_space_iff.mp $ by { rw [of_measurable_space_to_measurable_space], exact (generate_le _ $ assume t ht, is_measurable_generate_from ht) }) end dynkin_system lemma induction_on_inter {C : set α → Prop} {s : set (set α)} [m : measurable_space α] (h_eq : m = generate_from s) (h_inter : is_pi_system s) (h_empty : C ∅) (h_basic : ∀ t ∈ s, C t) (h_compl : ∀ t, is_measurable t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, is_measurable (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, is_measurable t → C t := have eq : is_measurable = dynkin_system.generate_has s, by { rw [h_eq, dynkin_system.generate_from_eq h_inter], refl }, assume t ht, have dynkin_system.generate_has s t, by rwa [eq] at ht, this.rec_on h_basic h_empty (assume t ht, h_compl t $ by { rw [eq], exact ht }) (assume f hf ht, h_union f hf $ assume i, by { rw [eq], exact ht _ }) end measurable_space namespace filter variables [measurable_space α] /-- A filter `f` is measurably generates if each `s ∈ f` includes a measurable `t ∈ f`. -/ class is_measurably_generated (f : filter α) : Prop := (exists_measurable_subset : ∀ ⦃s⦄, s ∈ f → ∃ t ∈ f, is_measurable t ∧ t ⊆ s) instance is_measurably_generated_bot : is_measurably_generated (⊥ : filter α) := ⟨λ _ _, ⟨∅, mem_bot_sets, is_measurable.empty, empty_subset _⟩⟩ instance is_measurably_generated_top : is_measurably_generated (⊤ : filter α) := ⟨λ s hs, ⟨univ, univ_mem_sets, is_measurable.univ, λ x _, hs x⟩⟩ lemma eventually.exists_measurable_mem {f : filter α} [is_measurably_generated f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ s ∈ f, is_measurable s ∧ ∀ x ∈ s, p x := is_measurably_generated.exists_measurable_subset h instance inf_is_measurably_generated (f g : filter α) [is_measurably_generated f] [is_measurably_generated g] : is_measurably_generated (f ⊓ g) := begin refine ⟨_⟩, rintros t ⟨sf, hsf, sg, hsg, ht⟩, rcases is_measurably_generated.exists_measurable_subset hsf with ⟨s'f, hs'f, hmf, hs'sf⟩, rcases is_measurably_generated.exists_measurable_subset hsg with ⟨s'g, hs'g, hmg, hs'sg⟩, refine ⟨s'f ∩ s'g, inter_mem_inf_sets hs'f hs'g, hmf.inter hmg, _⟩, exact subset.trans (inter_subset_inter hs'sf hs'sg) ht end lemma principal_is_measurably_generated_iff {s : set α} : is_measurably_generated (𝓟 s) ↔ is_measurable s := begin refine ⟨_, λ hs, ⟨λ t ht, ⟨s, mem_principal_self s, hs, ht⟩⟩⟩, rintros ⟨hs⟩, rcases hs (mem_principal_self s) with ⟨t, ht, htm, hts⟩, have : t = s := subset.antisymm hts ht, rwa ← this end alias principal_is_measurably_generated_iff ↔ _ is_measurable.principal_is_measurably_generated instance infi_is_measurably_generated {f : ι → filter α} [∀ i, is_measurably_generated (f i)] : is_measurably_generated (⨅ i, f i) := begin refine ⟨λ s hs, _⟩, rw [← equiv.plift.surjective.infi_comp, mem_infi_iff] at hs, rcases hs with ⟨t, ht, ⟨V, hVf, hVs⟩⟩, choose U hUf hU using λ i, is_measurably_generated.exists_measurable_subset (hVf i), refine ⟨⋂ i : t, U i, _, _, _⟩, { rw [← equiv.plift.surjective.infi_comp, mem_infi_iff], refine ⟨t, ht, U, hUf, subset.refl _⟩ }, { haveI := ht.countable.to_encodable, refine is_measurable.Inter (λ i, (hU i).1) }, { exact subset.trans (Inter_subset_Inter $ λ i, (hU i).2) hVs } end end filter /-- We say that a collection of sets is countably spanning if a countable subset spans the whole type. This is a useful condition in various parts of measure theory. For example, it is a needed condition to show that the product of two collections generate the product sigma algebra, see `generate_from_prod_eq`. -/ def is_countably_spanning (C : set (set α)) : Prop := ∃ (s : ℕ → set α), (∀ n, s n ∈ C) ∧ (⋃ n, s n) = univ lemma is_countably_spanning_is_measurable [measurable_space α] : is_countably_spanning {s : set α | is_measurable s} := ⟨λ _, univ, λ _, is_measurable.univ, Union_const _⟩
58828b79b8d655e3f6f211fd857146322447a96d
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Init/NotationExtra.lean
a3b3fdb3d95c95651b180cabf969cb2c82802de5
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,434
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 Extra notation that depends on Init/Meta -/ prelude import Init.Meta import Init.Data.Array.Subarray namespace Lean -- Auxiliary parsers and functions for declaring notation with binders syntax binderIdent := ident <|> "_" syntax unbracktedExplicitBinders := binderIdent+ (" : " term)? syntax bracketedExplicitBinders := "(" binderIdent+ " : " term ")" syntax explicitBinders := bracketedExplicitBinders+ <|> unbracktedExplicitBinders def expandExplicitBindersAux (combinator : Syntax) (idents : Array Syntax) (type? : Option Syntax) (body : Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do match i with | 0 => pure acc | i+1 => let ident := idents[i][0] let acc ← match ident.isIdent, type? with | true, none => `($combinator fun $ident => $acc) | true, some type => `($combinator fun $ident:ident : $type => $acc) | false, none => `($combinator fun _ => $acc) | false, some type => `($combinator fun _ : $type => $acc) loop i (acc.copyInfo (← getRef)) loop idents.size body def expandBrackedBindersAux (combinator : Syntax) (binders : Array Syntax) (body : Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do match i with | 0 => pure acc | i+1 => let idents := binders[i][1].getArgs let type := binders[i][3] loop i (← expandExplicitBindersAux combinator idents (some type) acc) loop binders.size body def expandExplicitBinders (combinatorDeclName : Name) (explicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do let combinator := mkIdentFrom (← getRef) combinatorDeclName let explicitBinders := explicitBinders[0] if explicitBinders.getKind == `Lean.unbracktedExplicitBinders then let idents := explicitBinders[0].getArgs let type? := if explicitBinders[1].isNone then none else some explicitBinders[1][1] expandExplicitBindersAux combinator idents type? body else if explicitBinders.getArgs.all (·.getKind == `Lean.bracketedExplicitBinders) then expandBrackedBindersAux combinator explicitBinders.getArgs body else Macro.throwError "unexpected explicit binder" def expandBrackedBinders (combinatorDeclName : Name) (bracketedExplicitBinders : Syntax) (body : Syntax) : MacroM Syntax := do let combinator := mkIdentFrom (← getRef) combinatorDeclName expandBrackedBindersAux combinator #[bracketedExplicitBinders] body end Lean open Lean macro "∃" xs:explicitBinders ", " b:term : term => expandExplicitBinders `Exists xs b macro "exists" xs:explicitBinders ", " b:term : term => expandExplicitBinders `Exists xs b macro "Σ" xs:explicitBinders ", " b:term : term => expandExplicitBinders `Sigma xs b macro "Σ'" xs:explicitBinders ", " b:term : term => expandExplicitBinders `PSigma xs b macro:25 xs:bracketedExplicitBinders "×" b:term : term => expandBrackedBinders `Sigma xs b macro:25 xs:bracketedExplicitBinders "×'" b:term : term => expandBrackedBinders `PSigma xs b syntax "funext " (colGt term:max)+ : tactic macro_rules | `(tactic|funext $xs*) => if xs.size == 1 then `(tactic| apply funext; intro $(xs[0]):term) else `(tactic| apply funext; intro $(xs[0]):term; funext $(xs[1:])*)
3e3278425840326417d7c6753b18d41702d91399
86d27503307c38df1c2f623003db02428c647dc6
/library/init/meta/default.lean
73e7e69931de3b3c37d809803f40ef81b19aa22f
[ "Apache-2.0" ]
permissive
david-christiansen/lean
ec01bce37268b3e442272832ea955c48a8b92a92
89136339ff8c551a2313b22e92d38c1d76d33606
refs/heads/master
1,594,457,625,583
1,497,312,913,000
1,497,325,368,000
94,268,567
0
0
null
1,497,397,719,000
1,497,397,719,000
null
UTF-8
Lean
false
false
933
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.name init.meta.options init.meta.format init.meta.rb_map import init.meta.level init.meta.expr init.meta.environment init.meta.attribute import init.meta.tactic init.meta.contradiction_tactic init.meta.constructor_tactic import init.meta.injection_tactic init.meta.relation_tactics init.meta.fun_info import init.meta.congr_lemma init.meta.match_tactic init.meta.ac_tactics import init.meta.backward init.meta.rewrite_tactic import init.meta.mk_dec_eq_instance init.meta.mk_inhabited_instance import init.meta.simp_tactic init.meta.set_get_option_tactics import init.meta.interactive init.meta.converter init.meta.vm import init.meta.comp_value_tactics init.meta.smt import init.meta.async_tactic init.meta.ref init.meta.coinductive_predicates
c7c281d2db52b935cbb9d3b7b255b7c64412bc50
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/fubini_auto.lean
8e829dea9a3f4a5ada360683ecbc9853159f4f8a
[]
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
10,739
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.limits.limits import Mathlib.category_theory.products.basic import Mathlib.category_theory.currying import Mathlib.PostPort universes v u l namespace Mathlib /-! # A Fubini theorem for categorical limits We prove that $lim_{J × K} G = lim_J (lim_K G(j, -))$ for a functor `G : J × K ⥤ C`, when all the appropriate limits exist. We begin working with a functor `F : J ⥤ K ⥤ C`. We'll write `G : J × K ⥤ C` for the associated "uncurried" functor. In the first part, given a coherent family `D` of limit cones over the functors `F.obj j`, and a cone `c` over `G`, we construct a cone over the cone points of `D`. We then show that if `c` is a limit cone, the constructed cone is also a limit cone. In the second part, we state the Fubini theorem in the setting where limits are provided by suitable `has_limit` classes. We construct `limit_uncurry_iso_limit_comp_lim F : limit (uncurry.obj F) ≅ limit (F ⋙ lim)` and give simp lemmas characterising it. For convenience, we also provide `limit_iso_limit_curry_comp_lim G : limit G ≅ limit ((curry.obj G) ⋙ lim)` in terms of the uncurried functor. ## Future work The dual statement. -/ namespace category_theory.limits /-- A structure carrying a diagram of cones over the the functors `F.obj j`. -/ -- We could try introducing a "dependent functor type" to handle this? structure diagram_of_cones {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) where obj : (j : J) → cone (functor.obj F j) map : {j j' : J} → (f : j ⟶ j') → functor.obj (cones.postcompose (functor.map F f)) (obj j) ⟶ obj j' id : autoParam (J → cone_morphism.hom (map 𝟙) = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) comp : autoParam (∀ {j₁ j₂ j₃ : J} (f : j₁ ⟶ j₂) (g : j₂ ⟶ j₃), cone_morphism.hom (map (f ≫ g)) = cone_morphism.hom (map f) ≫ cone_morphism.hom (map g)) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) /-- Extract the functor `J ⥤ C` consisting of the cone points and the maps between them, from a `diagram_of_cones`. -/ @[simp] theorem diagram_of_cones.cone_points_obj {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ K ⥤ C} (D : diagram_of_cones F) (j : J) : functor.obj (diagram_of_cones.cone_points D) j = cone.X (diagram_of_cones.obj D j) := Eq.refl (functor.obj (diagram_of_cones.cone_points D) j) /-- Given a diagram `D` of limit cones over the `F.obj j`, and a cone over `uncurry.obj F`, we can construct a cone over the diagram consisting of the cone points from `D`. -/ def cone_of_cone_uncurry {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ K ⥤ C} {D : diagram_of_cones F} (Q : (j : J) → is_limit (diagram_of_cones.obj D j)) (c : cone (functor.obj uncurry F)) : cone (diagram_of_cones.cone_points D) := cone.mk (cone.X c) (nat_trans.mk fun (j : J) => is_limit.lift (Q j) (cone.mk (cone.X c) (nat_trans.mk fun (k : K) => nat_trans.app (cone.π c) (j, k)))) /-- `cone_of_cone_uncurry Q c` is a limit cone when `c` is a limit cone.` -/ def cone_of_cone_uncurry_is_limit {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] {F : J ⥤ K ⥤ C} {D : diagram_of_cones F} (Q : (j : J) → is_limit (diagram_of_cones.obj D j)) {c : cone (functor.obj uncurry F)} (P : is_limit c) : is_limit (cone_of_cone_uncurry Q c) := is_limit.mk fun (s : cone (diagram_of_cones.cone_points D)) => is_limit.lift P (cone.mk (cone.X s) (nat_trans.mk fun (p : J × K) => nat_trans.app (cone.π s) (prod.fst p) ≫ nat_trans.app (cone.π (diagram_of_cones.obj D (prod.fst p))) (prod.snd p))) /-- Given a functor `F : J ⥤ K ⥤ C`, with all needed limits, we can construct a diagram consisting of the limit cone over each functor `F.obj j`, and the universal cone morphisms between these. -/ def diagram_of_cones.mk_of_has_limits {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] : diagram_of_cones F := diagram_of_cones.mk (fun (j : J) => limit.cone (functor.obj F j)) fun (j j' : J) (f : j ⟶ j') => cone_morphism.mk (functor.map lim (functor.map F f)) -- Satisfying the inhabited linter. protected instance diagram_of_cones_inhabited {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] : Inhabited (diagram_of_cones F) := { default := diagram_of_cones.mk_of_has_limits F } @[simp] theorem diagram_of_cones.mk_of_has_limits_cone_points {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] : diagram_of_cones.cone_points (diagram_of_cones.mk_of_has_limits F) = F ⋙ lim := rfl /-- The Fubini theorem for a functor `F : J ⥤ K ⥤ C`, showing that the limit of `uncurry.obj F` can be computed as the limit of the limits of the functors `F.obj j`. -/ def limit_uncurry_iso_limit_comp_lim {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] [has_limit (functor.obj uncurry F)] [has_limit (F ⋙ lim)] : limit (functor.obj uncurry F) ≅ limit (F ⋙ lim) := let c : cone (functor.obj uncurry F) := limit.cone (functor.obj uncurry F); let P : is_limit c := limit.is_limit (functor.obj uncurry F); let G : diagram_of_cones F := diagram_of_cones.mk_of_has_limits F; let Q : (j : J) → is_limit (diagram_of_cones.obj G j) := fun (j : J) => limit.is_limit (functor.obj F j); is_limit.cone_point_unique_up_to_iso (cone_of_cone_uncurry_is_limit Q P) (limit.is_limit (F ⋙ lim)) @[simp] theorem limit_uncurry_iso_limit_comp_lim_hom_π_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] [has_limit (functor.obj uncurry F)] [has_limit (F ⋙ lim)] {j : J} {k : K} : iso.hom (limit_uncurry_iso_limit_comp_lim F) ≫ limit.π (F ⋙ lim) j ≫ limit.π (functor.obj F j) k = limit.π (functor.obj uncurry F) (j, k) := sorry @[simp] theorem limit_uncurry_iso_limit_comp_lim_inv_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (F : J ⥤ K ⥤ C) [has_limits_of_shape K C] [has_limit (functor.obj uncurry F)] [has_limit (F ⋙ lim)] {j : J} {k : K} : iso.inv (limit_uncurry_iso_limit_comp_lim F) ≫ limit.π (functor.obj uncurry F) (j, k) = limit.π (F ⋙ lim) j ≫ limit.π (functor.obj F j) k := sorry /-- The Fubini theorem for a functor `G : J × K ⥤ C`, showing that the limit of `G` can be computed as the limit of the limits of the functors `G.obj (j, _)`. -/ def limit_iso_limit_curry_comp_lim {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits_of_shape K C] [has_limit G] [has_limit (functor.obj curry G ⋙ lim)] : limit G ≅ limit (functor.obj curry G ⋙ lim) := has_limit.iso_of_nat_iso (iso.app (equivalence.unit_iso (equivalence.symm currying)) G) ≪≫ limit_uncurry_iso_limit_comp_lim (functor.obj curry G) @[simp] theorem limit_iso_limit_curry_comp_lim_hom_π_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits_of_shape K C] [has_limit G] [has_limit (functor.obj curry G ⋙ lim)] {j : J} {k : K} : iso.hom (limit_iso_limit_curry_comp_lim G) ≫ limit.π (functor.obj curry G ⋙ lim) j ≫ limit.π (functor.obj (functor.obj curry G) j) k = limit.π G (j, k) := sorry @[simp] theorem limit_iso_limit_curry_comp_lim_inv_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits_of_shape K C] [has_limit G] [has_limit (functor.obj curry G ⋙ lim)] {j : J} {k : K} : iso.inv (limit_iso_limit_curry_comp_lim G) ≫ limit.π G (j, k) = limit.π (functor.obj curry G ⋙ lim) j ≫ limit.π (functor.obj (functor.obj curry G) j) k := sorry /-- A variant of the Fubini theorem for a functor `G : J × K ⥤ C`, showing that $\lim_k \lim_j G(j,k) ≅ \lim_j \lim_k G(j,k)$. -/ def limit_curry_swap_comp_lim_iso_limit_curry_comp_lim {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits C] : limit (functor.obj curry (prod.swap K J ⋙ G) ⋙ lim) ≅ limit (functor.obj curry G ⋙ lim) := (iso.symm (limit_iso_limit_curry_comp_lim (prod.swap K J ⋙ G)) ≪≫ has_limit.iso_of_equivalence (prod.braiding K J) (iso.refl (equivalence.functor (prod.braiding K J) ⋙ G))) ≪≫ limit_iso_limit_curry_comp_lim G @[simp] theorem limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_hom_π_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits C] {j : J} {k : K} : iso.hom (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G) ≫ limit.π (functor.obj curry G ⋙ lim) j ≫ limit.π (functor.obj (functor.obj curry G) j) k = limit.π (functor.obj curry (prod.swap K J ⋙ G) ⋙ lim) k ≫ limit.π (functor.obj (functor.obj curry (prod.swap K J ⋙ G)) k) j := sorry @[simp] theorem limit_curry_swap_comp_lim_iso_limit_curry_comp_lim_inv_π_π {J : Type v} {K : Type v} [small_category J] [small_category K] {C : Type u} [category C] (G : J × K ⥤ C) [has_limits C] {j : J} {k : K} : iso.inv (limit_curry_swap_comp_lim_iso_limit_curry_comp_lim G) ≫ limit.π (functor.obj curry (prod.swap K J ⋙ G) ⋙ lim) k ≫ limit.π (functor.obj (functor.obj curry (prod.swap K J ⋙ G)) k) j = limit.π (functor.obj curry G ⋙ lim) j ≫ limit.π (functor.obj (functor.obj curry G) j) k := sorry end Mathlib
f624cffcb44a51ada785727bb55fcb1efec6cbc9
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/tacticTests.lean
196b419aa66a42fd46800a275518e55fedfb8db6
[ "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
2,470
lean
inductive Le (m : Nat) : Nat → Prop | base : Le m m | succ : (n : Nat) → Le m n → Le m n.succ theorem ex1 (m : Nat) : Le m 0 → m = 0 := by intro h cases h rfl theorem ex2 (m n : Nat) : Le m n → Le m.succ n.succ := by intro h induction h with | base => apply Le.base | succ n m ih => apply Le.succ apply ih theorem ex3 (m : Nat) : Le 0 m := by induction m with | zero => apply Le.base | succ m ih => apply Le.succ apply ih theorem ex4 (m : Nat) : ¬ Le m.succ 0 := by intro h cases h theorem ex5 {m n : Nat} : Le m n.succ → m = n.succ ∨ Le m n := by intro h cases h with | base => apply Or.inl; rfl | succ => apply Or.inr; assumption theorem ex6 {m n : Nat} : Le m.succ n.succ → Le m n := by revert m induction n with | zero => intros m h; cases h with | base => apply Le.base | succ n h => exact absurd h (ex4 _) | succ n ih => intros m h have aux := ih (m := m) cases ex5 h with | inl h => injection h with h subst h apply Le.base | inr h => apply Le.succ exact ih h theorem ex7 {m n o : Nat} : Le m n → Le n o → Le m o := by intro h induction h with | base => intros; assumption | succ n s ih => intro h₂ apply ih apply ex6 apply Le.succ assumption theorem ex8 {m n : Nat} : Le m.succ n → Le m n := by intro h apply ex6 apply Le.succ assumption theorem ex9 {m n : Nat} : Le m n → m = n ∨ Le m.succ n := by intro h cases h with | base => apply Or.inl; rfl | succ n s => apply Or.inr apply ex2 assumption /- theorem ex10 (n : Nat) : ¬ Le n.succ n := by intro h cases h -- TODO: improve cases tactic done -/ theorem ex10 (n : Nat) : n.succ ≠ n := by induction n with | zero => intro h; injection h; done | succ n ih => intro h; injection h with h; apply ih h theorem ex11 (n : Nat) : ¬ Le n.succ n := by induction n with | zero => intro h; cases h; done | succ n ih => intro h have aux := ex6 h exact absurd aux ih done theorem ex12 (m n : Nat) : Le m n → Le n m → m = n := by revert m induction n with | zero => intro m h1 h2; apply ex1; assumption; done | succ n ih => intro m h1 h2 have ih := ih m cases ex5 h1 with | inl h => assumption | inr h => have ih := ih h have h3 := ex8 h2 have ih := ih h3 subst ih apply absurd h2 (ex11 _) done
c12fc65adab5687b502a2bf2c72b7ff376cd9c1e
bf532e3e865883a676110e756f800e0ddeb465be
/data/encodable.lean
812792141f5f6c2b37b86a4aa4a604fd5ef257cc
[ "Apache-2.0" ]
permissive
aqjune/mathlib
da42a97d9e6670d2efaa7d2aa53ed3585dafc289
f7977ff5a6bcf7e5c54eec908364ceb40dafc795
refs/heads/master
1,631,213,225,595
1,521,089,840,000
1,521,089,840,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,918
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Mario Carneiro Type class for encodable Types. Note that every encodable Type is countable. -/ import data.fintype data.list data.list.perm data.list.sort data.equiv data.nat.basic logic.function open option list nat function /-- An encodable type is a "constructively countable" type. This is where we have an explicit injection `encode : α → nat` and a partial inverse `decode : nat → option α`. This makes the range of `encode` decidable, although it is not decidable if `α` is finite or not. -/ class encodable (α : Type*) := (encode : α → nat) (decode : nat → option α) (encodek : ∀ a, decode (encode a) = some a) section encodable variables {α : Type*} {β : Type*} open encodable section variables [encodable α] theorem encode_injective : function.injective (@encode α _) | x y e := option.some.inj $ by rw [← encodek, e, encodek] /- lower priority of instance below because we don't want to use encodability to prove that e.g. equality of nat is decidable. Example of a problem: lemma H (e : ℕ) : finset.range (nat.succ e) = insert e (finset.range e) := begin exact finset.range_succ end fails with this priority not set to zero -/ @[priority 0] instance decidable_eq_of_encodable : decidable_eq α | a b := decidable_of_iff _ encode_injective.eq_iff end def encodable_of_left_injection [h₁ : encodable α] (f : β → α) (finv : α → option β) (linv : ∀ b, finv (f b) = some b) : encodable β := ⟨λ b, encode (f b), λ n, (decode α n).bind finv, λ b, by simp [encodable.encodek, option.bind, linv]⟩ def encodable_of_equiv (α) [h : encodable α] : β ≃ α → encodable β | ⟨f, g, l, r⟩ := encodable_of_left_injection f (λ b, some (g b)) (λ b, by rw l; refl) instance encodable_nat : encodable nat := ⟨id, some, λ a, rfl⟩ instance encodable_empty : encodable empty := ⟨λ a, a.rec _, λ n, none, λ a, a.rec _⟩ instance encodable_unit : encodable unit := ⟨λ_, 0, λn, if n = 0 then some () else none, λ⟨⟩, by simp⟩ instance encodable_option {α : Type*} [h : encodable α] : encodable (option α) := ⟨λ o, match o with | some a := succ (encode a) | none := 0 end, λ n, if n = 0 then some none else some (decode α (pred n)), λ o, by cases o; simp [encodable_option._match_1, encodek, nat.succ_ne_zero]⟩ section sum variables [encodable α] [encodable β] private def encode_sum : sum α β → nat | (sum.inl a) := bit ff $ encode a | (sum.inr b) := bit tt $ encode b private def decode_sum (n : nat) : option (sum α β) := match bodd_div2 n with | (ff, m) := match decode α m with | some a := some (sum.inl a) | none := none end | (tt, m) := match decode β m with | some b := some (sum.inr b) | none := none end end instance encodable_sum : encodable (sum α β) := ⟨encode_sum, decode_sum, λ s, by cases s; simp [encode_sum, decode_sum]; rw [bodd_bit, div2_bit, decode_sum, encodek]; refl⟩ end sum section sigma variables {γ : α → Type*} [encodable α] [∀ a, encodable (γ a)] private def encode_sigma : sigma γ → nat | ⟨a, b⟩ := mkpair (encode a) (encode b) private def decode_sigma (n : nat) : option (sigma γ) := let (n₁, n₂) := unpair n in (decode α n₁).bind $ λ a, (decode (γ a) n₂).map $ sigma.mk a instance encodable_sigma : encodable (sigma γ) := ⟨encode_sigma, decode_sigma, λ ⟨a, b⟩, by simp [encode_sigma, decode_sigma, option.bind, option.map, unpair_mkpair, encodek]⟩ end sigma instance encodable_product [encodable α] [encodable β] : encodable (α × β) := encodable_of_equiv _ (equiv.sigma_equiv_prod α β).symm section list variable [encodable α] private def encode_list : list α → nat | [] := 0 | (a::l) := succ (mkpair (encode_list l) (encode a)) private def decode_list : nat → option (list α) | 0 := some [] | (succ v) := match unpair v, unpair_le v with | (v₂, v₁), h := have v₂ < succ v, from lt_succ_of_le h, (::) <$> decode α v₁ <*> decode_list v₂ end instance encodable_list : encodable (list α) := ⟨encode_list, decode_list, λ l, by induction l with a l IH; simp [encode_list, decode_list, unpair_mkpair, encodek, *]⟩ end list section finset variables [encodable α] private def enle (a b : α) : Prop := encode a ≤ encode b private lemma enle.refl (a : α) : enle a a := le_refl _ private lemma enle.trans (a b c : α) : enle a b → enle b c → enle a c := le_trans private lemma enle.total (a b : α) : enle a b ∨ enle b a := le_total _ _ private lemma enle.antisymm (a b : α) (h₁ : enle a b) (h₂ : enle b a) : a = b := encode_injective (le_antisymm h₁ h₂) private def decidable_enle (a b : α) : decidable (enle a b) := by unfold enle; apply_instance local attribute [instance] decidable_enle private def ensort (l : list α) : list α := insertion_sort enle l open subtype list.perm private lemma sorted_eq_of_perm {l₁ l₂ : list α} (h : l₁ ~ l₂) : ensort l₁ = ensort l₂ := eq_of_sorted_of_perm enle.trans enle.antisymm (perm.trans (perm_insertion_sort _ _) $ perm.trans h (perm_insertion_sort _ _).symm) (sorted_insertion_sort _ enle.total enle.trans _) (sorted_insertion_sort _ enle.total enle.trans _) private def encode_multiset (s : multiset α) : nat := encode $ quot.lift_on s (λ l, ensort l) (λ l₁ l₂ p, sorted_eq_of_perm p) private def decode_multiset (n : nat) : option (multiset α) := coe <$> decode (list α) n instance encodable_multiset : encodable (multiset α) := ⟨encode_multiset, decode_multiset, λ s, quot.induction_on s $ λ l, show coe <$> decode (list α) (encode (ensort l)) = some ↑l, by rw [encodek, ← show (ensort l:multiset α) = l, from quotient.sound (perm_insertion_sort _ _)]; refl⟩ end finset def encodable_of_list [decidable_eq α] (l : list α) (H : ∀ x, x ∈ l) : encodable α := ⟨λ a, index_of a l, l.nth, λ a, index_of_nth (H _)⟩ def trunc_encodable_of_fintype (α : Type*) [decidable_eq α] [fintype α] : trunc (encodable α) := @@quot.rec_on_subsingleton _ (λ s : multiset α, (∀ x:α, x ∈ s) → trunc (encodable α)) _ finset.univ.1 (λ l H, trunc.mk $ encodable_of_list l H) finset.mem_univ section subtype open subtype decidable variable {P : α → Prop} variable [encA : encodable α] variable [decP : decidable_pred P] include encA private def encode_subtype : {a : α // P a} → nat | ⟨v, h⟩ := encode v include decP private def decode_subtype (v : nat) : option {a : α // P a} := match decode α v with | some a := if h : P a then some ⟨a, h⟩ else none | none := none end instance encodable_subtype : encodable {a : α // P a} := ⟨encode_subtype, decode_subtype, λ ⟨v, h⟩, by simp [encode_subtype, decode_subtype, encodek, h]⟩ end subtype instance bool.encodable : encodable bool := encodable_of_equiv _ equiv.bool_equiv_unit_sum_unit instance int.encodable : encodable ℤ := encodable_of_equiv _ equiv.int_equiv_nat instance encodable_finset [encodable α] : encodable (finset α) := encodable_of_equiv {s : multiset α // s.nodup} ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ instance encodable_ulift [encodable α] : encodable (ulift α) := encodable_of_equiv _ equiv.ulift instance encodable_plift [encodable α] : encodable (plift α) := encodable_of_equiv _ equiv.plift noncomputable def encodable_of_inj [encodable β] (f : α → β) (hf : injective f) : encodable α := encodable_of_left_injection f (partial_inv f) (λ x, (partial_inv_of_injective hf _ _).2 rfl) end encodable /- Choice function for encodable types and decidable predicates. We provide the following API choose {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] : (∃ x, p x) → α := choose_spec {α : Type*} {p : α → Prop} [c : encodable α] [d : decidable_pred p] (ex : ∃ x, p x) : p (choose ex) := -/ namespace encodable section find_a variables {α : Type*} (p : α → Prop) [encodable α] [decidable_pred p] private def good : option α → Prop | (some a) := p a | none := false private def decidable_good : decidable_pred (good p) | n := by cases n; unfold good; apply_instance local attribute [instance] decidable_good open encodable variable {p} def choose_x (h : ∃ x, p x) : {a:α // p a} := have ∃ n, good p (decode α n), from let ⟨w, pw⟩ := h in ⟨encode w, by simp [good, encodek, pw]⟩, match _, nat.find_spec this : ∀ o, good p o → {a // p a} with | some a, h := ⟨a, h⟩ end def choose (h : ∃ x, p x) : α := (choose_x h).1 lemma choose_spec (h : ∃ x, p x) : p (choose h) := (choose_x h).2 end find_a theorem axiom_of_choice {α : Type*} {β : α → Type*} {R : Π x, β x → Prop} [Π a, encodable (β a)] [∀ x y, decidable (R x y)] (H : ∀x, ∃y, R x y) : ∃f:Πa, β a, ∀x, R x (f x) := ⟨λ x, choose (H x), λ x, choose_spec (H x)⟩ theorem skolem {α : Type*} {β : α → Type*} {P : Π x, β x → Prop} [c : Π a, encodable (β a)] [d : ∀ x y, decidable (P x y)] : (∀x, ∃y, P x y) ↔ ∃f : Π a, β a, (∀x, P x (f x)) := ⟨axiom_of_choice, λ ⟨f, H⟩ x, ⟨_, H x⟩⟩ end encodable namespace quot open encodable variables {α : Type*} {s : setoid α} [@decidable_rel α (≈)] [encodable α] -- Choose equivalence class representative def rep (q : quotient s) : α := choose (exists_rep q) theorem rep_spec (q : quotient s) : ⟦rep q⟧ = q := choose_spec (exists_rep q) def encodable_quotient : encodable (quotient s) := ⟨λ q, encode (rep q), λ n, quotient.mk <$> decode α n, λ q, quot.induction_on q $ λ l, by rw encodek; exact congr_arg some (rep_spec _)⟩ end quot
36afb172bde6d57140d613c5622998bb933fe89a
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/probability_theory/density.lean
de54ae8c159c6a1f8ecc21e4c0b10deb4833f521
[ "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
18,667
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.decomposition.radon_nikodym import measure_theory.measure.lebesgue /-! # Probability density function This file defines the probability density function of random variables, by which we mean measurable functions taking values in a Borel space. In particular, a measurable function `f` is said to the probability density function of a random variable `X` if for all measurable sets `S`, `ℙ(X ∈ S) = ∫ x in S, f x dx`. Probability density functions are one way of describing the distribution of a random variable, and are useful for calculating probabilities and finding moments (although the latter is better achieved with moment generating functions). This file also defines the continuous uniform distribution and proves some properties about random variables with this distribution. ## Main definitions * `measure_theory.has_pdf` : A random variable `X : α → E` is said to `has_pdf` with respect to the measure `ℙ` on `α` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf` : If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. * `measure_theory.pdf.uniform` : A random variable `X` is said to follow the uniform distribution if it has a constant probability density function with a compact, non-null support. ## Main results * `measure_theory.pdf.integral_fun_mul_eq_integral` : Law of the unconscious statistician, i.e. if a random variable `X : α → E` has pdf `f`, then `𝔼(g(X)) = ∫ x, g x * f x dx` for all measurable `g : E → ℝ`. * `measure_theory.pdf.integral_mul_eq_integral` : A real-valued random variable `X` with pdf `f` has expectation `∫ x, x * f x dx`. * `measure_theory.pdf.uniform.integral_eq` : If `X` follows the uniform distribution with its pdf having support `s`, then `X` has expectation `(λ s)⁻¹ * ∫ x in s, x dx` where `λ` is the Lebesgue measure. ## TODOs Ultimately, we would also like to define characteristic functions to describe distributions as it exists for all random variables. However, to define this, we will need Fourier transforms which we currently do not have. -/ noncomputable theory open_locale classical measure_theory nnreal ennreal namespace measure_theory open topological_space measure_theory.measure variables {α E : Type*} [normed_group E] [measurable_space E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] /-- A random variable `X : α → E` is said to `has_pdf` with respect to the measure `ℙ` on `α` and `μ` on `E` if there exists a measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ class has_pdf {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) : Prop := (pdf' : measurable X ∧ ∃ (f : E → ℝ≥0∞), measurable f ∧ map X ℙ = μ.with_density f) @[measurability] lemma has_pdf.measurable {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measurable X := hX.pdf'.1 /-- If `X` is a random variable that `has_pdf X ℙ μ`, then `pdf X` is the measurable function `f` such that the push-forward measure of `ℙ` along `X` equals `μ.with_density f`. -/ def pdf {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) := if hX : has_pdf X ℙ μ then classical.some hX.pdf'.2 else 0 lemma pdf_undef {m : measurable_space α} {ℙ : measure α} {μ : measure E} {X : α → E} (h : ¬ has_pdf X ℙ μ) : pdf X ℙ μ = 0 := by simp only [pdf, dif_neg h] lemma has_pdf_of_pdf_ne_zero {m : measurable_space α} {ℙ : measure α} {μ : measure E} {X : α → E} (h : pdf X ℙ μ ≠ 0) : has_pdf X ℙ μ := begin by_contra hpdf, rw [pdf, dif_neg hpdf] at h, exact hpdf (false.rec (has_pdf X ℙ μ) (h rfl)) end lemma pdf_eq_zero_of_not_measurable {m : measurable_space α} {ℙ : measure α} {μ : measure E} {X : α → E} (hX : ¬ measurable X) : pdf X ℙ μ = 0 := pdf_undef (λ hpdf, hX hpdf.pdf'.1) lemma measurable_of_pdf_ne_zero {m : measurable_space α} {ℙ : measure α} {μ : measure E} (X : α → E) (h : pdf X ℙ μ ≠ 0) : measurable X := by { by_contra hX, exact h (pdf_eq_zero_of_not_measurable hX) } @[measurability] lemma measurable_pdf {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) : measurable (pdf X ℙ μ) := begin by_cases hX : has_pdf X ℙ μ, { rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).1 }, { rw [pdf, dif_neg hX], exact measurable_zero } end lemma map_eq_with_density_pdf {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] : measure.map X ℙ = μ.with_density (pdf X ℙ μ) := begin rw [pdf, dif_pos hX], exact (classical.some_spec hX.pdf'.2).2 end lemma map_eq_set_lintegral_pdf {m : measurable_space α} (X : α → E) (ℙ : measure α) (μ : measure E . volume_tac) [hX : has_pdf X ℙ μ] {s : set E} (hs : measurable_set s) : measure.map X ℙ s = ∫⁻ x in s, pdf X ℙ μ x ∂μ := by rw [← with_density_apply _ hs, map_eq_with_density_pdf X ℙ μ] namespace pdf variables {m : measurable_space α} {ℙ : measure α} {μ : measure E} lemma lintegral_eq_measure_univ {X : α → E} [has_pdf X ℙ μ] : ∫⁻ x, pdf X ℙ μ x ∂μ = ℙ set.univ := begin rw [← set_lintegral_univ, ← map_eq_set_lintegral_pdf X ℙ μ measurable_set.univ, measure.map_apply (has_pdf.measurable X ℙ μ) measurable_set.univ, set.preimage_univ], end lemma ae_lt_top [is_finite_measure ℙ] {μ : measure E} {X : α → E} : ∀ᵐ x ∂μ, pdf X ℙ μ x < ∞ := begin by_cases hpdf : has_pdf X ℙ μ, { haveI := hpdf, refine ae_lt_top (measurable_pdf X ℙ μ) _, rw lintegral_eq_measure_univ, exact (measure_lt_top _ _).ne }, { rw [pdf, dif_neg hpdf], exact filter.eventually_of_forall (λ x, with_top.zero_lt_top) } end lemma of_real_to_real_ae_eq [is_finite_measure ℙ] {X : α → E} : (λ x, ennreal.of_real (pdf X ℙ μ x).to_real) =ᵐ[μ] pdf X ℙ μ := begin by_cases hpdf : has_pdf X ℙ μ, { exactI of_real_to_real_ae_eq ae_lt_top }, { convert ae_eq_refl _, ext1 x, rw [pdf, dif_neg hpdf, pi.zero_apply, ennreal.zero_to_real, ennreal.of_real_zero] } end lemma integrable_iff_integrable_mul_pdf [is_finite_measure ℙ] {X : α → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : integrable (λ x, f (X x)) ℙ ↔ integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ := begin rw [← integrable_map_measure hf.ae_measurable (has_pdf.measurable X ℙ μ), map_eq_with_density_pdf X ℙ μ, integrable_with_density_iff (measurable_pdf _ _ _) ae_lt_top hf], apply_instance end /-- **The Law of the Unconscious Statistician**: Given a random variable `X` and a measurable function `f`, `f ∘ X` is a random variable with expectation `∫ x, f x * pdf X ∂μ` where `μ` is a measure on the codomain of `X`. -/ lemma integral_fun_mul_eq_integral [is_finite_measure ℙ] {X : α → E} [has_pdf X ℙ μ] {f : E → ℝ} (hf : measurable f) : ∫ x, f x * (pdf X ℙ μ x).to_real ∂μ = ∫ x, f (X x) ∂ℙ := begin by_cases hpdf : integrable (λ x, f x * (pdf X ℙ μ x).to_real) μ, { rw [← integral_map (has_pdf.measurable X ℙ μ) hf.ae_measurable, map_eq_with_density_pdf X ℙ μ, integral_eq_lintegral_pos_part_sub_lintegral_neg_part hpdf, integral_eq_lintegral_pos_part_sub_lintegral_neg_part, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.neg.ennreal_of_real, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf X ℙ μ) hf.ennreal_of_real], { congr' 2, { have : ∀ x, ennreal.of_real (f x * (pdf X ℙ μ x).to_real) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (f x), { intro x, rw [mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) }, { have : ∀ x, ennreal.of_real (- (f x * (pdf X ℙ μ x).to_real)) = ennreal.of_real (pdf X ℙ μ x).to_real * ennreal.of_real (-f x), { intro x, rw [neg_mul_eq_neg_mul, mul_comm, ennreal.of_real_mul ennreal.to_real_nonneg] }, simp_rw [this], exact lintegral_congr_ae (filter.eventually_eq.mul of_real_to_real_ae_eq (ae_eq_refl _)) } }, { refine ⟨hf.ae_measurable, _⟩, rw [has_finite_integral, lintegral_with_density_eq_lintegral_mul _ (measurable_pdf _ _ _) hf.nnnorm.coe_nnreal_ennreal], have : (λ x, (pdf X ℙ μ * λ x, ↑∥f x∥₊) x) =ᵐ[μ] (λ x, ∥f x * (pdf X ℙ μ x).to_real∥₊), { simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul], rw [smul_eq_mul, mul_comm], refine filter.eventually_eq.mul (ae_eq_refl _) (ae_eq_trans of_real_to_real_ae_eq.symm _), convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rw lintegral_congr_ae this, exact hpdf.2 } }, { rw [integral_undef hpdf, integral_undef], rwa ← integrable_iff_integrable_mul_pdf hf at hpdf, all_goals { apply_instance } } end lemma map_absolutely_continuous {X : α → E} [has_pdf X ℙ μ] : map X ℙ ≪ μ := by { rw map_eq_with_density_pdf X ℙ μ, exact with_density_absolutely_continuous _ _, } /-- A random variable that `has_pdf` is quasi-measure preserving. -/ lemma to_quasi_measure_preserving {X : α → E} [has_pdf X ℙ μ] : quasi_measure_preserving X ℙ μ := { measurable := has_pdf.measurable X ℙ μ, absolutely_continuous := map_absolutely_continuous, } lemma have_lebesgue_decomposition_of_has_pdf {X : α → E} [hX' : has_pdf X ℙ μ] : (map X ℙ).have_lebesgue_decomposition μ := ⟨⟨⟨0, pdf X ℙ μ⟩, by simp only [zero_add, measurable_pdf X ℙ μ, true_and, mutually_singular.zero.symm, map_eq_with_density_pdf X ℙ μ] ⟩⟩ lemma has_pdf_iff {X : α → E} : has_pdf X ℙ μ ↔ measurable X ∧ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := begin split, { intro hX', exactI ⟨hX'.pdf'.1, have_lebesgue_decomposition_of_has_pdf, map_absolutely_continuous⟩ }, { rintros ⟨hX, h_decomp, h⟩, haveI := h_decomp, refine ⟨⟨hX, (measure.map X ℙ).rn_deriv μ, measurable_rn_deriv _ _, _⟩⟩, rwa with_density_rn_deriv_eq } end lemma has_pdf_iff_of_measurable {X : α → E} (hX : measurable X) : has_pdf X ℙ μ ↔ (map X ℙ).have_lebesgue_decomposition μ ∧ map X ℙ ≪ μ := by { rw has_pdf_iff, simp only [hX, true_and], } section variables {F : Type*} [normed_group F] [measurable_space F] [second_countable_topology F] [normed_space ℝ F] [complete_space F] [borel_space F] {ν : measure F} /-- A random variable that `has_pdf` transformed under a `quasi_measure_preserving` map also `has_pdf` if `(map g (map X ℙ)).have_lebesgue_decomposition μ`. `quasi_measure_preserving_has_pdf'` is more useful in the case we are working with a probability measure and a real-valued random variable. -/ lemma quasi_measure_preserving_has_pdf {X : α → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) (hmap : (map g (map X ℙ)).have_lebesgue_decomposition ν) : has_pdf (g ∘ X) ℙ ν := begin rw [has_pdf_iff, ← map_map hg.measurable (has_pdf.measurable X ℙ μ)], refine ⟨hg.measurable.comp (has_pdf.measurable X ℙ μ), hmap, _⟩, rw [map_eq_with_density_pdf X ℙ μ], refine absolutely_continuous.mk (λ s hsm hs, _), rw [map_apply hg.measurable hsm, with_density_apply _ (hg.measurable hsm)], have := hg.absolutely_continuous hs, rw map_apply hg.measurable hsm at this, exact set_lintegral_measure_zero _ _ this, end lemma quasi_measure_preserving_has_pdf' [is_finite_measure ℙ] [sigma_finite ν] {X : α → E} [has_pdf X ℙ μ] {g : E → F} (hg : quasi_measure_preserving g μ ν) : has_pdf (g ∘ X) ℙ ν := begin haveI : is_finite_measure (map g (map X ℙ)) := @is_finite_measure_map _ _ _ _ (map X ℙ) (is_finite_measure_map ℙ (has_pdf.measurable X ℙ μ)) _ hg.measurable, exact quasi_measure_preserving_has_pdf hg infer_instance, end end section real variables [is_finite_measure ℙ] {X : α → ℝ} /-- A real-valued random variable `X` `has_pdf X ℙ λ` (where `λ` is the Lebesgue measure) if and only if the push-forward measure of `ℙ` along `X` is absolutely continuous with respect to `λ`. -/ lemma real.has_pdf_iff_of_measurable (hX : measurable X) : has_pdf X ℙ ↔ map X ℙ ≪ volume := begin haveI : is_finite_measure (map X ℙ) := is_finite_measure_map ℙ hX, rw [has_pdf_iff_of_measurable hX, and_iff_right_iff_imp], exact λ h, infer_instance, end lemma real.has_pdf_iff : has_pdf X ℙ ↔ measurable X ∧ map X ℙ ≪ volume := begin by_cases hX : measurable X, { rw [real.has_pdf_iff_of_measurable hX, iff_and_self], exact λ h, hX, apply_instance }, { exact ⟨λ h, false.elim (hX h.pdf'.1), λ h, false.elim (hX h.1)⟩, } end /-- If `X` is a real-valued random variable that has pdf `f`, then the expectation of `X` equals `∫ x, x * f x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_mul_eq_integral [has_pdf X ℙ] : ∫ x, x * (pdf X ℙ volume x).to_real = ∫ x, X x ∂ℙ := integral_fun_mul_eq_integral measurable_id lemma has_finite_integral_mul {f : ℝ → ℝ} {g : ℝ → ℝ≥0∞} (hg : pdf X ℙ =ᵐ[volume] g) (hgi : ∫⁻ x, ∥f x∥₊ * g x ≠ ∞) : has_finite_integral (λ x, f x * (pdf X ℙ volume x).to_real) := begin rw has_finite_integral, have : (λ x, ↑∥f x∥₊ * g x) =ᵐ[volume] (λ x, ∥f x * (pdf X ℙ volume x).to_real∥₊), { refine ae_eq_trans (filter.eventually_eq.mul (ae_eq_refl (λ x, ∥f x∥₊)) (ae_eq_trans hg.symm of_real_to_real_ae_eq.symm)) _, simp_rw [← smul_eq_mul, nnnorm_smul, ennreal.coe_mul, smul_eq_mul], refine filter.eventually_eq.mul (ae_eq_refl _) _, convert ae_eq_refl _, ext1 x, exact real.ennnorm_eq_of_real ennreal.to_real_nonneg }, rwa [lt_top_iff_ne_top, ← lintegral_congr_ae this], end end real section /-! **Uniform Distribution** -/ /-- A random variable `X` has uniform distribution if it has a probability density function `f` with support `s` such that `f = (μ s)⁻¹ 1ₛ` a.e. where `1ₛ` is the indicator function for `s`. -/ def is_uniform {m : measurable_space α} (X : α → E) (support : set E) (ℙ : measure α) (μ : measure E . volume_tac) := pdf X ℙ μ =ᵐ[μ] support.indicator ((μ support)⁻¹ • 1) namespace is_uniform lemma has_pdf {m : measurable_space α} {X : α → E} {ℙ : measure α} {μ : measure E} {support : set E} (hns : μ support ≠ 0) (hnt : μ support ≠ ⊤) (hu : is_uniform X support ℙ μ) : has_pdf X ℙ μ := has_pdf_of_pdf_ne_zero begin intro hpdf, rw [is_uniform, hpdf] at hu, suffices : μ (support ∩ function.support ((μ support)⁻¹ • 1)) = 0, { have heq : function.support ((μ support)⁻¹ • (1 : E → ℝ≥0∞)) = set.univ, { ext x, rw [function.mem_support], simp [hnt] }, rw [heq, set.inter_univ] at this, exact hns this }, exact set.indicator_ae_eq_zero hu.symm, end lemma pdf_to_real_ae_eq {m : measurable_space α} {X : α → E} {ℙ : measure α} {μ : measure E} {s : set E} (hX : is_uniform X s ℙ μ) : (λ x, (pdf X ℙ μ x).to_real) =ᵐ[μ] (λ x, (s.indicator ((μ s)⁻¹ • (1 : E → ℝ≥0∞)) x).to_real) := filter.eventually_eq.fun_comp hX ennreal.to_real variables [is_finite_measure ℙ] {X : α → ℝ} variables {s : set ℝ} (hms : measurable_set s) (hns : volume s ≠ 0) include hms hns lemma mul_pdf_integrable (hcs : is_compact s) (huX : is_uniform X s ℙ) : integrable (λ x : ℝ, x * (pdf X ℙ volume x).to_real) := begin by_cases hsupp : volume s = ∞, { have : pdf X ℙ =ᵐ[volume] 0, { refine ae_eq_trans huX _, simp [hsupp] }, refine integrable.congr (integrable_zero _ _ _) _, rw [(by simp : (λ x, 0 : ℝ → ℝ) = (λ x, x * (0 : ℝ≥0∞).to_real))], refine filter.eventually_eq.mul (ae_eq_refl _) (filter.eventually_eq.fun_comp this.symm ennreal.to_real) }, refine ⟨ae_measurable_id'.mul (measurable_pdf X ℙ).ae_measurable.ennreal_to_real, _⟩, refine has_finite_integral_mul huX _, set ind := (volume s)⁻¹ • (1 : ℝ → ℝ≥0∞) with hind, have : ∀ x, ↑∥x∥₊ * s.indicator ind x = s.indicator (λ x, ∥x∥₊ * ind x) x := λ x, (s.indicator_mul_right (λ x, ↑∥x∥₊) ind).symm, simp only [this, lintegral_indicator _ hms, hind, mul_one, algebra.id.smul_eq_mul, pi.one_apply, pi.smul_apply], rw lintegral_mul_const _ measurable_nnnorm.coe_nnreal_ennreal, { refine (ennreal.mul_lt_top (set_lintegral_lt_top_of_is_compact hsupp hcs continuous_nnnorm).ne (ennreal.inv_lt_top.2 (pos_iff_ne_zero.mpr hns)).ne).ne }, { apply_instance } end /-- A real uniform random variable `X` with support `s` has expectation `(λ s)⁻¹ * ∫ x in s, x ∂λ` where `λ` is the Lebesgue measure. -/ lemma integral_eq (hnt : volume s ≠ ⊤) (huX : is_uniform X s ℙ) : ∫ x, X x ∂ℙ = (volume s)⁻¹.to_real * ∫ x in s, x := begin haveI := has_pdf hns hnt huX, rw ← integral_mul_eq_integral, all_goals { try { apply_instance } }, rw integral_congr_ae (filter.eventually_eq.mul (ae_eq_refl _) (pdf_to_real_ae_eq huX)), have : ∀ x, x * (s.indicator ((volume s)⁻¹ • (1 : ℝ → ℝ≥0∞)) x).to_real = x * (s.indicator ((volume s)⁻¹.to_real • (1 : ℝ → ℝ)) x), { refine λ x, congr_arg ((*) x) _, by_cases hx : x ∈ s, { simp [set.indicator_of_mem hx] }, { simp [set.indicator_of_not_mem hx] }}, simp_rw [this, ← s.indicator_mul_right (λ x, x), integral_indicator hms], change ∫ x in s, x * ((volume s)⁻¹.to_real • 1) ∂(volume) = _, rw [integral_mul_right, mul_comm, algebra.id.smul_eq_mul, mul_one], end . end is_uniform end end pdf end measure_theory
c807de02636bf093369ababc1f50aceed29214b4
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/ring_theory/integral_closure.lean
19825fe69dea29841e7ca6dab62729c7e1970813
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
16,939
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.adjoin /-! # Integral closure of a subring. -/ universes u v open_locale classical open polynomial submodule section variables (R : Type u) {A : Type v} variables [comm_ring R] [comm_ring A] variables [algebra R A] /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : polynomial R`. -/ def is_integral (x : A) : Prop := ∃ p : polynomial R, monic p ∧ aeval R A x p = 0 variables {R} theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := ⟨X - C x, monic_X_sub_C _, by rw [alg_hom.map_sub, aeval_def, aeval_def, eval₂_X, eval₂_C, sub_self]⟩ theorem is_integral_of_subring {x : A} (T : set R) [is_subring T] (hx : is_integral T (algebra.comap.to_comap T R A x)) : is_integral R (x : A) := let ⟨p, hpm, hpx⟩ := hx in ⟨⟨p.support, λ n, (p.to_fun n).1, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, have _ := congr_arg subtype.val H, this, λ H, subtype.eq H⟩)⟩, have _ := congr_arg subtype.val hpm, this, hpx⟩ theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (ring.closure s) (algebra.comap.to_comap (ring.closure s) R A r) := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, exact ⟨_, set.finite_mem_finset _, p.restriction, subtype.eq hmp, hpr⟩ }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A) : submodule R A).fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact is_submonoid.pow_mem (algebra.subset_adjoin (set.mem_singleton _)) }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range at hr, rcases hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_eq q, aeval_def, eval₂_sum, finsupp.sum], refine sum_mem _ (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [finsupp.mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s : submodule R A).fg := set.finite.induction_on hfs (λ _, ⟨{1}, le_antisymm (span_le.2 $ finset.singleton_subset_set_iff.2 $ is_submonoid.one_mem) begin rw submodule.le_def, change ring.closure _ ⊆ _, simp only [set.union_empty, finset.coe_singleton, span_singleton_eq_range, algebra.smul_def, mul_one], exact ring.closure_subset (set.subset.refl _) end⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg_mul _ _ (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his theorem is_integral_of_noetherian' (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : @linear_map R (polynomial R) A _ _ _ _ _ := (aeval R A x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_noetherian (S : subalgebra R A) (H : is_noetherian R (S : submodule R A)) (x : A) (hx : x ∈ S) : is_integral R x := begin letI : algebra R S := S.algebra, letI : comm_ring S := S.comm_ring R A, suffices : is_integral R (⟨x, hx⟩ : S), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg subtype.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, finsupp.sum], rw ← p.support.sum_hom subtype.val, { refine finset.sum_congr rfl (λ n hn, _), change _ = _ * _, rw is_semiring_hom.map_pow coe, refl, split; intros; refl }, refine { map_add := _, map_zero := _ }; intros; refl }, refine is_integral_of_noetherian' H ⟨x, hx⟩ end theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : (S : submodule R A).fg) (x : A) (hx : x ∈ S) : is_integral R x := begin cases HS with y hy, obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, have : ∀ (jk : (↑(y.product y) : set (A × A))), jk.1.1 * jk.1.2 ∈ (span R ↑y : submodule R A), { intros jk, let j : ↥(↑y : set A) := ⟨jk.1.1, (finset.mem_product.1 jk.2).1⟩, let k : ↥(↑y : set A) := ⟨jk.1.2, (finset.mem_product.1 jk.2).2⟩, have hj : j.1 ∈ (span R ↑y : submodule R A) := subset_span j.2, have hk : k.1 ∈ (span R ↑y : submodule R A) := subset_span k.2, revert hj hk, rw hy, exact @is_submonoid.mul_mem A _ S _ j.1 k.1 }, rw ← set.image_id ↑y at this, simp only [finsupp.mem_span_iff_total] at this, choose ly hly1 hly2, let S₀' : finset R := lx.frange ∪ finset.bind finset.univ (finsupp.frange ∘ ly), let S₀ : set R := ring.closure ↑S₀', refine is_integral_of_subring (ring.closure ↑S₀') _, letI : algebra S₀ (algebra.comap S₀ R A) := algebra.comap.algebra _ _ _, letI hmod : module S₀ (algebra.comap S₀ R A) := algebra.to_module, have : (span S₀ (insert 1 (↑y:set A) : set (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)) = (algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)), { apply le_antisymm, { rw [span_le, set.insert_subset, mem_coe], split, change _ ∈ ring.closure _, exact is_submonoid.one_mem, exact algebra.subset_adjoin }, rw [algebra.adjoin_eq_span, span_le], intros r hr, refine monoid.in_closure.rec_on hr _ _ _, { intros r hr, exact subset_span (set.mem_insert_of_mem _ hr) }, { exact subset_span (set.mem_insert _ _) }, intros r1 r2 hr1 hr2 ih1 ih2, rw ← set.image_id (insert _ ↑y) at ih1 ih2, simp only [mem_coe, finsupp.mem_span_iff_total] at ih1 ih2, have ih1' := ih1, have ih2' := ih2, rcases ih1' with ⟨l1, hl1, rfl⟩, rcases ih2' with ⟨l2, hl2, rfl⟩, simp only [finsupp.total_apply, finsupp.sum_mul, finsupp.mul_sum, mem_coe], rw [finsupp.sum], refine sum_mem _ _, intros r2 hr2, rw [finsupp.sum], refine sum_mem _ _, intros r1 hr1, rw [algebra.mul_smul_comm, algebra.smul_mul_assoc], letI : module ↥S₀ A := hmod, refine smul_mem _ _ (smul_mem _ _ _), rcases hl1 hr1 with rfl | hr1, { change 1 * r2 ∈ _, rw one_mul r2, exact subset_span (hl2 hr2) }, rcases hl2 hr2 with rfl | hr2, { change r1 * 1 ∈ _, rw mul_one, exact subset_span (set.mem_insert_of_mem _ hr1) }, let jk : ↥(↑(finset.product y y) : set (A × A)) := ⟨(r1, r2), finset.mem_product.2 ⟨hr1, hr2⟩⟩, specialize hly2 jk, change _ = r1 * r2 at hly2, rw [id, id, ← hly2, finsupp.total_apply], rw [finsupp.sum], refine sum_mem _ _, intros z hz, have : ly jk z ∈ S₀, { apply ring.subset_closure, apply finset.mem_union_right, apply finset.mem_bind.2, exact ⟨jk, finset.mem_univ _, by convert finset.mem_image_of_mem _ hz⟩ }, change @has_scalar.smul S₀ (algebra.comap S₀ R A) hmod.to_has_scalar ⟨ly jk z, this⟩ z ∈ _, exact smul_mem _ _ (subset_span (set.mem_insert_of_mem _ (hly1 _ hz))) }, haveI : is_noetherian_ring ↥S₀ := is_noetherian_ring_closure _ (finset.finite_to_set _), apply is_integral_of_noetherian (algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by rw finset.coe_insert; convert this⟩), show x ∈ ((algebra.adjoin S₀ ((↑y : set A) : set (algebra.comap S₀ R A)) : subalgebra S₀ (algebra.comap S₀ R A)) : submodule S₀ (algebra.comap S₀ R A)), rw [← hlx2, finsupp.total_apply, finsupp.sum], refine sum_mem _ _, intros r hr, rw ← this, have : lx r ∈ ring.closure ↑S₀' := ring.subset_closure (finset.mem_union_left _ (by convert finset.mem_image_of_mem _ hr)), change @has_scalar.smul S₀ (algebra.comap S₀ R A) hmod.to_has_scalar ⟨lx r, this⟩ r ∈ _, rw finsupp.mem_supported at hlx1, exact smul_mem _ _ (subset_span (set.mem_insert_of_mem _ (hlx1 hr))), end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ ring.closure ({x, y} : set A)) : is_integral R z := begin have := fg_mul _ _ (fg_adjoin_singleton_of_integral x hx) (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (ring.closure_mono (set.subset_union_right _ _) hz) end theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).map_zero ▸ is_integral_algebra_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).map_one ▸ is_integral_algebra_map theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := is_integral_of_mem_closure hx hy (is_add_submonoid.add_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := is_integral_of_mem_closure hx hx (is_add_subgroup.neg_mem (ring.subset_closure (or.inl rfl))) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := is_integral_add hx (is_integral_neg hy) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := is_integral_of_mem_closure hx hy (is_submonoid.mul_mem (ring.subset_closure (or.inl rfl)) (ring.subset_closure (or.inr rfl))) variables (R A) def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, subring := { zero_mem := is_integral_zero, one_mem := is_integral_one, add_mem := λ _ _, is_integral_add, neg_mem := λ _, is_integral_neg, mul_mem := λ _ _, is_integral_mul }, range_le' := λ y ⟨x, hx⟩, hx ▸ is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, (M : submodule R A).fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ theorem integral_closure_idem : integral_closure (integral_closure R A : set A) A = ⊥ := begin rw eq_bot_iff, intros r hr, rcases is_integral_iff_is_integral_closure_finite.1 hr with ⟨s, hfs, hr⟩, apply algebra.mem_bot.2, refine ⟨⟨_, _⟩, rfl⟩, refine (mem_integral_closure_iff_mem_fg _ _).2 ⟨algebra.adjoin _ (subtype.val '' s ∪ {r}), algebra.fg_trans (fg_adjoin_of_finite (set.finite_image _ hfs) (λ y ⟨x, hx, hxy⟩, hxy ▸ x.2)) _, algebra.subset_adjoin (or.inr rfl)⟩, refine fg_adjoin_singleton_of_integral _ _, rcases hr with ⟨p, hmp, hpx⟩, refine ⟨to_subring (of_subring _ (of_subring _ p)) _ _, _, hpx⟩, { intros x hx, rcases finsupp.mem_frange.1 hx with ⟨h1, n, rfl⟩, change (coeff p n).1.1 ∈ ring.closure _, rcases ring.exists_list_of_mem_closure (coeff p n).2 with ⟨L, HL1, HL2⟩, rw ← HL2, clear HL2 hfs h1 hx n hmp hpx hr r p, induction L with hd tl ih, { exact is_add_submonoid.zero_mem }, rw list.forall_mem_cons at HL1, rw [list.map_cons, list.sum_cons], refine is_add_submonoid.add_mem _ (ih HL1.2), cases HL1 with HL HL', clear HL' ih tl, induction hd with hd tl ih, { exact is_submonoid.one_mem }, rw list.forall_mem_cons at HL, rw list.prod_cons, refine is_submonoid.mul_mem _ (ih HL.2), rcases HL.1 with hs | rfl, { exact algebra.subset_adjoin (set.mem_image_of_mem _ hs) }, exact is_add_subgroup.neg_mem (is_submonoid.one_mem) }, replace hmp := congr_arg subtype.val hmp, replace hmp := congr_arg subtype.val hmp, exact subtype.eq hmp end end section algebra open algebra variables {R : Type*} {A : Type*} {B : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R A] [algebra A B] lemma is_integral_trans_aux (x : B) {p : polynomial A} (pmonic : monic p) (hp : aeval A B x p = 0) (S : set (comap R A B)) (hS : S = (↑((finset.range (p.nat_degree + 1)).image (λ i, to_comap R A B (p.coeff i))) : set (comap R A B))) : is_integral (adjoin R S) (comap.to_comap R A B x) := begin have coeffs_mem : ∀ i, coeff (map ↑(to_comap R A B) p) i ∈ adjoin R S, { intro i, by_cases hi : i ∈ finset.range (p.nat_degree + 1), { apply algebra.subset_adjoin, subst S, rw [finset.mem_coe, finset.mem_image, coeff_map], exact ⟨i, hi, rfl⟩ }, { rw [finset.mem_range, not_lt] at hi, rw [coeff_map, coeff_eq_zero_of_nat_degree_lt hi, ring_hom.map_zero], exact submodule.zero_mem (adjoin R S : submodule R (comap R A B)) } }, obtain ⟨q, hq⟩ : ∃ q : polynomial (adjoin R S), q.map (algebra_map (adjoin R S) (comap R A B)) = (p.map $ to_comap R A B), { rw [← set.mem_range], dsimp only, apply (polynomial.mem_map_range _).2, { intros i, specialize coeffs_mem i, rw ← subalgebra.mem_coe at coeffs_mem, convert coeffs_mem, exact subtype.val_range } }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) (comap R A B))).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact monic_map _ pmonic } }, { convert hp using 1, replace hq := congr_arg (eval (comap.to_comap R A B x)) hq, convert hq using 1; symmetry; apply eval_map }, end /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : ∀ x : A, is_integral R x) (x : B) (hx : is_integral A x) : is_integral R (comap.to_comap R A B x) := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set (comap R A B) := (↑((finset.range (p.nat_degree + 1)).image (λ i, to_comap R A B (p.coeff i))) : set (comap R A B)), refine is_integral_of_mem_of_fg (adjoin R (S ∪ {comap.to_comap R A B x})) _ _ _, swap, { apply subset_adjoin, simp }, apply fg_trans, { apply fg_adjoin_of_finite, { apply finset.finite_to_set }, intros x hx, rw [finset.mem_coe, finset.mem_image] at hx, rcases hx with ⟨i, hi, rfl⟩, rcases A_int (p.coeff i) with ⟨q, hq, hqx⟩, use [q, hq], replace hqx := congr_arg (to_comap R A B : A → (comap R A B)) hqx, rw alg_hom.map_zero at hqx, convert hqx using 1, symmetry, exact polynomial.hom_eval₂ _ _ _ _ }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp _ rfl } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (A_int : ∀ x : A, is_integral R x)(B_int : ∀ x:B, is_integral A x) : ∀ x:(comap R A B), is_integral R x := λ x, is_integral_trans A_int x (B_int x) end algebra
2e18ccbb98ef94d028483a6ec39b1a8cb8212da8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/mk_simp_attribute.lean
2422f9675391ae99e34a956bd1cc06d8a2230272
[ "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
4,456
lean
/- Copyright (c) 2019 Rob Lewis All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rob Lewis -/ import tactic.doc_commands /-! # User command to register `simp` attributes In this file we define a command `mk_simp_attribute` that can be used to register `simp` sets. We also define all `simp` attributes that are used in the library and tag lemmas from Lean core with these attributes. -/ /-! ### User command -/ section cmd open interactive lean lean.parser namespace tactic /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← (tk "with" *> many ident) <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } end tactic end cmd /-! ### Attributes -/ mk_simp_attribute equiv_rw_simp "The simpset `equiv_rw_simp` is used by the tactic `equiv_rw` to simplify applications of equivalences and their inverses." mk_simp_attribute field_simps "The simpset `field_simps` is used by the tactic `field_simp` to reduce an expression in a field to an expression of the form `n / d` where `n` and `d` are division-free." mk_simp_attribute functor_norm "Simp set for functor_norm" attribute [functor_norm] bind_assoc pure_bind bind_pure mk_simp_attribute ghost_simps "Simplification rules for ghost equations" mk_simp_attribute integral_simps "Simp set for integral rules." mk_simp_attribute is_R_or_C_simps "Simp attribute for lemmas about `is_R_or_C`" mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq and_true true_and function.comp_app and_self eq_self_iff_true function.comp.right_id not_false_iff true_or or_true mk_simp_attribute monad_norm none with functor_norm mk_simp_attribute nontriviality "Simp lemmas for `nontriviality` tactic" mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" mk_simp_attribute push_cast "The `push_cast` simp attribute uses `norm_cast` lemmas to move casts toward the leaf nodes of the expression." mk_simp_attribute split_if_reduction "Simp set for if-then-else statements, used in the `split_ifs` tactic" attribute [split_if_reduction] if_pos if_neg dif_pos dif_neg if_congr mk_simp_attribute transport_simps "The simpset `transport_simps` is used by the tactic `transport` to simplify certain expressions involving application of equivalences, and trivial `eq.rec` or `ep.mpr` conversions. It's probably best not to adjust it without understanding the algorithm used by `transport`." attribute [transport_simps] cast_eq mk_simp_attribute typevec "simp set for the manipulation of typevec and arrow expressions"
755696a2b36d183f20812a2c93259bbaaec15668
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/algebra/spectrum.lean
6b5043020159ebb0dae8b662c87fb3913b4e3d1e
[ "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
15,013
lean
/- Copyright (c) 2021 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import algebra.star.pointwise import algebra.star.subalgebra import tactic.noncomm_ring /-! # Spectrum of an element in an algebra > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file develops the basic theory of the spectrum of an element of an algebra. This theory will serve as the foundation for spectral theory in Banach algebras. ## Main definitions * `resolvent_set a : set R`: the resolvent set of an element `a : A` where `A` is an `R`-algebra. * `spectrum a : set R`: the spectrum of an element `a : A` where `A` is an `R`-algebra. * `resolvent : R → A`: the resolvent function is `λ r, ring.inverse (↑ₐr - a)`, and hence when `r ∈ resolvent R A`, it is actually the inverse of the unit `(↑ₐr - a)`. ## Main statements * `spectrum.unit_smul_eq_smul` and `spectrum.smul_eq_smul`: units in the scalar ring commute (multiplication) with the spectrum, and over a field even `0` commutes with the spectrum. * `spectrum.left_add_coset_eq`: elements of the scalar ring commute (addition) with the spectrum. * `spectrum.unit_mem_mul_iff_mem_swap_mul` and `spectrum.preimage_units_mul_eq_swap_mul`: the units (of `R`) in `σ (a*b)` coincide with those in `σ (b*a)`. * `spectrum.scalar_eq`: in a nontrivial algebra over a field, the spectrum of a scalar is a singleton. ## Notations * `σ a` : `spectrum R a` of `a : A` -/ open set open_locale pointwise universes u v section defs variables (R : Type u) {A : Type v} variables [comm_semiring R] [ring A] [algebra R A] local notation `↑ₐ` := algebra_map R A -- definition and basic properties /-- Given a commutative ring `R` and an `R`-algebra `A`, the *resolvent set* of `a : A` is the `set R` consisting of those `r : R` for which `r•1 - a` is a unit of the algebra `A`. -/ def resolvent_set (a : A) : set R := { r : R | is_unit (↑ₐr - a) } /-- Given a commutative ring `R` and an `R`-algebra `A`, the *spectrum* of `a : A` is the `set R` consisting of those `r : R` for which `r•1 - a` is not a unit of the algebra `A`. The spectrum is simply the complement of the resolvent set. -/ def spectrum (a : A) : set R := (resolvent_set R a)ᶜ variable {R} /-- Given an `a : A` where `A` is an `R`-algebra, the *resolvent* is a map `R → A` which sends `r : R` to `(algebra_map R A r - a)⁻¹` when `r ∈ resolvent R A` and `0` when `r ∈ spectrum R A`. -/ noncomputable def resolvent (a : A) (r : R) : A := ring.inverse (↑ₐr - a) /-- The unit `1 - r⁻¹ • a` constructed from `r • 1 - a` when the latter is a unit. -/ @[simps] noncomputable def is_unit.sub_inv_smul {r : Rˣ} {s : R} {a : A} (h : is_unit $ r • ↑ₐs - a) : Aˣ := { val := ↑ₐs - r⁻¹ • a, inv := r • ↑h.unit⁻¹, val_inv := by rw [mul_smul_comm, ←smul_mul_assoc, smul_sub, smul_inv_smul, h.mul_coe_inv], inv_val := by rw [smul_mul_assoc, ←mul_smul_comm, smul_sub, smul_inv_smul, h.coe_inv_mul], } end defs namespace spectrum section scalar_semiring variables {R : Type u} {A : Type v} variables [comm_semiring R] [ring A] [algebra R A] local notation `σ` := spectrum R local notation `↑ₐ` := algebra_map R A lemma mem_iff {r : R} {a : A} : r ∈ σ a ↔ ¬ is_unit (↑ₐr - a) := iff.rfl lemma not_mem_iff {r : R} {a : A} : r ∉ σ a ↔ is_unit (↑ₐr - a) := by { apply not_iff_not.mp, simp [set.not_not_mem, mem_iff] } variables (R) lemma zero_mem_iff {a : A} : (0 : R) ∈ σ a ↔ ¬is_unit a := by rw [mem_iff, map_zero, zero_sub, is_unit.neg_iff] lemma zero_not_mem_iff {a : A} : (0 : R) ∉ σ a ↔ is_unit a := by rw [zero_mem_iff, not_not] variables {R} lemma mem_resolvent_set_of_left_right_inverse {r : R} {a b c : A} (h₁ : (↑ₐr - a) * b = 1) (h₂ : c * (↑ₐr - a) = 1) : r ∈ resolvent_set R a := units.is_unit ⟨↑ₐr - a, b, h₁, by rwa ←left_inv_eq_right_inv h₂ h₁⟩ lemma mem_resolvent_set_iff {r : R} {a : A} : r ∈ resolvent_set R a ↔ is_unit (↑ₐr - a) := iff.rfl @[simp] lemma resolvent_set_of_subsingleton [subsingleton A] (a : A) : resolvent_set R a = set.univ := by simp_rw [resolvent_set, subsingleton.elim (algebra_map R A _ - a) 1, is_unit_one, set.set_of_true] @[simp] lemma of_subsingleton [subsingleton A] (a : A) : spectrum R a = ∅ := by rw [spectrum, resolvent_set_of_subsingleton, set.compl_univ] lemma resolvent_eq {a : A} {r : R} (h : r ∈ resolvent_set R a) : resolvent a r = ↑h.unit⁻¹ := ring.inverse_unit h.unit lemma units_smul_resolvent {r : Rˣ} {s : R} {a : A} : r • resolvent a (s : R) = resolvent (r⁻¹ • a) (r⁻¹ • s : R) := begin by_cases h : s ∈ spectrum R a, { rw [mem_iff] at h, simp only [resolvent, algebra.algebra_map_eq_smul_one] at *, rw [smul_assoc, ←smul_sub], have h' : ¬ is_unit (r⁻¹ • (s • 1 - a)), from λ hu, h (by simpa only [smul_inv_smul] using is_unit.smul r hu), simp only [ring.inverse_non_unit _ h, ring.inverse_non_unit _ h', smul_zero] }, { simp only [resolvent], have h' : is_unit (r • (algebra_map R A (r⁻¹ • s)) - a), { simpa [algebra.algebra_map_eq_smul_one, smul_assoc] using not_mem_iff.mp h }, rw [←h'.coe_sub_inv_smul, ←(not_mem_iff.mp h).unit_spec, ring.inverse_unit, ring.inverse_unit, h'.coe_inv_sub_inv_smul], simp only [algebra.algebra_map_eq_smul_one, smul_assoc, smul_inv_smul], }, end lemma units_smul_resolvent_self {r : Rˣ} {a : A} : r • resolvent a (r : R) = resolvent (r⁻¹ • a) (1 : R) := by simpa only [units.smul_def, algebra.id.smul_eq_mul, units.inv_mul] using @units_smul_resolvent _ _ _ _ _ r r a /-- The resolvent is a unit when the argument is in the resolvent set. -/ lemma is_unit_resolvent {r : R} {a : A} : r ∈ resolvent_set R a ↔ is_unit (resolvent a r) := is_unit_ring_inverse.symm lemma inv_mem_resolvent_set {r : Rˣ} {a : Aˣ} (h : (r : R) ∈ resolvent_set R (a : A)) : (↑r⁻¹ : R) ∈ resolvent_set R (↑a⁻¹ : A) := begin rw [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one, ←units.smul_def] at h ⊢, rw [is_unit.smul_sub_iff_sub_inv_smul, inv_inv, is_unit.sub_iff], have h₁ : (a : A) * (r • (↑a⁻¹ : A) - 1) = r • 1 - a, { rw [mul_sub, mul_smul_comm, a.mul_inv, mul_one], }, have h₂ : (r • (↑a⁻¹ : A) - 1) * a = r • 1 - a, { rw [sub_mul, smul_mul_assoc, a.inv_mul, one_mul], }, have hcomm : commute (a : A) (r • (↑a⁻¹ : A) - 1), { rwa ←h₂ at h₁ }, exact (hcomm.is_unit_mul_iff.mp (h₁.symm ▸ h)).2, end lemma inv_mem_iff {r : Rˣ} {a : Aˣ} : (r : R) ∈ σ (a : A) ↔ (↑r⁻¹ : R) ∈ σ (↑a⁻¹ : A) := not_iff_not.2 $ ⟨inv_mem_resolvent_set, inv_mem_resolvent_set⟩ lemma zero_mem_resolvent_set_of_unit (a : Aˣ) : 0 ∈ resolvent_set R (a : A) := by simpa only [mem_resolvent_set_iff, ←not_mem_iff, zero_not_mem_iff] using a.is_unit lemma ne_zero_of_mem_of_unit {a : Aˣ} {r : R} (hr : r ∈ σ (a : A)) : r ≠ 0 := λ hn, (hn ▸ hr) (zero_mem_resolvent_set_of_unit a) lemma add_mem_iff {a : A} {r s : R} : r + s ∈ σ a ↔ r ∈ σ (-↑ₐs + a) := by simp only [mem_iff, sub_neg_eq_add, ←sub_sub, map_add] lemma add_mem_add_iff {a : A} {r s : R} : r + s ∈ σ (↑ₐs + a) ↔ r ∈ σ a := by rw [add_mem_iff, neg_add_cancel_left] lemma smul_mem_smul_iff {a : A} {s : R} {r : Rˣ} : r • s ∈ σ (r • a) ↔ s ∈ σ a := by simp only [mem_iff, not_iff_not, algebra.algebra_map_eq_smul_one, smul_assoc, ←smul_sub, is_unit_smul_iff] theorem unit_smul_eq_smul (a : A) (r : Rˣ) : σ (r • a) = r • σ a := begin ext, have x_eq : x = r • r⁻¹ • x, by simp, nth_rewrite 0 x_eq, rw smul_mem_smul_iff, split, { exact λ h, ⟨r⁻¹ • x, ⟨h, by simp⟩⟩}, { rintros ⟨_, _, x'_eq⟩, simpa [←x'_eq],} end -- `r ∈ σ(a*b) ↔ r ∈ σ(b*a)` for any `r : Rˣ` theorem unit_mem_mul_iff_mem_swap_mul {a b : A} {r : Rˣ} : ↑r ∈ σ (a * b) ↔ ↑r ∈ σ (b * a) := begin have h₁ : ∀ x y : A, is_unit (1 - x * y) → is_unit (1 - y * x), { refine λ x y h, ⟨⟨1 - y * x, 1 + y * h.unit.inv * x, _, _⟩, rfl⟩, calc (1 - y * x) * (1 + y * (is_unit.unit h).inv * x) = (1 - y * x) + y * ((1 - x * y) * h.unit.inv) * x : by noncomm_ring ... = 1 : by simp only [units.inv_eq_coe_inv, is_unit.mul_coe_inv, mul_one, sub_add_cancel], calc (1 + y * (is_unit.unit h).inv * x) * (1 - y * x) = (1 - y * x) + y * (h.unit.inv * (1 - x * y)) * x : by noncomm_ring ... = 1 : by simp only [units.inv_eq_coe_inv, is_unit.coe_inv_mul, mul_one, sub_add_cancel]}, simpa only [mem_iff, not_iff_not, algebra.algebra_map_eq_smul_one, ←units.smul_def, is_unit.smul_sub_iff_sub_inv_smul, ←smul_mul_assoc, ←mul_smul_comm r⁻¹ b a] using iff.intro (h₁ (r⁻¹ • a) b) (h₁ b (r⁻¹ • a)), end theorem preimage_units_mul_eq_swap_mul {a b : A} : (coe : Rˣ → R) ⁻¹' σ (a * b) = coe ⁻¹' σ (b * a) := set.ext $ λ _, unit_mem_mul_iff_mem_swap_mul section star variables [has_involutive_star R] [star_ring A] [star_module R A] lemma star_mem_resolvent_set_iff {r : R} {a : A} : star r ∈ resolvent_set R a ↔ r ∈ resolvent_set R (star a) := by refine ⟨λ h, _, λ h, _⟩; simpa only [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one, star_sub, star_smul, star_star, star_one] using is_unit.star h protected lemma map_star (a : A) : σ (star a) = star (σ a) := by { ext, simpa only [set.mem_star, mem_iff, not_iff_not] using star_mem_resolvent_set_iff.symm } end star end scalar_semiring section scalar_ring variables {R : Type u} {A : Type v} variables [comm_ring R] [ring A] [algebra R A] local notation `σ` := spectrum R local notation `↑ₐ` := algebra_map R A -- it would be nice to state this for `subalgebra_class`, but we don't have such a thing yet lemma subset_subalgebra {S : subalgebra R A} (a : S) : spectrum R (a : A) ⊆ spectrum R a := compl_subset_compl.2 (λ _, is_unit.map S.val) -- this is why it would be nice if `subset_subalgebra` was registered for `subalgebra_class`. lemma subset_star_subalgebra [star_ring R] [star_ring A] [star_module R A] {S : star_subalgebra R A} (a : S) : spectrum R (a : A) ⊆ spectrum R a := compl_subset_compl.2 (λ _, is_unit.map S.subtype) lemma singleton_add_eq (a : A) (r : R) : {r} + (σ a) = σ (↑ₐr + a) := ext $ λ x, by rw [singleton_add, image_add_left, mem_preimage, add_comm, add_mem_iff, map_neg, neg_neg] lemma add_singleton_eq (a : A) (r : R) : (σ a) + {r} = σ (a + ↑ₐr) := add_comm {r} (σ a) ▸ add_comm (algebra_map R A r) a ▸ singleton_add_eq a r lemma vadd_eq (a : A) (r : R) : r +ᵥ (σ a) = σ (↑ₐr + a) := (singleton_add).symm.trans $ singleton_add_eq a r lemma neg_eq (a : A) : -(σ a) = σ (-a) := set.ext $ λ x, by simp only [mem_neg, mem_iff, map_neg, ←neg_add', is_unit.neg_iff, sub_neg_eq_add] lemma singleton_sub_eq (a : A) (r : R) : {r} - (σ a) = σ (↑ₐr - a) := by rw [sub_eq_add_neg, neg_eq, singleton_add_eq, sub_eq_add_neg] lemma sub_singleton_eq (a : A) (r : R) : (σ a) - {r} = σ (a - ↑ₐr) := by simpa only [neg_sub, neg_eq] using congr_arg has_neg.neg (singleton_sub_eq a r) end scalar_ring section scalar_field variables {𝕜 : Type u} {A : Type v} variables [field 𝕜] [ring A] [algebra 𝕜 A] local notation `σ` := spectrum 𝕜 local notation `↑ₐ` := algebra_map 𝕜 A /-- Without the assumption `nontrivial A`, then `0 : A` would be invertible. -/ @[simp] lemma zero_eq [nontrivial A] : σ (0 : A) = {0} := begin refine set.subset.antisymm _ (by simp [algebra.algebra_map_eq_smul_one, mem_iff]), rw [spectrum, set.compl_subset_comm], intros k hk, rw set.mem_compl_singleton_iff at hk, have : is_unit (units.mk0 k hk • (1 : A)) := is_unit.smul (units.mk0 k hk) is_unit_one, simpa [mem_resolvent_set_iff, algebra.algebra_map_eq_smul_one] end @[simp] theorem scalar_eq [nontrivial A] (k : 𝕜) : σ (↑ₐk) = {k} := by rw [←add_zero (↑ₐk), ←singleton_add_eq, zero_eq, set.singleton_add_singleton, add_zero] @[simp] lemma one_eq [nontrivial A] : σ (1 : A) = {1} := calc σ (1 : A) = σ (↑ₐ1) : by rw [algebra.algebra_map_eq_smul_one, one_smul] ... = {1} : scalar_eq 1 /-- the assumption `(σ a).nonempty` is necessary and cannot be removed without further conditions on the algebra `A` and scalar field `𝕜`. -/ theorem smul_eq_smul [nontrivial A] (k : 𝕜) (a : A) (ha : (σ a).nonempty) : σ (k • a) = k • (σ a) := begin rcases eq_or_ne k 0 with rfl | h, { simpa [ha, zero_smul_set] }, { exact unit_smul_eq_smul a (units.mk0 k h) }, end theorem nonzero_mul_eq_swap_mul (a b : A) : σ (a * b) \ {0} = σ (b * a) \ {0} := begin suffices h : ∀ (x y : A), σ (x * y) \ {0} ⊆ σ (y * x) \ {0}, { exact set.eq_of_subset_of_subset (h a b) (h b a) }, { rintros _ _ k ⟨k_mem, k_neq⟩, change k with ↑(units.mk0 k k_neq) at k_mem, exact ⟨unit_mem_mul_iff_mem_swap_mul.mp k_mem, k_neq⟩ }, end protected lemma map_inv (a : Aˣ) : (σ (a : A))⁻¹ = σ (↑a⁻¹ : A) := begin refine set.eq_of_subset_of_subset (λ k hk, _) (λ k hk, _), { rw set.mem_inv at hk, have : k ≠ 0, { simpa only [inv_inv] using inv_ne_zero (ne_zero_of_mem_of_unit hk), }, lift k to 𝕜ˣ using is_unit_iff_ne_zero.mpr this, rw ←units.coe_inv k at hk, exact inv_mem_iff.mp hk }, { lift k to 𝕜ˣ using is_unit_iff_ne_zero.mpr (ne_zero_of_mem_of_unit hk), simpa only [units.coe_inv] using inv_mem_iff.mp hk, } end end scalar_field end spectrum namespace alg_hom section comm_semiring variables {F R A B : Type*} [comm_semiring R] [ring A] [algebra R A] [ring B] [algebra R B] variables [alg_hom_class F R A B] local notation `σ` := spectrum R local notation `↑ₐ` := algebra_map R A lemma mem_resolvent_set_apply (φ : F) {a : A} {r : R} (h : r ∈ resolvent_set R a) : r ∈ resolvent_set R ((φ : A → B) a) := by simpa only [map_sub, alg_hom_class.commutes] using h.map φ lemma spectrum_apply_subset (φ : F) (a : A) : σ ((φ : A → B) a) ⊆ σ a := λ _, mt (mem_resolvent_set_apply φ) end comm_semiring section comm_ring variables {F R A B : Type*} [comm_ring R] [ring A] [algebra R A] [ring B] [algebra R B] variables [alg_hom_class F R A R] local notation `σ` := spectrum R local notation `↑ₐ` := algebra_map R A lemma apply_mem_spectrum [nontrivial R] (φ : F) (a : A) : φ a ∈ σ a := begin have h : ↑ₐ(φ a) - a ∈ (φ : A →+* R).ker, { simp only [ring_hom.mem_ker, map_sub, ring_hom.coe_coe, alg_hom_class.commutes, algebra.id.map_eq_id, ring_hom.id_apply, sub_self], }, simp only [spectrum.mem_iff, ←mem_nonunits_iff, coe_subset_nonunits ((φ : A →+* R).ker_ne_top) h], end end comm_ring end alg_hom
98c0571c5b1808994b4932ecdddceaee0bb4a8b4
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Algebra/Ring/Basic.lean
32e40eb4ea6a7d4724e155d903b9c89ee304a1fc
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
5,274
lean
import Mathlib.Algebra.GroupWithZero.Defs import Mathlib.Algebra.Group.Basic import Mathlib.Tactic.Spread /- # Semirings and rings -/ class Numeric (α : Type u) where ofNat : Nat → α instance Numeric.OfNat [Numeric α] : OfNat α n := ⟨Numeric.ofNat n⟩ instance [Numeric α] : Coe ℕ α := ⟨Numeric.ofNat⟩ theorem ofNat_eq_ofNat (α) (n : ℕ) [Numeric α] : Numeric.ofNat (α := α) n = OfNat.ofNat n := rfl class Semiring (R : Type u) extends Semigroup R, AddCommSemigroup R, Numeric R where add_zero (a : R) : a + 0 = a zero_add (a : R) : 0 + a = a nsmul : ℕ → R → R := nsmul_rec nsmul_zero' : ∀ x, nsmul 0 x = 0 -- fill in with tactic once we can do this nsmul_succ' : ∀ (n : ℕ) x, nsmul n.succ x = x + nsmul n x -- fill in with tactic zero_mul (a : R) : 0 * a = 0 mul_zero (a : R) : a * 0 = 0 -- Monoid R one_mul (a : R) : 1 * a = a mul_one (a : R) : a * 1 = a npow : ℕ → R → R := npow_rec npow_zero' : ∀ x, npow 0 x = 1 -- fill in with tactic once we can do this npow_succ' : ∀ (n : ℕ) x, npow n.succ x = x * npow n x -- fill in with tactic mul_add (a b c : R) : a * (b + c) = a * b + a * c add_mul (a b c : R) : (a + b) * c = a * c + b * c ofNat_succ (a : Nat) : ofNat (a + 1) = ofNat a + 1 section Semiring variable {R} [Semiring R] open Numeric instance : MonoidWithZero R where __ := ‹Semiring R› instance : AddCommMonoid R where __ := ‹Semiring R› theorem mul_add (a b c : R) : a * (b + c) = a * b + a * c := Semiring.mul_add a b c theorem add_mul (a b c : R) : (a + b) * c = a * c + b * c := Semiring.add_mul a b c @[simp] lemma ofNat_zero : (ofNat 0 : R) = 0 := rfl @[simp] lemma ofNat_one : (ofNat 1 : R) = 1 := rfl @[simp] lemma ofNat_add : ∀ {a b}, (ofNat (a + b) : R) = ofNat a + ofNat b | a, 0 => (add_zero _).symm | a, b + 1 => trans (Semiring.ofNat_succ _) (by simp [Semiring.ofNat_succ, ofNat_add (b := b), add_assoc]) @[simp] lemma ofNat_mul : ∀ {a b}, (ofNat (a * b) : R) = ofNat a * ofNat b | a, 0 => by simp | a, b + 1 => by simp [Nat.mul_succ, mul_add, (show ofNat (a * b) = ofNat a * ofNat b from ofNat_mul)] @[simp] theorem ofNat_pow (a n : ℕ) : Numeric.ofNat (a^n) = (Numeric.ofNat a : R)^n := by induction n with | zero => rw [pow_zero, Nat.pow_zero] exact rfl | succ n ih => rw [pow_succ, Nat.pow_succ, ofNat_mul, ih] end Semiring class CommSemiring (R : Type u) extends Semiring R where mul_comm (a b : R) : a * b = b * a instance (R : Type u) [CommSemiring R] : CommMonoid R where __ := ‹CommSemiring R› class Ring (R : Type u) extends Semiring R, Neg R, Sub R where -- AddGroup R sub := λ a b => a + -b sub_eq_add_neg : ∀ a b : R, a - b = a + -b gsmul : ℤ → R → R := gsmul_rec gsmul_zero' : ∀ (a : R), gsmul 0 a = 0 gsmul_succ' (n : ℕ) (a : R) : gsmul (Int.ofNat n.succ) a = a + gsmul (Int.ofNat n) a gsmul_neg' (n : ℕ) (a : R) : gsmul (Int.negSucc n) a = -(gsmul ↑(n.succ) a) add_left_neg (a : R) : -a + a = 0 instance {R} [Ring R] : AddCommGroup R := { ‹Ring R› with } class CommRing (R : Type u) extends Ring R where mul_comm (a b : R) : a * b = b * a instance (R : Type u) [CommRing R] : CommSemiring R where __ := inferInstanceAs (Semiring R) __ := ‹CommRing R› /- Instances -/ namespace Nat instance : Numeric Nat := ⟨id⟩ @[simp] theorem ofNat_eq_Nat (n : Nat) : Numeric.ofNat n = n := rfl instance : CommSemiring Nat where mul_comm := Nat.mul_comm mul_add := Nat.left_distrib add_mul := Nat.right_distrib ofNat_succ := fun _ => rfl mul_one := Nat.mul_one one_mul := Nat.one_mul npow (n x) := x ^ n npow_zero' := Nat.pow_zero npow_succ' n x := by simp [Nat.pow_succ, Nat.mul_comm] mul_assoc := Nat.mul_assoc add_comm := Nat.add_comm add_assoc := Nat.add_assoc add_zero := Nat.add_zero zero_add := Nat.zero_add nsmul := (·*·) nsmul_zero' := Nat.zero_mul nsmul_succ' n x := by simp [Nat.add_comm, (Nat.succ_mul n x)] zero_mul := Nat.zero_mul mul_zero := Nat.mul_zero end Nat namespace Int instance : Numeric ℤ := ⟨Int.ofNat⟩ instance : CommRing ℤ where zero_mul := Int.zero_mul mul_zero := Int.mul_zero mul_comm := Int.mul_comm mul_add := Int.distrib_left add_mul := Int.distrib_right ofNat_succ := fun _ => rfl mul_one := Int.mul_one one_mul := Int.one_mul npow (n x) := HPow.hPow x n npow_zero' n := rfl npow_succ' n x := by rw [Int.mul_comm]; rfl mul_assoc := Int.mul_assoc add_comm := Int.add_comm add_assoc := Int.add_assoc add_zero := Int.add_zero zero_add := Int.zero_add add_left_neg := Int.add_left_neg nsmul := (·*·) nsmul_zero' := Int.zero_mul nsmul_succ' n x := by show ofNat (Nat.succ n) * x = x + ofNat n * x rw [Int.ofNat_succ, Int.distrib_right, Int.add_comm, Int.one_mul] sub_eq_add_neg a b := Int.sub_eq_add_neg gsmul := HMul.hMul gsmul_zero' := Int.zero_mul gsmul_succ' n x := by rw [Int.ofNat_succ, Int.distrib_right, Int.add_comm, Int.one_mul] gsmul_neg' n x := by cases x with | ofNat m => rw [Int.negSucc_ofNat_ofNat, Int.ofNat_mul_ofNat] exact rfl | negSucc m => rw [Int.mul_negSucc_ofNat_negSucc_ofNat, Int.ofNat_mul_negSucc_ofNat] exact rfl end Int
2e7af720f28f1cd1c5e11c6cb66b33e2405d19a3
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/04_Quantifiers_and_Equality.org.22.lean
b242a7da2ea37c6293e8ec579566ea6ab494661b
[]
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
418
lean
/- page 56 -/ import standard import data.nat open nat definition is_even (a : nat) := ∃ b, a = 2*b theorem even_plus_even {a b : nat} (H1 : is_even a) (H2 : is_even b) : is_even (a + b) := exists.elim H1 (fun (w1 : nat) (Hw1 : a = 2*w1), exists.elim H2 (fun (w2 : nat) (Hw2 : b = 2*w2), exists.intro (w1 + w2) (calc a + b = 2*w1 + b : Hw1 ... = 2*w1 + 2*w2 : Hw2 ... = 2*(w1 + w2) : mul.left_distrib)))
703df8f881546b5e5072afa222ffee0344911d63
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/08_Building_Theories_and_Proofs.org.42.lean
05f3b1c7ec1dd9d2a631189a102bd7b0779ebdd7
[]
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
146
lean
import standard import data.nat open nat private definition inc (x : nat) := x + 1 private theorem inc_eq_succ (x : nat) : succ x = inc x := rfl
6f3201133eaaa744d857e720140cc030d3067aba
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20161026_ICTAC_Tutorial/ex1.lean
a5e1982970085f07e4e774000a0789e54c7c770a
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
412
lean
/- declare some constants -/ constant m : nat -- m is a natural number constant n : nat constants b1 b2 : bool -- declare two constants at once /- check their types -/ check m -- output: nat check n check n + 0 -- nat check m * (n + 0) -- nat check b1 -- bool check b1 && b2 -- "&&" is boolean and check b1 || b2 -- boolean or check tt -- boolean "true"
81432d26f57eb7ebf2cdeb5258bebb7ee02cd6ce
3618c6e11aa822fd542440674dfb9a7b9921dba0
/scratch/coprod/free_group copy.lean
36afdbfea8e17c70ba8154917e5ff1da8d6f0773
[]
no_license
ChrisHughes24/single_relation
99ceedcc02d236ce46d6c65d72caa669857533c5
057e157a59de6d0e43b50fcb537d66792ec20450
refs/heads/master
1,683,652,062,698
1,683,360,089,000
1,683,360,089,000
279,346,432
0
0
null
null
null
null
UTF-8
Lean
false
false
15,698
lean
import data.list.chain data.int.basic tactic variables {α : Type*} open list def reduced (l : list (α × ℤ)) : Prop := l.chain' (λ a b, a.1 ≠ b.1) ∧ ∀ a : α × ℤ, a ∈ l → a.2 ≠ 0 @[simp] lemma reduced_nil : reduced ([] : list (α × ℤ)) := ⟨list.chain'_nil, λ _, false.elim⟩ lemma reduced_of_reduced_cons {a : α × ℤ} {l : list (α × ℤ)} (h : reduced (a :: l)) : reduced l := ⟨(list.chain'_cons'.1 h.1).2, λ b hb, h.2 _ (mem_cons_of_mem _ hb)⟩ lemma reduced_cons_of_reduced_cons {a : α} {i j : ℤ} {l : list (α × ℤ)} (h : reduced ((a, i) :: l)) (hj : j ≠ 0) : reduced ((a, j) :: l) := ⟨chain'_cons'.2 (chain'_cons'.1 h.1), begin rintros ⟨b, k⟩ hb, cases (mem_cons_iff _ _ _).1 hb with hb hb, { cc }, { exact h.2 _ (mem_cons_of_mem _ hb) } end⟩ lemma reduced_cons_cons {a b : α} {i j : ℤ} {l : list (α × ℤ)} (hab : a ≠ b) (hi : i ≠ 0) (hbl : reduced ((b, j) :: l)) : reduced ((a, i) :: (b, j) :: l) := ⟨chain'_cons.2 ⟨hab, hbl.1⟩, begin rintros ⟨c, k⟩ hc, cases (mem_cons_iff _ _ _).1 hc with hc hc, { cc }, { exact hbl.2 _ hc } end⟩ lemma reduced_reverse {l : list (α × ℤ)} (h : reduced l) : reduced l.reverse := ⟨chain'_reverse.2 $ by {convert h.1, simp [function.funext_iff, eq_comm] }, by simpa using h.2⟩ @[simp] lemma reduced_reverse_iff {l : list (α × ℤ)} : reduced l.reverse ↔ reduced l := ⟨λ h, by convert reduced_reverse h; simp, reduced_reverse⟩ variable (α) def free_group : Type* := {l : list (α × ℤ) // reduced l} namespace free_group instance : has_one (free_group α) := ⟨⟨[], trivial, by simp⟩⟩ variables {α} [decidable_eq α] def rcons : α × ℤ → list (α × ℤ) → list (α × ℤ) | a [] := [a] | a (b::l) := if a.1 = b.1 then let k := a.2 + b.2 in if k = 0 then l else (a.1, k) :: l else a :: b :: l def rconcat (a : α × ℤ) (l : list (α × ℤ)) : list (α × ℤ) := (rcons a l.reverse).reverse lemma reduced_rcons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, a.2 ≠ 0 → reduced l → reduced (rcons a l) | (a, i) [] ha h := ⟨list.chain'_singleton _, by simp [rcons]; cc⟩ | (a, i) ((b, j) :: l) ha h := begin simp [rcons], split_ifs, { exact reduced_of_reduced_cons h }, { subst h_1, exact reduced_cons_of_reduced_cons h h_2 }, { exact reduced_cons_cons h_1 ha h } end lemma reduced_rconcat {a : α × ℤ} {l : list (α × ℤ)} (ha : a.2 ≠ 0) (hl : reduced l) : reduced (rconcat a l) := begin rw [rconcat, reduced_reverse_iff], exact reduced_rcons ha (reduced_reverse hl) end lemma reduced_reduce : ∀ l : list (α × ℤ), reduced (reduce l) | [] := reduced_nil | [a] := begin simp [reduced, reduce], end | (a::l) := begin rw reduce, split_ifs, { exact reduced_reduce l }, { exact reduced_rcons h (reduced_reduce l) } end lemma rcons_eq_cons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, reduced (a :: l) → rcons a l = a :: l | a [] h := rfl | a (b::l) h := if_neg (chain'_cons.1 h.1).1 lemma rconcat_eq_concat {a : α × ℤ} {l : list (α × ℤ)} (h : reduced (l ++ [a])) : rconcat a l = l ++ [a] := begin rw [rconcat, rcons_eq_cons], simp, convert reduced_reverse h, simp, end lemma rcons_reduce_eq_reduce_cons : ∀ {a : α × ℤ} {l : list (α × ℤ)}, a.2 ≠ 0 → rcons a (reduce l) = reduce (a :: l) | a [] ha := by simp [rcons, reduce, ha] | a (b::l) ha := begin rw [reduce], split_ifs, { rw [reduce, if_neg ha, reduce, if_pos h] }, { rw [reduce, if_neg ha, reduce, if_neg h] } end inductive rel : list (α × ℤ) → list (α × ℤ) → Prop | refl : ∀ l, rel l l | zero : ∀ {a : α}, rel [(a, 0)] [] | add : ∀ {a i j}, rel [(a, i), (a, j)] [(a, i + j)] | append : ∀ {l₁ l₂ l₃ l₄}, rel l₁ l₂ → rel l₃ l₄ → rel (l₁ ++ l₃) (l₂ ++ l₄) | symm : ∀ {l₁ l₂}, rel l₁ l₂ → rel l₂ l₁ | trans : ∀ {l₁ l₂ l₃}, rel l₁ l₂ → rel l₂ l₃ → rel l₁ l₃ attribute [refl] rel.refl attribute [symm] rel.symm attribute [trans] rel.trans -- @[refl] lemma rel.refl : ∀ l : list (α × ℤ), rel l l := sorry lemma rel_rcons_cons : ∀ (a : α × ℤ) (l : list (α × ℤ)), rel (rcons a l) (a::l) | a [] := rel.refl _ | (a, i) ((b,j)::l) := begin rw rcons, split_ifs, { replace h : a = b := h, subst h, show rel ([] ++ l) ([(a,i), (a, j)] ++ l), refine rel.append _ (rel.refl _), symmetry, exact rel.add.trans (h_1.symm ▸ rel.zero) }, { replace h : a = b := h, subst h, show rel ([(a, i + j)] ++ l) ([(a, i), (a, j)] ++ l), exact rel.append rel.add.symm (rel.refl _) }, { refl }, end lemma rel_cons_of_rel {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) (a : α × ℤ) : rel (a :: l₁) (a :: l₂) := show rel ([a] ++ l₁) ([a] ++ l₂), from rel.append (rel.refl _) h lemma rel_rcons_cons_of_rel {a : α × ℤ} {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) : rel (rcons a l₁) (a ::l₂) := (rel_rcons_cons a l₁).trans (rel_cons_of_rel h _) lemma rel_reduce : ∀ l : list (α × ℤ), rel l (reduce l) | [] := rel.refl _ | ((a, i)::l) := begin rw reduce, split_ifs, { replace h : i = 0 := h, subst h, show rel ([(a, 0)] ++ l) ([] ++ reduce l), exact rel.append rel.zero (rel_reduce _) }, { exact (rel_rcons_cons_of_rel (rel_reduce _).symm).symm } end lemma reduce_eq_reduce_of_rel {l₁ l₂ : list (α × ℤ)} (h : rel l₁ l₂) : reduce l₁ = reduce l₂ := begin induction h, { refl }, { simp [reduce] }, { simp only [reduce], split_ifs, { refl }, { simp * at * }, { exfalso, omega }, { simp [rcons, *] }, { exfalso, omega }, { simp [rcons, *] }, { simp [rcons, *] }, { simp [rcons, *] } }, { } end lemma reduce_eq_self_of_reduced : ∀ {l : list (α × ℤ)}, reduced l → reduce l = l | [] h := rfl | (a::l) h := by rw [← rcons_reduce_eq_reduce_cons (h.2 a (mem_cons_self _ _)), reduce_eq_self_of_reduced (reduced_of_reduced_cons h), rcons_eq_cons h] lemma rcons_eq_reduce_cons {a : α × ℤ} {l : list (α × ℤ)} (ha : a.2 ≠ 0) (hl : reduced l) : rcons a l = reduce (a :: l) := by rw [← rcons_reduce_eq_reduce_cons ha, reduce_eq_self_of_reduced hl] @[simp] lemma reduce_reduce (l : list (α × ℤ)) : reduce (reduce l) = reduce l := reduce_eq_self_of_reduced (reduced_reduce l) lemma reduce_cons_reduce_eq_reduce_cons (a : α × ℤ) (l : list (α × ℤ)) : reduce (a :: reduce l) = reduce (a :: l) := if ha : a.2 = 0 then by rw [reduce, if_pos ha, reduce, if_pos ha, reduce_reduce] else by rw [← rcons_reduce_eq_reduce_cons ha, ← rcons_reduce_eq_reduce_cons ha, reduce_reduce] lemma reduce_reduce_concat_eq_reduce_concat : ∀ (l : list (α × ℤ)), ∀ (a : α × ℤ), reduce (reduce l ++ [a]) = reduce (l ++ [a]) | [] a := rfl | [a] b := begin simp [reduce], split_ifs; simp [reduce, *, rcons] end | (a::b::l) c := begin simp only [reduce, cons_append], split_ifs, { exact reduce_reduce_concat_eq_reduce_concat _ _ }, { rw [rcons_eq_reduce_cons h_1 (reduced_reduce _), reduce_reduce_concat_eq_reduce_concat, rcons_eq_reduce_cons h_1 (reduced_reduce _), cons_append, ← reduce_cons_reduce_eq_reduce_cons, reduce_reduce_concat_eq_reduce_concat] }, { rw [rcons_eq_reduce_cons h (reduced_reduce _), reduce_reduce_concat_eq_reduce_concat, rcons_eq_reduce_cons h (reduced_reduce _), cons_append, ← reduce_cons_reduce_eq_reduce_cons, reduce_reduce_concat_eq_reduce_concat] }, { rw [rcons_eq_reduce_cons h (reduced_rcons h_1 (reduced_reduce _)), rcons_eq_reduce_cons h_1 (reduced_reduce _), rcons_eq_reduce_cons h (reduced_rcons h_1 (reduced_reduce _)), rcons_eq_reduce_cons h_1 (reduced_reduce _), reduce_cons_reduce_eq_reduce_cons, reduce_cons_reduce_eq_reduce_cons, ← reduce_reduce_concat_eq_reduce_concat l c, ← reduce_cons_reduce_eq_reduce_cons], } end -- list.reverse_rec_on l (by simp [reduce]) -- begin -- assume l b ih a, -- end -- begin -- intro a, -- induction l with b l ih generalizing a, -- { simp [reduce] }, -- { simp [reduce], -- split_ifs, -- { exact ih a }, -- { } } -- end lemma reduce_reduce_append_eq_reduce_append : ∀ {l₁ l₂ : list (α × ℤ)}, reduce (l₁ ++ reduce l₂) = reduce (l₁ ++ l₂) | [] l₂ := by simp | (a::l₁) l₂ := by rw [cons_append, ← reduce_cons_reduce_eq_reduce_cons, reduce_reduce_append_eq_reduce_append, reduce_cons_reduce_eq_reduce_cons, cons_append] lemma reduce_reduce_append_eq_reduce_append' : ∀ (l₁ l₂ : list (α × ℤ)), reduce (reduce l₁ ++ l₂) = reduce (l₁ ++ l₂) | l₁ [] := by simp | l₁ [a] := begin end | l₁ (a::b::l₂) := show reduce (reduce l₁ ++ ([a] ++ (b::l₂))) = reduce (l₁ ++ a :: b::l₂), begin rw [← append_assoc, ← reduce_reduce_append_eq_reduce_append' _ (b :: l₂), reduce_reduce_append_eq_reduce_append' l₁ [a], reduce_reduce_append_eq_reduce_append'], simp end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ x, list.length x.2)⟩] } lemma reduce_reverse : ∀ {l : list (α × ℤ)}, reduce (reverse l) = reverse (reduce l) | [] := rfl | [a] := begin simp [reduce], split_ifs; simp [reduce_cons], end | (a::b::l) := begin rw [reduce], split_ifs, end lemma reduce_reduce_cons : ∀ (a : α × ℤ) (l : list (α × ℤ)), reduce (reduce_cons a l) = reduce (a :: l) | a [] := rfl | a (b::l) := begin simp [reduce, reduce_cons], split_ifs, { refl }, { exfalso, omega }, { exfalso, omega }, { rw [reduce_cons_reduce_eq_reduce_cons h_3, reduce_cons_reduce_eq_reduce_cons h_2], } end def mul_aux : list (α × ℤ) → list (α × ℤ) → list (α × ℤ) | [] l₂ := l₂ | (a :: l₁) l₂ := reduce_cons a (mul_aux l₁ l₂) lemma mul_aux_reduced : ∀ {l₁ l₂ : list (α × ℤ)}, reduced l₁ → reduced l₂ → reduced (mul_aux l₁ l₂) | [] l₂ _ h := h | (a::l₁) l₂ h₁ h₂ := reduced_reduce_cons (h₁.2 _ (mem_cons_self _ _)) (mul_aux_reduced (reduced_of_reduced_cons h₁) h₂) lemma mul_aux_eq_reduce_append : ∀ {l₁ l₂ : list (α × ℤ)}, reduced l₁ → reduced l₂ → mul_aux l₁ l₂ = reduce (l₁ ++ l₂) | [] l₂ _ h := by simp [reduce, mul_aux, reduce_eq_self_of_reduced h] | (a::l₁) l₂ h₁ h₂ := by rw [mul_aux, mul_aux_eq_reduce_append (reduced_of_reduced_cons h₁) h₂, reduce_cons_reduce_eq_reduce_cons (h₁.2 a (mem_cons_self _ _)), cons_append] lemma reduce_cons_append : ∀ {a b : α × ℤ} {l₁ l₂ : list (α × ℤ)}, reduce_cons a ((b::l₁) ++ l₂) = reduce_cons a (b::l₁) ++ l₂ | a b [] l₂ := begin simp [reduce_cons], split_ifs; simp end | a b (c::l₁) l₂ := begin rw [cons_append, reduce_cons], dsimp, split_ifs, { simp [reduce_cons, *] }, { simp [reduce_cons, *] }, { simp [reduce_cons, *] } end lemma mul_aux_reduce_cons : ∀ (a : α) (i : ℤ) (hi : i ≠ 0), ∀ l₁ l₂ : list (α × ℤ), reduced l₁ → reduced l₂ → mul_aux (reduce_cons (a, i) l₁) l₂ = reduce_cons (a, i) (mul_aux l₁ l₂) | a i hi [] l₂ h₁ h₂ := rfl | a i hi ((b, j)::l₁) l₂ h₁ h₂ := begin conv_rhs { }, rw [mul_aux, reduce_cons_eq_reduce_cons (show (a, i).snd ≠ 0, from hi) h₁, reduce_cons_eq_reduce_cons, ← mul_aux_reduce_cons], end -- lemma mul_aux_assoc {l₁ l₂ l₃ : list (α × ℤ)} (h₁ : reduced l₁) (h₂ : reduced l₂) (h₃ : reduced l₃) : -- mul_aux (mul_aux l₁ l₂) l₃ = mul_aux l₁ (mul_aux l₂ l₃) := -- begin -- rw [mul_aux_eq_reduce_append (mul_aux_reduced h₁ h₂) h₃, -- mul_aux_eq_reduce_append h₁ h₂], -- end instance : has_mul (free_group α) := ⟨λ a b : free_group α, ⟨mul_aux a.1 b.1, mul_aux_reduced a.2 b.2⟩⟩ lemma reduce_cons_reduce_cons {a : α} {i j : ℤ} : ∀ {l : list (α × ℤ)}, i + j = 0 → reduce_cons (a, i) (reduce_cons (a, j) l) = l | [] hij := by simp [reduce_cons, hij] | [(c, k)] hij := begin simp [reduce_cons], split_ifs; simp [reduce_cons, add_comm j, add_eq_zero_iff_eq_neg, *] at *, end lemma reduce_cons_reduce_cons {a b : α} {i j : ℤ} : ∀ {l : list (α × ℤ)}, reduced l → i ≠ 0 → j ≠ 0 → reduce_cons (a, i) (reduce_cons (b, j) l) = if a = b then if i + j = 0 then l else reduce_cons (a, i + j) l else (a, i) :: reduce_cons (b, j) | [] hl hi hj := begin split_ifs, simp [reduce_cons, *], simp, end lemma mul_aux_reduce_cons (a : α) (i : ℤ) : ∀ l₁ l₂ : list (α × ℤ), reduced l₁ → reduced l₂ → mul_aux (reduce_cons (a, i) l₁) l₂ = reduce_cons (a, i) (mul_aux l₁ l₂) | [] l₂ h₁ h₂:= rfl | ((b, j) :: l₁) l₂ h₁ h₂ := begin rw [mul_aux, reduce_cons], dsimp only, split_ifs, sorry, end | [(b, j)] [] h₁ h₂ := begin simp [mul_aux, reduce_cons], split_ifs, { refl }, { refl }, { simp [mul_aux, reduce_cons, h] } end | | [(b, j)] [(c, k)] ⟨h₁c, h₁0⟩ ⟨h₂c, h₂0⟩ := begin simp [mul_aux, reduce_cons], split_ifs, { simp [mul_aux, reduce_cons, *], omega }, { simp [mul_aux, reduce_cons, h], split_ifs, { have := h₂0 (c, k) (mem_singleton_self _), omega }, { } } end lemma mul_aux_assoc (l₁ l₂ l₃ : list (α × ℤ)) (h₁ : reduced l₁) (h₂ : reduced l₂) (h₃ : reduced l₃) : mul_aux (mul_aux l₁ l₂) l₃ = mul_aux l₁ (mul_aux l₂ l₃) := begin repeat { rw mul_aux_eq_reduce_append }, rw [reduce_reduce_append_eq_reduce_append] , end lemma mul_aux_assoc : ∀ (l₁ l₂ l₃ : list (α × ℤ)), mul_aux (mul_aux l₁ l₂) l₃ = mul_aux l₁ (mul_aux l₂ l₃) | [] l₂ l₃ := rfl | (a::l₁) l₂ l₃ := begin simp [mul_aux], end def inv_aux (l : list (α × ℤ)) : list (α × ℤ) := l.reverse.map (λ a, (a.1, -a.2)) lemma reduced_inv_aux {l : list (α × ℤ)} (ha : reduced l) : reduced (inv_aux l) := ⟨(list.chain'_map _).2 (list.chain'_reverse.2 begin convert ha, simp [function.funext_iff, eq_comm] end), begin simp [inv_aux, eq_comm] , end⟩ -- instance : has_inv (free_group α) := -- ⟨λ a, ⟨inv_aux a.1, reduced_inv_aux a.2⟩⟩ -- lemma mul_aux_assoc : ∀ l₁ l₂ l₃ : list (α × ℤ), -- mul_aux (mul_aux l₁ l₂) l₃ = mul_aux l₁ (mul_aux l₂ l₃) -- | [] l₂ l₃ := by simp -- | l₁ [] l₃ := by simp -- | l₁ l₂ [] := by simp -- | [(a, i)] [(b, j)] ((c, k) :: l₃) := begin -- simp with mul_aux, -- split_ifs; simp [*, add_assoc] with mul_aux at *, -- end -- | [(a, i)] ((b, j) :: (c, k) :: l₂) l₃ := -- begin -- simp with mul_aux, -- split_ifs; simp * with mul_aux -- end -- | [(a, i), (b, j)] ((c, k) :: l₂) ((d, l) :: l₃) := -- begin -- simp with mul_aux, -- split_ifs; simp [*, add_assoc, ← mul_aux_assoc] with mul_aux at * -- end -- | ((a, i) :: (b, j) :: (c, k) :: l₁) l₂ l₃ := -- begin -- simp only with mul_aux, -- rw [← mul_aux_cons_cons, mul_aux_assoc], -- simp with mul_aux -- end -- lemma mul_aux_inv_aux_cancel : ∀ l₁ : list (α × ℤ), -- mul_aux l₁ (inv_aux l₁) = [] -- | [] := rfl -- | [(a, i)] := by simp [inv_aux] with mul_aux -- | ((a, i) :: (b, j) :: l) := begin -- rw [inv_aux, list.reverse_cons, list.reverse_cons, list.map_append, -- list.map_append, list.map_singleton, list.map_singleton, -- mul_aux_cons_cons], -- end end free_group
da6da54e31cfcf2108517f8791ea67a70b30f089
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/ring_theory/algebra.lean
c3121cd956d70c00c6dd08bf2371ff12d39cc71d
[ "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
54,994
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import data.matrix.basic import linear_algebra.tensor_product import ring_theory.subsemiring import deprecated.subring /-! # Algebra over Commutative Semiring (under category) In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`, algebra equivalences `alg_equiv`, and `subalgebra`s. We also define usual operations on `alg_hom`s (`id`, `comp`) and subalgebras (`map`, `comap`). If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replcaed with `is_scalar_tower`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. * `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`. -/ noncomputable theory universes u v w u₁ v₁ open_locale tensor_product big_operators section prio -- We set this priority to 0 later in this file set_option default_priority 200 -- see Note [default priority] /-- The category of R-algebras where R is a commutative ring is the under category R ↓ CRing. In the categorical setting we have a forgetful functor R-Alg ⥤ R-Mod. However here it extends module in order to preserve definitional equality in certain cases. -/ @[nolint has_inhabited_instance] class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] extends has_scalar R A, R →+* A := (commutes' : ∀ r x, to_fun r * x = x * to_fun r) (smul_def' : ∀ r x, r • x = to_fun r * x) end prio /-- Embedding `R →+* A` given by `algebra` structure. -/ def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A := algebra.to_ring_hom /-- Creating an algebra from a morphism to the center of a semiring. -/ def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S) (h : ∀ c x, i c * x = x * i c) : algebra R S := { smul := λ c x, i c * x, commutes' := h, smul_def' := λ c x, rfl, .. i} /-- Creating an algebra from a morphism to a commutative semiring. -/ def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) : algebra R S := i.to_algebra' $ λ _, mul_comm _ namespace algebra variables {R : Type u} {S : Type v} {A : Type w} /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x) (h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A := { to_fun := λ r, r • 1, map_one' := one_smul _ _, map_mul' := λ r₁ r₂, by rw [h₁, mul_smul], map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul r₁ r₂ 1, commutes' := λ r x, by simp only [h₁, h₂], smul_def' := λ r x, by simp only [h₁] } /-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure. If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A` is an `algebra` over `R`. -/ def of_semimodule [comm_semiring R] [semiring A] [semimodule R A] (h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y)) (h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A := of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one]) section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A] lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x /-- To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree, it suffices to check the `algebra_map`s agree. -/ -- We'll later use this to show `algebra ℤ M` is a subsingleton. @[ext] lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A) (w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) : P = Q := begin unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ }, congr, { funext r a, replace w := congr_arg (λ s, s * a) (w r), simp only [←algebra.smul_def''] at w, apply w, }, { ext r, exact w r, }, { apply proof_irrel_heq, }, { apply proof_irrel_heq, }, end @[priority 200] -- see Note [lower instance priority] instance to_semimodule : semimodule R A := { one_smul := by simp [smul_def''], mul_smul := by simp [smul_def'', mul_assoc], smul_add := by simp [smul_def'', mul_add], smul_zero := by simp [smul_def''], add_smul := by simp [smul_def'', add_mul], zero_smul := by simp [smul_def''] } -- from now on, we don't want to use the following instance anymore attribute [instance, priority 0] algebra.to_has_scalar lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x := algebra.smul_def' r x lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 := calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm ... = r • 1 : (algebra.smul_def r 1).symm theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r := algebra.commutes' r x theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) := by rw [← mul_assoc, ← commutes, mul_assoc] @[simp] lemma mul_smul_comm (s : R) (x y : A) : x * (s • y) = s • (x * y) := by rw [smul_def, smul_def, left_comm] @[simp] lemma smul_mul_assoc (r : R) (x y : A) : (r • x) * y = r • (x * y) := by rw [smul_def, smul_def, mul_assoc] variables (R A) /-- The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`, packaged as an `R`-linear map. -/ protected def linear_map : R →ₗ[R] A := { map_smul' := λ x y, begin dsimp, simp [algebra.smul_def], end, ..algebra_map R A } @[simp] lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl instance id : algebra R R := (ring_hom.id R).to_algebra variables {R A} namespace id @[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl @[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl end id /-- Algebra over a subsemiring. -/ instance of_subsemiring (S : subsemiring R) : algebra S A := { smul := λ s x, (s : R) • x, commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp (subsemiring.subtype S) } /-- Algebra over a subring. -/ instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A] (S : set R) [is_subring S] : algebra S A := { smul := λ s x, (s : R) • x, commutes' := λ r x, algebra.commutes r x, smul_def' := λ r x, algebra.smul_def r x, .. (algebra_map R A).comp (⟨coe, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩ : S →+* R) } lemma subring_coe_algebra_map_hom {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S →+* R) = is_subring.subtype S := rfl lemma subring_coe_algebra_map {R : Type*} [comm_ring R] (S : set R) [is_subring S] : (algebra_map S R : S → R) = subtype.val := rfl lemma subring_algebra_map_apply {R : Type*} [comm_ring R] (S : set R) [is_subring S] (x : S) : algebra_map S R x = x := rfl lemma set_range_subset {R : Type*} [comm_ring R] {T₁ T₂ : set R} [is_subring T₁] (hyp : T₁ ⊆ T₂) : set.range (algebra_map T₁ R) ⊆ T₂ := begin rintros x ⟨⟨t, ht⟩, rfl⟩, exact hyp ht, end variables (R A) /-- The multiplication in an algebra is a bilinear map. -/ def lmul : A →ₗ A →ₗ A := linear_map.mk₂ R (*) (λ x y z, add_mul x y z) (λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y]) (λ x y z, mul_add x y z) (λ c x y, by rw [smul_def, smul_def, left_comm]) /-- The multiplication on the left in an algebra is a linear map. -/ def lmul_left (r : A) : A →ₗ A := lmul R A r /-- The multiplication on the right in an algebra is a linear map. -/ def lmul_right (r : A) : A →ₗ A := (lmul R A).flip r /-- Simultaneous multiplication on the left and right is a linear map. -/ def lmul_left_right (vw: A × A) : A →ₗ[R] A := (lmul_right R A vw.2).comp (lmul_left R A vw.1) /-- The multiplication map on an algebra, as an `R`-linear map from `A ⊗[R] A` to `A`. -/ def lmul' : A ⊗[R] A →ₗ[R] A := tensor_product.lift (algebra.lmul R A) variables {R A} @[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl @[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl @[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl @[simp] lemma lmul_left_right_apply (vw : A × A) (p : A) : lmul_left_right R A vw p = vw.1 * p * vw.2 := rfl @[simp] lemma lmul'_apply {x y} : algebra.lmul' R A (x ⊗ₜ y) = x * y := begin dsimp [algebra.lmul'], simp, end /-- Explicit characterization of the submonoid map in the case of an algebra. `S` is made explicit to help with type inference -/ def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S] (M : submonoid R) : (submonoid S) := submonoid.map (algebra_map R S : R →* S) M lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) : (algebra_map R S x) ∈ algebra_map_submonoid S M := set.mem_image_of_mem (algebra_map R S) x.2 end semiring end algebra namespace module instance endomorphism_algebra (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) := { to_fun := λ r, r • linear_map.id, map_one' := one_smul _ _, map_zero' := zero_smul _ _, map_add' := λ r₁ r₂, add_smul _ _ _, map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] }, commutes' := by { intros, ext, simp }, smul_def' := by { intros, ext, simp } } lemma algebra_map_End_eq_smul_id (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) : (algebra_map R (End R M)) a = a • linear_map.id := rfl lemma algebra_map_End_apply (R : Type u) (M : Type v) [comm_ring R] [add_comm_group M] [module R M] (a : R) (m : M) : (algebra_map R (End R M)) a m = a • m := rfl lemma ker_algebra_map_End (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] (a : K) (ha : a ≠ 0) : ((algebra_map K (End K V)) a).ker = ⊥ := linear_map.ker_smul _ _ ha end module instance matrix_algebra (n : Type u) (R : Type v) [decidable_eq n] [fintype n] [comm_semiring R] : algebra R (matrix n n R) := { commutes' := by { intros, simp [matrix.scalar], }, smul_def' := by { intros, simp [matrix.scalar], }, ..(matrix.scalar n) } set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_inhabited_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩ instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl -- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute. @[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ := by { cases φ₁, cases φ₂, congr, exact H } theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := coe_fn_inj $ funext H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes @[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s := φ.to_ring_hom.map_add r s @[simp] lemma map_zero : φ 0 = 0 := φ.to_ring_hom.map_zero @[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y := φ.to_ring_hom.map_mul x y @[simp] lemma map_one : φ 1 = 1 := φ.to_ring_hom.map_one @[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := by simp only [algebra.smul_def, map_mul, commutes] @[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := φ.to_ring_hom.map_pow x n lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := φ.to_ring_hom.map_sum f s @[simp] lemma map_nat_cast (n : ℕ) : φ n = n := φ.to_ring_hom.map_nat_cast n section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } end @[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ B := { to_fun := φ, map_add' := φ.map_add, map_smul' := φ.map_smul } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ := ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := φ.to_ring_hom.map_prod f s end comm_semiring section ring variables [comm_ring R] [ring A] [ring B] [ring C] variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B) @[simp] lemma map_neg (x) : φ (-x) = -φ x := φ.to_ring_hom.map_neg x @[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y := φ.to_ring_hom.map_sub x y end ring theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : function.injective f ↔ (∀ x, f x = 0 → x = 0) := ring_hom.injective_iff (f : A →+* B) end alg_hom set_option old_structure_cmd true /-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/ structure alg_equiv (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) attribute [nolint doc_blame] alg_equiv.to_ring_equiv attribute [nolint doc_blame] alg_equiv.to_equiv attribute [nolint doc_blame] alg_equiv.to_add_equiv attribute [nolint doc_blame] alg_equiv.to_mul_equiv notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A' namespace alg_equiv variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁} variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃] variables [algebra R A₁] [algebra R A₂] [algebra R A₃] instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩ @[ext] lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : 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 lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) := begin intros f g w, ext, exact congr_fun w a, end instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩ @[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} : (⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) a = to_fun a := rfl @[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₁} : e.to_fun a = e a := rfl @[simp, norm_cast] lemma coe_ring_equiv (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl lemma coe_ring_equiv_injective : function.injective (λ e : A₁ ≃ₐ[R] A₂, (e : A₁ ≃+* A₂)) := begin intros f g w, ext, replace w : ((f : A₁ ≃+* A₂) : A₁ → A₂) = ((g : A₁ ≃+* A₂) : A₁ → A₂) := congr_arg (λ e : A₁ ≃+* A₂, (e : A₁ → A₂)) w, exact congr_fun w a, end @[simp] lemma map_add (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add @[simp] lemma map_zero (e : A₁ ≃ₐ[R] A₂) : e 0 = 0 := e.to_add_equiv.map_zero @[simp] lemma map_mul (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul @[simp] lemma map_one (e : A₁ ≃ₐ[R] A₂) : e 1 = 1 := e.to_mul_equiv.map_one @[simp] lemma commutes (e : A₁ ≃ₐ[R] A₂) : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r := e.commutes' @[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg @[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w} [ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) : ∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub lemma map_sum (e : A₁ ≃ₐ[R] A₂) {ι : Type*} (f : ι → A₁) (s : finset ι) : e (∑ x in s, f x) = ∑ x in s, e (f x) := e.to_add_equiv.map_sum f s instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) := ⟨λ e, { map_one' := e.map_one, map_zero' := e.map_zero, ..e }⟩ @[simp, norm_cast] lemma coe_alg_hom (e : A₁ ≃ₐ[R] A₂) : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e := rfl lemma injective (e : A₁ ≃ₐ[R] A₂) : function.injective e := e.to_equiv.injective lemma surjective (e : A₁ ≃ₐ[R] A₂) : function.surjective e := e.to_equiv.surjective lemma bijective (e : A₁ ≃ₐ[R] A₂) : function.bijective e := e.to_equiv.bijective instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩ instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩ /-- Algebra equivalences are reflexive. -/ @[refl] def refl : A₁ ≃ₐ[R] A₁ := 1 @[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ := alg_hom.ext (λ x, rfl) /-- Algebra equivalences are symmetric. -/ @[symm] def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ := { commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr, change _ = e _, rw e.commutes, }, ..e.to_ring_equiv.symm, } @[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₂} : e.inv_fun a = e.symm a := rfl @[simp] lemma symm_symm {e : A₁ ≃ₐ[R] A₂} : e.symm.symm = e := by { ext, refl, } /-- Algebra equivalences are transitive. -/ @[trans] def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ := { commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'], ..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), } @[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply @[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply @[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) : (e₁.trans e₂) x = e₂ (e₁ x) := rfl @[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ := by { ext, simp } @[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) : alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ := by { ext, simp } /-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/ def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ := { inv_fun := g, left_inv := alg_hom.ext_iff.1 h₂, right_inv := alg_hom.ext_iff.1 h₁, ..f } /-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/ def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ := { .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f } /-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/ def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ := { to_fun := e.to_fun, map_add' := λ x y, by simp, map_smul' := λ r x, by simp [algebra.smul_def''], inv_fun := e.symm.to_fun, left_inv := e.left_inv, right_inv := e.right_inv, } @[simp] lemma to_linear_equiv_apply (e : A₁ ≃ₐ[R] A₂) (x : A₁) : e.to_linear_equiv x = e x := rfl end alg_equiv namespace algebra variables (R : Type u) (S : Type v) (A : Type w) include R S A /-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. -/ /- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and `algebra ?m_1 A -/ /- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the appropriate type classes -/ @[nolint unused_arguments] def comap : Type w := A instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h instance comap.semiring [h : semiring A] : semiring (comap R S A) := h instance comap.ring [h : ring A] : ring (comap R S A) := h instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] : algebra S (comap R S A) := h /-- Identity homomorphism `A →ₐ[S] comap R S A`. -/ def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] : A →ₐ[S] comap R S A := alg_hom.id S A /-- Identity homomorphism `comap R S A →ₐ[S] A`. -/ def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] : comap R S A →ₐ[S] A := alg_hom.id S A variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] /-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/ instance comap.algebra : algebra R (comap R S A) := { smul := λ r x, (algebra_map R S r • x : A), commutes' := λ r x, algebra.commutes _ _, smul_def' := λ _ _, algebra.smul_def _ _, .. (algebra_map S A).comp (algebra_map R S) } /-- Embedding of `S` into `comap R S A`. -/ def to_comap : S →ₐ[R] comap R S A := { commutes' := λ r, rfl, .. algebra_map S A } theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl end algebra namespace alg_hom variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁} variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B) include R /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B := { commutes' := λ r, φ.commutes (algebra_map R S r) ..φ } end alg_hom namespace rat instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α := (rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x end rat /-- A subalgebra is a subring that includes the range of `algebra_map`. -/ structure subalgebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : Type v := (carrier : subsemiring A) (algebra_map_mem' : ∀ r, algebra_map R A r ∈ carrier) namespace subalgebra variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] include R instance : has_coe (subalgebra R A) (subsemiring A) := ⟨λ S, S.carrier⟩ instance : has_mem A (subalgebra R A) := ⟨λ x S, x ∈ (S : set A)⟩ variables {A} theorem mem_coe {x : A} {s : subalgebra R A} : x ∈ (s : set A) ↔ x ∈ s := iff.rfl @[ext] theorem ext {S T : subalgebra R A} (h : ∀ x : A, x ∈ S ↔ x ∈ T) : S = T := by cases S; cases T; congr; ext x; exact h x theorem ext_iff {S T : subalgebra R A} : S = T ↔ ∀ x : A, x ∈ S ↔ x ∈ T := ⟨λ h x, by rw h, ext⟩ variables (S : subalgebra R A) theorem algebra_map_mem (r : R) : algebra_map R A r ∈ S := S.algebra_map_mem' r theorem srange_le : (algebra_map R A).srange ≤ S := λ x ⟨r, _, hr⟩, hr ▸ S.algebra_map_mem r theorem range_subset : set.range (algebra_map R A) ⊆ S := λ x ⟨r, hr⟩, hr ▸ S.algebra_map_mem r theorem range_le : set.range (algebra_map R A) ≤ S := S.range_subset theorem one_mem : (1 : A) ∈ S := subsemiring.one_mem S theorem mul_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x * y ∈ S := subsemiring.mul_mem S hx hy theorem smul_mem {x : A} (hx : x ∈ S) (r : R) : r • x ∈ S := (algebra.smul_def r x).symm ▸ S.mul_mem (S.algebra_map_mem r) hx theorem pow_mem {x : A} (hx : x ∈ S) (n : ℕ) : x ^ n ∈ S := subsemiring.pow_mem S hx n theorem zero_mem : (0 : A) ∈ S := subsemiring.zero_mem S theorem add_mem {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x + y ∈ S := subsemiring.add_mem S hx hy theorem neg_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) : -x ∈ S := neg_one_smul R x ▸ S.smul_mem hx _ theorem sub_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x y : A} (hx : x ∈ S) (hy : y ∈ S) : x - y ∈ S := S.add_mem hx $ S.neg_mem hy theorem nsmul_mem {x : A} (hx : x ∈ S) (n : ℕ) : n •ℕ x ∈ S := subsemiring.nsmul_mem S hx n theorem gsmul_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) {x : A} (hx : x ∈ S) (n : ℤ) : n •ℤ x ∈ S := int.cases_on n (λ i, S.nsmul_mem hx i) (λ i, S.neg_mem $ S.nsmul_mem hx _) theorem coe_nat_mem (n : ℕ) : (n : A) ∈ S := subsemiring.coe_nat_mem S n theorem coe_int_mem {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) (n : ℤ) : (n : A) ∈ S := int.cases_on n (λ i, S.coe_nat_mem i) (λ i, S.neg_mem $ S.coe_nat_mem $ i + 1) theorem list_prod_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.prod ∈ S := subsemiring.list_prod_mem S h theorem list_sum_mem {L : list A} (h : ∀ x ∈ L, x ∈ S) : L.sum ∈ S := subsemiring.list_sum_mem S h theorem multiset_prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.prod ∈ S := subsemiring.multiset_prod_mem S m h theorem multiset_sum_mem {m : multiset A} (h : ∀ x ∈ m, x ∈ S) : m.sum ∈ S := subsemiring.multiset_sum_mem S m h theorem prod_mem {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∏ x in t, f x ∈ S := subsemiring.prod_mem S h theorem sum_mem {ι : Type w} {t : finset ι} {f : ι → A} (h : ∀ x ∈ t, f x ∈ S) : ∑ x in t, f x ∈ S := subsemiring.sum_mem S h instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : is_add_submonoid (S : set A) := { zero_mem := S.zero_mem, add_mem := λ _ _, S.add_mem } instance {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : is_submonoid (S : set A) := { one_mem := S.one_mem, mul_mem := λ _ _, S.mul_mem } instance {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : is_subring (S : set A) := { neg_mem := λ _, S.neg_mem } instance : inhabited S := ⟨0⟩ instance (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : semiring S := subsemiring.to_semiring S instance (R : Type u) (A : Type v) [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : comm_semiring S := subsemiring.to_comm_semiring S instance (R : Type u) (A : Type v) [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : ring S := @@subtype.ring _ S.is_subring instance (R : Type u) (A : Type v) [comm_ring R] [comm_ring A] [algebra R A] (S : subalgebra R A) : comm_ring S := @@subtype.comm_ring _ S.is_subring instance algebra : algebra R S := { smul := λ (c:R) x, ⟨c • x.1, S.smul_mem x.2 c⟩, commutes' := λ c x, subtype.eq $ algebra.commutes _ _, smul_def' := λ c x, subtype.eq $ algebra.smul_def _ _, .. (algebra_map R A).cod_srestrict S $ λ x, S.range_le ⟨x, rfl⟩ } instance to_algebra {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (S : subalgebra R A) : algebra S A := algebra.of_subsemiring _ instance nontrivial [nontrivial A] : nontrivial S := subsemiring.nontrivial S -- todo: standardize on the names these morphisms -- compare with submodule.subtype /-- Embedding of a subalgebra into the algebra. -/ def val : S →ₐ[R] A := by refine_struct { to_fun := (coe : S → A) }; intros; refl @[simp] lemma val_apply (x : S) : S.val x = (x : A) := rfl /-- Convert a `subalgebra` to `submodule` -/ def to_submodule : submodule R A := { carrier := S, zero_mem' := (0:S).2, add_mem' := λ x y hx hy, (⟨x, hx⟩ + ⟨y, hy⟩ : S).2, smul_mem' := λ c x hx, (algebra.smul_def c x).symm ▸ (⟨algebra_map R A c, S.range_le ⟨c, rfl⟩⟩ * ⟨x, hx⟩:S).2 } instance coe_to_submodule : has_coe (subalgebra R A) (submodule R A) := ⟨to_submodule⟩ instance to_submodule.is_subring {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (S : subalgebra R A) : is_subring ((S : submodule R A) : set A) := S.is_subring @[simp] lemma mem_to_submodule {x} : x ∈ (S : submodule R A) ↔ x ∈ S := iff.rfl theorem to_submodule_injective {S U : subalgebra R A} (h : (S : submodule R A) = U) : S = U := ext $ λ x, by rw [← mem_to_submodule, ← mem_to_submodule, h] theorem to_submodule_inj {S U : subalgebra R A} : (S : submodule R A) = U ↔ S = U := ⟨to_submodule_injective, congr_arg _⟩ instance : partial_order (subalgebra R A) := { le := λ S T, (S : set A) ⊆ (T : set A), le_refl := λ S, set.subset.refl S, le_trans := λ _ _ _, set.subset.trans, le_antisymm := λ S T hst hts, ext $ λ x, ⟨@hst x, @hts x⟩ } /-- Reinterpret an `S`-subalgebra as an `R`-subalgebra in `comap R S A`. -/ def comap {R : Type u} {S : Type v} {A : Type w} [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A] (iSB : subalgebra S A) : subalgebra R (algebra.comap R S A) := { carrier := (iSB : subsemiring A), algebra_map_mem' := λ r, iSB.algebra_map_mem (algebra_map R S r) } /-- If `S` is an `R`-subalgebra of `A` and `T` is an `S`-subalgebra of `A`, then `T` is an `R`-subalgebra of `A`. -/ def under {R : Type u} {A : Type v} [comm_semiring R] [comm_semiring A] {i : algebra R A} (S : subalgebra R A) (T : subalgebra S A) : subalgebra R A := { carrier := T, algebra_map_mem' := λ r, T.algebra_map_mem ⟨algebra_map R A r, S.algebra_map_mem r⟩ } /-- Transport a subalgebra via an algebra homomorphism. -/ def map (S : subalgebra R A) (f : A →ₐ[R] B) : subalgebra R B := { carrier := subsemiring.map (f : A →+* B) S, algebra_map_mem' := λ r, f.commutes r ▸ set.mem_image_of_mem _ (S.algebra_map_mem r) } /-- Preimage of a subalgebra under an algebra homomorphism. -/ def comap' (S : subalgebra R B) (f : A →ₐ[R] B) : subalgebra R A := { carrier := subsemiring.comap (f : A →+* B) S, algebra_map_mem' := λ r, show f (algebra_map R A r) ∈ S, from (f.commutes r).symm ▸ S.algebra_map_mem r } theorem map_le {S : subalgebra R A} {f : A →ₐ[R] B} {U : subalgebra R B} : map S f ≤ U ↔ S ≤ comap' U f := set.image_subset_iff instance integral_domain {R A : Type*} [comm_ring R] [integral_domain A] [algebra R A] (S : subalgebra R A) : integral_domain S := @subring.domain A _ S _ end subalgebra namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] variables (φ : A →ₐ[R] B) /-- Range of an `alg_hom` as a subalgebra. -/ protected def range (φ : A →ₐ[R] B) : subalgebra R B := { carrier := { carrier := set.range φ, one_mem' := ⟨1, φ.map_one⟩, mul_mem' := λ _ _ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x * y, by rw [φ.map_mul, hx, hy]⟩, zero_mem' := ⟨0, φ.map_zero⟩, add_mem' := λ _ _ ⟨x, hx⟩ ⟨y, hy⟩, ⟨x + y, by rw [φ.map_add, hx, hy]⟩ }, algebra_map_mem' := λ r, ⟨algebra_map R A r, φ.commutes r⟩ } /-- Restrict the codomain of an algebra homomorphism. -/ def cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : A →ₐ[R] S := { commutes' := λ r, subtype.eq $ f.commutes r, .. ring_hom.cod_srestrict (f : A →+* B) S hf } theorem injective_cod_restrict (f : A →ₐ[R] B) (S : subalgebra R B) (hf : ∀ x, f x ∈ S) : function.injective (f.cod_restrict S hf) ↔ function.injective f := ⟨λ H x y hxy, H $ subtype.eq hxy, λ H x y hxy, H (congr_arg subtype.val hxy : _)⟩ end alg_hom namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace algebra variables (R : Type u) {A : Type v} {B : Type w} variables [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] /-- The minimal subalgebra that includes `s`. -/ def adjoin (s : set A) : subalgebra R A := { carrier := subsemiring.closure (set.range (algebra_map R A) ∪ s), algebra_map_mem' := λ r, subsemiring.subset_closure $ or.inl ⟨r, rfl⟩ } variables {R} protected lemma gc : galois_connection (adjoin R : set A → subalgebra R A) coe := λ s S, ⟨λ H, le_trans (le_trans (set.subset_union_right _ _) subsemiring.subset_closure) H, λ H, subsemiring.closure_le.2 $ set.union_subset S.range_subset H⟩ /-- Galois insertion between `adjoin` and `coe`. -/ protected def gi : galois_insertion (adjoin R : set A → subalgebra R A) coe := { choice := λ s hs, adjoin R s, gc := algebra.gc, le_l_u := λ S, (algebra.gc (S : set A) (adjoin R S)).1 $ le_refl _, choice_eq := λ _ _, rfl } instance : complete_lattice (subalgebra R A) := galois_insertion.lift_complete_lattice algebra.gi instance : inhabited (subalgebra R A) := ⟨⊥⟩ theorem mem_bot {x : A} : x ∈ (⊥ : subalgebra R A) ↔ x ∈ set.range (algebra_map R A) := suffices (⊥ : subalgebra R A) = (of_id R A).range, by rw this; refl, le_antisymm bot_le $ subalgebra.range_le _ theorem mem_top {x : A} : x ∈ (⊤ : subalgebra R A) := subsemiring.subset_closure $ or.inr trivial @[simp] theorem coe_top : ((⊤ : subalgebra R A) : submodule R A) = ⊤ := submodule.ext $ λ x, iff_of_true mem_top trivial theorem eq_top_iff {S : subalgebra R A} : S = ⊤ ↔ ∀ x : A, x ∈ S := ⟨λ h x, by rw h; exact mem_top, λ h, by ext x; exact ⟨λ _, mem_top, λ _, h x⟩⟩ @[simp] theorem map_top (f : A →ₐ[R] B) : subalgebra.map (⊤ : subalgebra R A) f = f.range := subalgebra.ext $ λ x, ⟨λ ⟨y, _, hy⟩, ⟨y, hy⟩, λ ⟨y, hy⟩, ⟨y, algebra.mem_top, hy⟩⟩ @[simp] theorem map_bot (f : A →ₐ[R] B) : subalgebra.map (⊥ : subalgebra R A) f = ⊥ := eq_bot_iff.2 $ λ x ⟨y, hy, hfy⟩, let ⟨r, hr⟩ := mem_bot.1 hy in subalgebra.range_le _ ⟨r, by rwa [← f.commutes, hr]⟩ @[simp] theorem comap_top (f : A →ₐ[R] B) : subalgebra.comap' (⊤ : subalgebra R B) f = ⊤ := eq_top_iff.2 $ λ x, mem_top /-- `alg_hom` to `⊤ : subalgebra R A`. -/ def to_top : A →ₐ[R] (⊤ : subalgebra R A) := by refine_struct { to_fun := λ x, (⟨x, mem_top⟩ : (⊤ : subalgebra R A)) }; intros; refl theorem surjective_algbera_map_iff : function.surjective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, eq_bot_iff.2 $ λ y _, let ⟨x, hx⟩ := h y in hx ▸ subalgebra.algebra_map_mem _ _, λ h y, algebra.mem_bot.1 $ eq_bot_iff.1 h (algebra.mem_top : y ∈ _)⟩ theorem bijective_algbera_map_iff {R A : Type*} [field R] [semiring A] [nontrivial A] [algebra R A] : function.bijective (algebra_map R A) ↔ (⊤ : subalgebra R A) = ⊥ := ⟨λ h, surjective_algbera_map_iff.1 h.2, λ h, ⟨(algebra_map R A).injective, surjective_algbera_map_iff.2 h⟩⟩ /-- The bottom subalgebra is isomorphic to the base ring. -/ def bot_equiv_of_injective (h : function.injective (algebra_map R A)) : (⊥ : subalgebra R A) ≃ₐ[R] R := alg_equiv.symm $ alg_equiv.of_bijective (algebra.of_id R _) ⟨λ x y hxy, h (congr_arg subtype.val hxy : _), λ ⟨y, hy⟩, let ⟨x, hx⟩ := algebra.mem_bot.1 hy in ⟨x, subtype.eq hx⟩⟩ /-- The bottom subalgebra is isomorphic to the field. -/ def bot_equiv (F R : Type*) [field F] [semiring R] [nontrivial R] [algebra F R] : (⊥ : subalgebra F R) ≃ₐ[F] F := bot_equiv_of_injective (ring_hom.injective _) end algebra section nat variables (R : Type*) [semiring R] /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def alg_hom_nat {R : Type u} [semiring R] [algebra ℕ R] {S : Type v} [semiring S] [algebra ℕ S] (f : R →+* S) : R →ₐ[ℕ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- Semiring ⥤ ℕ-Alg -/ instance algebra_nat : algebra ℕ R := { commutes' := nat.cast_commute, smul_def' := λ _ _, nsmul_eq_mul _ _, .. nat.cast_ring_hom R } variables {R} /-- A subsemiring is a `ℕ`-subalgebra. -/ def subalgebra_of_subsemiring (S : subsemiring R) : subalgebra ℕ R := { carrier := S, algebra_map_mem' := λ i, S.coe_nat_mem i } @[simp] lemma mem_subalgebra_of_subsemiring {x : R} {S : subsemiring R} : x ∈ subalgebra_of_subsemiring S ↔ x ∈ S := iff.rfl section span_nat open submodule lemma span_nat_eq_add_group_closure (s : set R) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := eq.symm $ add_submonoid.closure_eq_of_le subset_span $ λ x hx, span_induction hx (λ x hx, add_submonoid.subset_closure hx) (add_submonoid.zero_mem _) (λ _ _, add_submonoid.add_mem _) (λ _ _ _, add_submonoid.nsmul_mem _ ‹_› _) @[simp] lemma span_nat_eq (s : add_submonoid R) : (span ℕ (s : set R)).to_add_submonoid = s := by rw [span_nat_eq_add_group_closure, s.closure_eq] end span_nat end nat section int variables (R : Type*) [ring R] /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def alg_hom_int {R : Type u} [comm_ring R] [algebra ℤ R] {S : Type v} [comm_ring S] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ i, show f _ = _, by simp, .. f } /-- Ring ⥤ ℤ-Alg -/ instance algebra_int : algebra ℤ R := { commutes' := int.cast_commute, smul_def' := λ _ _, gsmul_eq_mul _ _, .. int.cast_ring_hom R } /-- Promote a ring homomorphisms to a `ℤ`-algebra homomorphism. -/ def ring_hom.to_int_alg_hom {R S : Type*} [ring R] [ring S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } variables {R} /-- A subring is a `ℤ`-subalgebra. -/ def subalgebra_of_subring (S : set R) [is_subring S] : subalgebra ℤ R := { carrier := { carrier := S, one_mem' := is_submonoid.one_mem, mul_mem' := λ _ _, is_submonoid.mul_mem, zero_mem' := is_add_submonoid.zero_mem, add_mem' := λ _ _, is_add_submonoid.add_mem, }, algebra_map_mem' := λ i, int.induction_on i (show (0 : R) ∈ S, from is_add_submonoid.zero_mem) (λ i ih, show (i + 1 : R) ∈ S, from is_add_submonoid.add_mem ih is_submonoid.one_mem) (λ i ih, show ((-i - 1 : ℤ) : R) ∈ S, by { rw [int.cast_sub, int.cast_one], exact is_add_subgroup.sub_mem S _ _ ih is_submonoid.one_mem }) } section variables {S : Type*} [ring S] instance int_algebra_subsingleton : subsingleton (algebra ℤ S) := ⟨λ P Q, by { ext, simp, }⟩ end section variables {S : Type*} [semiring S] instance nat_algebra_subsingleton : subsingleton (algebra ℕ S) := ⟨λ P Q, by { ext, simp, }⟩ end @[simp] lemma mem_subalgebra_of_subring {x : R} {S : set R} [is_subring S] : x ∈ subalgebra_of_subring S ↔ x ∈ S := iff.rfl section span_int open submodule lemma span_int_eq_add_group_closure (s : set R) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq (s : add_subgroup R) : (span ℤ (s : set R)).to_add_subgroup = s := by rw [span_int_eq_add_group_closure, s.closure_eq] end span_int end int /-! The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra. We couldn't set this up back in `algebra.pi_instances` because this file imports it. -/ namespace pi variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) variables (I f) instance algebra (α) {r : comm_semiring α} [s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] : algebra α (Π i : I, f i) := { commutes' := λ a f, begin ext, simp [algebra.commutes], end, smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end, ..pi.ring_hom (λ i, algebra_map α (f i)) } @[simp] lemma algebra_map_apply (α) {r : comm_semiring α} [s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] (a : α) (i : I) : algebra_map α (Π i, f i) a i = algebra_map α (f i) a := rfl -- One could also build a `Π i, R i`-algebra structure on `Π i, A i`, -- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful. end pi section is_scalar_tower variables {R : Type*} [comm_semiring R] variables (A : Type*) [semiring A] [algebra R A] variables {M : Type*} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M] variables {N : Type*} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N] lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m := by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul] variable {A} lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m := by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul] @[simp] lemma map_smul_eq_smul_map (f : M →ₗ[A] N) (r : R) (m : M) : f (r • m) = r • f m := by rw [algebra_compatible_smul A r m, linear_map.map_smul, ←algebra_compatible_smul A r (f m)] instance : has_coe (M →ₗ[A] N) (M →ₗ[R] N) := ⟨λ f, ⟨f.to_fun, λ x y, f.map_add' x y, λ r n, map_smul_eq_smul_map _ _ _⟩⟩ end is_scalar_tower section restrict_scalars /- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then `S`-modules are also `R`-modules. -/ section semimodule variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] variables (E : Type*) [add_comm_monoid E] [semimodule S E] variables {F : Type*} [add_comm_monoid F] [semimodule S F] /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, called `module.restrict_scalars' R S E`. We do not register this as an instance as `S` can not be inferred. -/ def semimodule.restrict_scalars' : semimodule R E := { smul := λ c x, (algebra_map R S c) • x, one_smul := by simp, mul_smul := by simp [mul_smul], smul_add := by simp [smul_add], smul_zero := by simp [smul_zero], add_smul := by simp [add_smul], zero_smul := by simp [zero_smul] } /-- When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`. When the `R`-module structure on `E` is registered directly (using `module.restrict_scalars'` for instance, or for `S = ℂ` and `R = ℝ`), theorems on `module.restrict_scalars R S E` can be directly applied to `E` as these types are the same for the kernel. -/ @[nolint unused_arguments] def semimodule.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] : inhabited (semimodule.restrict_scalars R S E) := I instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_monoid E] : add_comm_monoid (semimodule.restrict_scalars R S E) := I instance semimodule.restrict_scalars.module_orig (R : Type*) (S : Type*) [semiring S] (E : Type*) [add_comm_monoid E] [I : semimodule S E] : semimodule S (semimodule.restrict_scalars R S E) := I instance : semimodule R (semimodule.restrict_scalars R S E) := (semimodule.restrict_scalars' R S E : semimodule R E) lemma semimodule.restrict_scalars_smul_def (c : R) (x : semimodule.restrict_scalars R S E) : c • x = ((algebra_map R S c) • x : E) := rfl /-- `module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`. Unfortunately these structures are not generally definitionally equal: the `R`-module structure on `S` is part of the data of `S`, while the `R`-module structure on `module.restrict_scalars R S S` comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`. The field `algebra.smul_def'` gives the equation we need here. -/ def algebra.restrict_scalars_equiv : (semimodule.restrict_scalars R S S) ≃ₗ[R] S := { to_fun := λ s, s, inv_fun := λ s, s, left_inv := λ s, rfl, right_inv := λ s, rfl, map_add' := λ x y, rfl, map_smul' := λ c x, (algebra.smul_def' _ _).symm, } @[simp] lemma algebra.restrict_scalars_equiv_apply (s : S) : algebra.restrict_scalars_equiv R S s = s := rfl @[simp] lemma algebra.restrict_scalars_equiv_symm_apply (s : S) : (algebra.restrict_scalars_equiv R S).symm s = s := rfl variables {S E} open semimodule instance : is_scalar_tower R S (restrict_scalars R S E) := ⟨λ r s e, by { rw [algebra.smul_def, mul_smul], refl }⟩ /-- `V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars, corresponding to `V`, an `S`-submodule of the original `S`-module. -/ @[simps] def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) := { carrier := V.carrier, zero_mem' := V.zero_mem, smul_mem' := λ c e h, V.smul_mem _ h, add_mem' := λ x y hx hy, V.add_mem hx hy, } @[simp] lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) : e ∈ V.restrict_scalars R ↔ e ∈ V := iff.refl _ @[simp] lemma submodule.restrict_scalars_bot : submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ := rfl @[simp] lemma submodule.restrict_scalars_top : submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ := rfl /-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/ def linear_map.restrict_scalars (f : E →ₗ[S] F) : (restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) := { to_fun := f.to_fun, map_add' := λx y, f.map_add x y, map_smul' := λc x, f.map_smul (algebra_map R S c) x } @[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) : (f.restrict_scalars R : E → F) = f := rfl @[simp] lemma restrict_scalars_ker (f : E →ₗ[S] F) : (f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker := rfl end semimodule section module instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] : add_comm_group (semimodule.restrict_scalars R S E) := I end module variables (𝕜 : Type*) [field 𝕜] (𝕜' : Type*) [field 𝕜'] [algebra 𝕜 𝕜'] variables (W : Type*) [add_comm_group W] [vector_space 𝕜' W] /-- `V.restrict_scalars 𝕜` is the `𝕜`-subspace of the `𝕜`-vector space given by restriction of scalars, corresponding to `V`, a `𝕜'`-subspace of the original `𝕜'`-vector space. -/ def subspace.restrict_scalars (V : subspace 𝕜' W) : subspace 𝕜 (semimodule.restrict_scalars 𝕜 𝕜' W) := { ..submodule.restrict_scalars 𝕜 (V : submodule 𝕜' W) } end restrict_scalars section extend_scalars /-! When `V` is an `R`-module and `W` is an `S`-module, where `S` is an algebra over `R`, then the collection of `R`-linear maps from `V` to `W` admits an `S`-module structure, given by multiplication in the target -/ variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule R V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- The set of `R`-linear maps admits an `S`-action by left multiplication -/ instance linear_map.has_scalar_extend_scalars : has_scalar S (V →ₗ[R] (semimodule.restrict_scalars R S W)) := { smul := λ r f, { to_fun := λ v, r • f v, map_add' := by simp [smul_add], map_smul' := λ c x, by rw [linear_map.map_smul, smul_algebra_smul_comm] }} /-- The set of `R`-linear maps is an `S`-module-/ instance linear_map.module_extend_scalars : semimodule S (V →ₗ[R] (semimodule.restrict_scalars R S W)) := { one_smul := λ f, by { ext v, simp [(•)] }, mul_smul := λ r r' f, by { ext v, simp [(•), smul_smul] }, smul_add := λ r f g, by { ext v, simp [(•), smul_add] }, smul_zero := λ r, by { ext v, simp [(•)] }, add_smul := λ r r' f, by { ext v, simp [(•), add_smul] }, zero_smul := λ f, by { ext v, simp [(•)] } } variables {R S V W} /-- When `f` is a linear map taking values in `S`, then `λb, f b • x` is a linear map. -/ def smul_algebra_right (f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) : V →ₗ[R] (semimodule.restrict_scalars R S W) := { to_fun := λb, f b • x, map_add' := by simp [add_smul], map_smul' := λ b y, by { simp [algebra.smul_def, ← smul_smul], refl } } @[simp] theorem smul_algebra_right_apply (f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) (c : V) : smul_algebra_right f x c = f c • x := rfl end extend_scalars /-! When `V` and `W` are `S`-modules, for some `R`-algebra `S`, the collection of `S`-linear maps from `V` to `W` forms an `R`-module. (But not generally an `S`-module, because `S` may be non-commutative.) -/ section module_of_linear_maps variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S] (V : Type*) [add_comm_monoid V] [semimodule S V] (W : Type*) [add_comm_monoid W] [semimodule S W] /-- For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define `(r • f) v = f (r • v)`. -/ def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) := { smul := λ r f, { to_fun := λ v, f ((algebra_map R S r) • v), map_add' := λ x y, by simp [smul_add], map_smul' := λ s v, by simp [smul_smul, algebra.commutes], } } local attribute [instance] linear_map_algebra_has_scalar /-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/ def linear_map_algebra_module : semimodule R (V →ₗ[S] W) := { one_smul := λ f, begin ext v, dsimp [(•)], simp, end, mul_smul := λ r r' f, begin ext v, dsimp [(•)], rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul, smul_smul, algebra.commutes], end, smul_zero := λ r, by { ext v, dsimp [(•)], refl, }, smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], }, zero_smul := λ f, by { ext v, dsimp [(•)], simp, }, add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, } local attribute [instance] linear_map_algebra_module variables {R S V W} @[simp] lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) : (c • f) v = (c • (f v) : semimodule.restrict_scalars R S W) := begin erw [linear_map.map_smul], refl, end end module_of_linear_maps
1df46efa3d0c8af1bc72a73412790d958b16ddbf
cb7c0cb2d4a70d8ea5541196e18451ff4c9258c1
/mm0-lean/x86/bits.lean
7a2f5e5da3cb50643093b0dd2493017dc87c8475
[ "CC0-1.0" ]
permissive
stjordanis/mm0
b5e6fe7b93fb2f590e477c42b3e6601b340c874c
0d5fb4d9ab4fbf5922ec13c966caab31a37f603c
refs/heads/master
1,599,557,200,715
1,572,706,586,000
1,572,706,586,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,736
lean
-- import data.bitvec import data.vector @[reducible] def bitvec (n : ℕ) := vector bool n namespace bitvec open vector nat -- Create a zero bitvector @[reducible] protected def zero (n : ℕ) : bitvec n := repeat ff n -- Create a bitvector with the constant one. @[reducible] protected def one : Π (n : ℕ), bitvec n | 0 := nil | (succ n) := tt :: repeat ff n -- bitvec specific version of vector.append def append {m n} : bitvec m → bitvec n → bitvec (m + n) := vector.append def singleton (b : bool) : bitvec 1 := vector.cons b vector.nil protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b | ⟨x, p⟩ := ⟨x, h ▸ p⟩ section bitwise variable {n : ℕ} def not : bitvec n → bitvec n := map bnot def and : bitvec n → bitvec n → bitvec n := map₂ band def or : bitvec n → bitvec n → bitvec n := map₂ bor def xor : bitvec n → bitvec n → bitvec n := map₂ bxor def shl (x : bitvec n) (i : ℕ) : bitvec n := bitvec.cong (by simp) $ (repeat ff (min n i)).append (drop i x) def from_bits_fill (fill : bool) : list bool → ∀ {n}, bitvec n | [] n := repeat fill n | (a :: l) 0 := vector.nil | (a :: l) (n+1) := vector.cons a (from_bits_fill l) def fill_shr (x : bitvec n) (i : ℕ) (fill : bool) : bitvec n := from_bits_fill fill (list.repeat ff i ++ x.1) -- unsigned shift right def ushr (x : bitvec n) (i : ℕ) : bitvec n := fill_shr x i ff end bitwise protected def of_nat : Π (n : ℕ), nat → bitvec n | 0 x := nil | (succ n) x := let ⟨b, y⟩ := bodd_div2 x in b :: of_nat n y def bits_to_nat (v : list bool) : nat := v.foldr nat.bit 0 def to_nat {n} (v : bitvec n) : ℕ := bits_to_nat v.1 section arith variable {n : ℕ} protected def neg {n} (v : bitvec n) : bitvec n := bitvec.of_nat _ (2^n - to_nat v) protected def add (x y : bitvec n) : bitvec n := bitvec.of_nat _ (to_nat x + to_nat y) protected def sub (x y : bitvec n) : bitvec n := x.add y.neg instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩ instance : has_one (bitvec n) := ⟨bitvec.one n⟩ instance : has_add (bitvec n) := ⟨bitvec.add⟩ instance : has_sub (bitvec n) := ⟨bitvec.sub⟩ instance : has_neg (bitvec n) := ⟨bitvec.neg⟩ protected def mul (x y : bitvec n) : bitvec n := bitvec.of_nat _ (to_nat x * to_nat y) instance : has_mul (bitvec n) := ⟨bitvec.mul⟩ end arith end bitvec @[reducible] def byte := bitvec 8 def byte.to_nat : byte → ℕ := bitvec.to_nat @[reducible] def short := bitvec 16 @[reducible] def word := bitvec 32 @[reducible] def qword := bitvec 64 def of_bits : list bool → nat | [] := 0 | (b :: l) := nat.bit b (of_bits l) inductive split_bits : ℕ → list (Σ n, bitvec n) → Prop | nil : split_bits 0 [] | zero {b l} : split_bits b l → split_bits b (⟨0, vector.nil⟩ :: l) | succ {b n l bs} : split_bits (nat.div2 b) (⟨n, bs⟩ :: l) → split_bits b (⟨n + 1, vector.cons (nat.bodd b) bs⟩ :: l) def from_list_byte : list byte → ℕ | [] := 0 | (b :: l) := b.to_nat + 0x100 * from_list_byte l def bits_to_byte {n} (m) (w : bitvec n) (l : list byte) : Prop := l.length = m ∧ split_bits w.to_nat (l.map (λ b, ⟨8, b⟩)) def short.to_list_byte : short → list byte → Prop := bits_to_byte 2 def word.to_list_byte : word → list byte → Prop := bits_to_byte 4 def qword.to_list_byte : qword → list byte → Prop := bits_to_byte 8 def EXTS_aux : list bool → bool → ∀ {m}, bitvec m | [] b m := vector.repeat b _ | (a::l) _ 0 := vector.nil | (a::l) _ (m+1) := vector.cons a (EXTS_aux l a) def EXTS {m n} (v : bitvec n) : bitvec m := EXTS_aux v.1 ff def EXTZ_aux : list bool → ∀ {m}, bitvec m | [] m := vector.repeat ff _ | (a::l) 0 := vector.nil | (a::l) (m+1) := vector.cons a (EXTZ_aux l) def EXTZ {m n} (v : bitvec n) : bitvec m := EXTZ_aux v.1 def bitvec.update0_aux : list bool → ∀ {n}, bitvec n → bitvec n | [] n v := v | (a::l) 0 v := v | (a::l) (n+1) v := vector.cons a (bitvec.update0_aux l v.tail) def bitvec.update_aux : ℕ → list bool → ∀ {n}, bitvec n → bitvec n | 0 l n v := bitvec.update0_aux l v | (m+1) l 0 v := v | (m+1) l (n+1) v := vector.cons v.head (bitvec.update_aux m l v.tail) def bitvec.update {m n} (v1 : bitvec n) (index : ℕ) (v2 : bitvec m) : bitvec n := bitvec.update_aux index v2.1 v1 class byte_encoder (α : Type*) := (f : α → list byte → Prop) def encodes {α : Type*} [E : byte_encoder α] : α → list byte → Prop := E.f def encodes_with {α : Type*} [byte_encoder α] (a : α) (l1 l2 : list byte) : Prop := ∃ l, encodes a l ∧ l2 = l ++ l1 def encodes_start {α : Type*} [byte_encoder α] (a : α) (l : list byte) : Prop := ∃ l', encodes_with a l' l inductive encodes_list {α} [byte_encoder α] : list α → list byte → Prop | nil : encodes_list [] [] | cons {a as l ls} : encodes a l → encodes_list (a :: as) (l ++ ls) inductive encodes_list_start {α} [byte_encoder α] : list α → list byte → Prop | nil {l} : encodes_list_start [] l | cons {a as l ls} : encodes a l → encodes_list_start (a :: as) (l ++ ls) instance : byte_encoder unit := ⟨λ _ l, l = []⟩ instance : byte_encoder byte := ⟨λ b l, l = [b]⟩ instance : byte_encoder short := ⟨short.to_list_byte⟩ instance : byte_encoder word := ⟨word.to_list_byte⟩ instance : byte_encoder qword := ⟨qword.to_list_byte⟩ instance : byte_encoder (list byte) := ⟨eq⟩ instance {n} : byte_encoder (vector byte n) := ⟨λ x l, x.1 = l⟩ instance {α β} [byte_encoder α] [byte_encoder β] : byte_encoder (α × β) := ⟨λ ⟨a, b⟩ l, ∃ l1 l2, encodes a l1 ∧ encodes a l2 ∧ l = l1 ++ l2⟩ def string.to_cstr (s : string) : list byte := s.to_list.map (λ c, bitvec.of_nat _ c.1) ++ [0] structure pstate_result (σ α : Type*) := (safe : Prop) (P : α → σ → Prop) (good : safe → ∃ a s, P a s) def pstate (σ α : Type*) := σ → pstate_result σ α inductive pstate_pure_P {σ α : Type*} (a : α) (s : σ) : α → σ → Prop | mk : pstate_pure_P a s inductive pstate_map_P {σ α β} (f : α → β) (x : pstate_result σ α) : β → σ → Prop | mk (a s') : x.P a s' → pstate_map_P (f a) s' def pstate_bind_safe {σ α β} (x : pstate σ α) (f : α → pstate σ β) (s : σ) : Prop := (x s).safe ∧ ∀ a s', (x s).P a s' → (f a s').safe def pstate_bind_P {σ α β} (x : pstate σ α) (f : α → pstate σ β) (s : σ) (b : β) (s' : σ) : Prop := ∃ a s1, (x s).P a s1 ∧ (f a s1).P b s' instance {σ} : monad (pstate σ) := { pure := λ α a s, ⟨true, pstate_pure_P a s, λ _, ⟨_, _, ⟨a, s⟩⟩⟩, map := λ α β f x s, ⟨(x s).1, pstate_map_P f (x s), λ h, let ⟨a, s', h⟩ := (x s).good h in ⟨_, _, ⟨_, _, _, h⟩⟩⟩, bind := λ α β x f s, ⟨pstate_bind_safe x f s, pstate_bind_P x f s, λ ⟨h₁, h₂⟩, let ⟨a, s1, hx⟩ := (x s).good h₁, ⟨b, s2, hf⟩ := (f a s1).good (h₂ a s1 hx) in ⟨b, s2, ⟨_, _, hx, hf⟩⟩⟩ } def pstate.lift {σ α} (f : σ → α → σ → Prop) : pstate σ α := λ s, ⟨_, f s, id⟩ inductive pstate.get' {σ} (s : σ) : σ → σ → Prop | mk : pstate.get' s s def pstate.get {σ} : pstate σ σ := pstate.lift pstate.get' def pstate.put {σ} (s : σ) : pstate σ unit := pstate.lift $ λ _ _, eq s def pstate.assert {σ α} (p : σ → α → Prop) : pstate σ α := pstate.lift $ λ s a s', p s a ∧ s = s' def pstate.modify {σ} (f : σ → σ) : pstate σ unit := pstate.lift $ λ s _ s', s' = f s def pstate.any {σ α} : pstate σ α := pstate.assert $ λ _ _, true def pstate.fail {σ α} : pstate σ α := pstate.assert $ λ _ _, false
6a4a60c970b035d0ec132350d5da02a12d41380b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/convex/gauge.lean
2b1855b092fd190d45cf6806fde8883a84ad0a00
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
18,614
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.convex.basic import analysis.normed_space.pointwise import analysis.seminorm import data.complex.is_R_or_C import tactic.congrm /-! # The Minkowksi functional This file defines the Minkowski functional, aka gauge. The Minkowski functional of a set `s` is the function which associates each point to how much you need to scale `s` for `x` to be inside it. When `s` is symmetric, convex and absorbent, its gauge is a seminorm. Reciprocally, any seminorm arises as the gauge of some set, namely its unit ball. This induces the equivalence of seminorms and locally convex topological vector spaces. ## Main declarations For a real vector space, * `gauge`: Aka Minkowksi functional. `gauge s x` is the least (actually, an infimum) `r` such that `x ∈ r • s`. * `gauge_seminorm`: The Minkowski functional as a seminorm, when `s` is symmetric, convex and absorbent. ## References * [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966] ## Tags Minkowski functional, gauge -/ open normed_field set open_locale pointwise noncomputable theory variables {𝕜 E F : Type*} section add_comm_group variables [add_comm_group E] [module ℝ E] /--The Minkowski functional. Given a set `s` in a real vector space, `gauge s` is the functional which sends `x : E` to the smallest `r : ℝ` such that `x` is in `s` scaled by `r`. -/ def gauge (s : set E) (x : E) : ℝ := Inf {r : ℝ | 0 < r ∧ x ∈ r • s} variables {s t : set E} {a : ℝ} {x : E} lemma gauge_def : gauge s x = Inf {r ∈ set.Ioi 0 | x ∈ r • s} := rfl /-- An alternative definition of the gauge using scalar multiplication on the element rather than on the set. -/ lemma gauge_def' : gauge s x = Inf {r ∈ set.Ioi 0 | r⁻¹ • x ∈ s} := begin congrm Inf (λ r, _), exact and_congr_right (λ hr, mem_smul_set_iff_inv_smul_mem₀ hr.ne' _ _), end private lemma gauge_set_bdd_below : bdd_below {r : ℝ | 0 < r ∧ x ∈ r • s} := ⟨0, λ r hr, hr.1.le⟩ /-- If the given subset is `absorbent` then the set we take an infimum over in `gauge` is nonempty, which is useful for proving many properties about the gauge. -/ lemma absorbent.gauge_set_nonempty (absorbs : absorbent ℝ s) : {r : ℝ | 0 < r ∧ x ∈ r • s}.nonempty := let ⟨r, hr₁, hr₂⟩ := absorbs x in ⟨r, hr₁, hr₂ r (real.norm_of_nonneg hr₁.le).ge⟩ lemma gauge_mono (hs : absorbent ℝ s) (h : s ⊆ t) : gauge t ≤ gauge s := λ x, cInf_le_cInf gauge_set_bdd_below hs.gauge_set_nonempty $ λ r hr, ⟨hr.1, smul_set_mono h hr.2⟩ lemma exists_lt_of_gauge_lt (absorbs : absorbent ℝ s) (h : gauge s x < a) : ∃ b, 0 < b ∧ b < a ∧ x ∈ b • s := begin obtain ⟨b, ⟨hb, hx⟩, hba⟩ := exists_lt_of_cInf_lt absorbs.gauge_set_nonempty h, exact ⟨b, hb, hba, hx⟩, end /-- The gauge evaluated at `0` is always zero (mathematically this requires `0` to be in the set `s` but, the real infimum of the empty set in Lean being defined as `0`, it holds unconditionally). -/ @[simp] lemma gauge_zero : gauge s 0 = 0 := begin rw gauge_def', by_cases (0 : E) ∈ s, { simp only [smul_zero, sep_true, h, cInf_Ioi] }, { simp only [smul_zero, sep_false, h, real.Inf_empty] } end @[simp] lemma gauge_zero' : gauge (0 : set E) = 0 := begin ext, rw gauge_def', obtain rfl | hx := eq_or_ne x 0, { simp only [cInf_Ioi, mem_zero, pi.zero_apply, eq_self_iff_true, sep_true, smul_zero] }, { simp only [mem_zero, pi.zero_apply, inv_eq_zero, smul_eq_zero], convert real.Inf_empty, exact eq_empty_iff_forall_not_mem.2 (λ r hr, hr.2.elim (ne_of_gt hr.1) hx) } end @[simp] lemma gauge_empty : gauge (∅ : set E) = 0 := by { ext, simp only [gauge_def', real.Inf_empty, mem_empty_eq, pi.zero_apply, sep_false] } lemma gauge_of_subset_zero (h : s ⊆ 0) : gauge s = 0 := by { obtain rfl | rfl := subset_singleton_iff_eq.1 h, exacts [gauge_empty, gauge_zero'] } /-- The gauge is always nonnegative. -/ lemma gauge_nonneg (x : E) : 0 ≤ gauge s x := real.Inf_nonneg _ $ λ x hx, hx.1.le lemma gauge_neg (symmetric : ∀ x ∈ s, -x ∈ s) (x : E) : gauge s (-x) = gauge s x := begin have : ∀ x, -x ∈ s ↔ x ∈ s := λ x, ⟨λ h, by simpa using symmetric _ h, symmetric x⟩, rw [gauge_def', gauge_def'], simp_rw [smul_neg, this], end lemma gauge_le_of_mem (ha : 0 ≤ a) (hx : x ∈ a • s) : gauge s x ≤ a := begin obtain rfl | ha' := ha.eq_or_lt, { rw [mem_singleton_iff.1 (zero_smul_set_subset _ hx), gauge_zero] }, { exact cInf_le gauge_set_bdd_below ⟨ha', hx⟩ } end lemma gauge_le_eq (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : absorbent ℝ s) (ha : 0 ≤ a) : {x | gauge s x ≤ a} = ⋂ (r : ℝ) (H : a < r), r • s := begin ext, simp_rw [set.mem_Inter, set.mem_set_of_eq], refine ⟨λ h r hr, _, λ h, le_of_forall_pos_lt_add (λ ε hε, _)⟩, { have hr' := ha.trans_lt hr, rw mem_smul_set_iff_inv_smul_mem₀ hr'.ne', obtain ⟨δ, δ_pos, hδr, hδ⟩ := exists_lt_of_gauge_lt hs₂ (h.trans_lt hr), suffices : (r⁻¹ * δ) • δ⁻¹ • x ∈ s, { rwa [smul_smul, mul_inv_cancel_right₀ δ_pos.ne'] at this }, rw mem_smul_set_iff_inv_smul_mem₀ δ_pos.ne' at hδ, refine hs₁.smul_mem_of_zero_mem hs₀ hδ ⟨mul_nonneg (inv_nonneg.2 hr'.le) δ_pos.le, _⟩, rw [inv_mul_le_iff hr', mul_one], exact hδr.le }, { have hε' := (lt_add_iff_pos_right a).2 (half_pos hε), exact (gauge_le_of_mem (ha.trans hε'.le) $ h _ hε').trans_lt (add_lt_add_left (half_lt_self hε) _) } end lemma gauge_lt_eq' (absorbs : absorbent ℝ s) (a : ℝ) : {x | gauge s x < a} = ⋃ (r : ℝ) (H : 0 < r) (H : r < a), r • s := begin ext, simp_rw [mem_set_of_eq, mem_Union, exists_prop], exact ⟨exists_lt_of_gauge_lt absorbs, λ ⟨r, hr₀, hr₁, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁⟩, end lemma gauge_lt_eq (absorbs : absorbent ℝ s) (a : ℝ) : {x | gauge s x < a} = ⋃ (r ∈ set.Ioo 0 (a : ℝ)), r • s := begin ext, simp_rw [mem_set_of_eq, mem_Union, exists_prop, mem_Ioo, and_assoc], exact ⟨exists_lt_of_gauge_lt absorbs, λ ⟨r, hr₀, hr₁, hx⟩, (gauge_le_of_mem hr₀.le hx).trans_lt hr₁⟩, end lemma gauge_lt_one_subset_self (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) : {x | gauge s x < 1} ⊆ s := begin rw gauge_lt_eq absorbs, refine set.Union₂_subset (λ r hr _, _), rintro ⟨y, hy, rfl⟩, exact hs.smul_mem_of_zero_mem h₀ hy (Ioo_subset_Icc_self hr), end lemma gauge_le_one_of_mem {x : E} (hx : x ∈ s) : gauge s x ≤ 1 := gauge_le_of_mem zero_le_one $ by rwa one_smul lemma self_subset_gauge_le_one : s ⊆ {x | gauge s x ≤ 1} := λ x, gauge_le_one_of_mem lemma convex.gauge_le (hs : convex ℝ s) (h₀ : (0 : E) ∈ s) (absorbs : absorbent ℝ s) (a : ℝ) : convex ℝ {x | gauge s x ≤ a} := begin by_cases ha : 0 ≤ a, { rw gauge_le_eq hs h₀ absorbs ha, exact convex_Inter (λ i, convex_Inter (λ hi, hs.smul _)) }, { convert convex_empty, exact eq_empty_iff_forall_not_mem.2 (λ x hx, ha $ (gauge_nonneg _).trans hx) } end lemma balanced.star_convex (hs : balanced ℝ s) : star_convex ℝ 0 s := star_convex_zero_iff.2 $ λ x hx a ha₀ ha₁, hs _ (by rwa real.norm_of_nonneg ha₀) (smul_mem_smul_set hx) lemma le_gauge_of_not_mem (hs₀ : star_convex ℝ 0 s) (hs₂ : absorbs ℝ s {x}) (hx : x ∉ a • s) : a ≤ gauge s x := begin rw star_convex_zero_iff at hs₀, obtain ⟨r, hr, h⟩ := hs₂, refine le_cInf ⟨r, hr, singleton_subset_iff.1 $ h _ (real.norm_of_nonneg hr.le).ge⟩ _, rintro b ⟨hb, x, hx', rfl⟩, refine not_lt.1 (λ hba, hx _), have ha := hb.trans hba, refine ⟨(a⁻¹ * b) • x, hs₀ hx' (mul_nonneg (inv_nonneg.2 ha.le) hb.le) _, _⟩, { rw ←div_eq_inv_mul, exact div_le_one_of_le hba.le ha.le }, { rw [←mul_smul, mul_inv_cancel_left₀ ha.ne'] } end lemma one_le_gauge_of_not_mem (hs₁ : star_convex ℝ 0 s) (hs₂ : absorbs ℝ s {x}) (hx : x ∉ s) : 1 ≤ gauge s x := le_gauge_of_not_mem hs₁ hs₂ $ by rwa one_smul section linear_ordered_field variables {α : Type*} [linear_ordered_field α] [mul_action_with_zero α ℝ] [ordered_smul α ℝ] lemma gauge_smul_of_nonneg [mul_action_with_zero α E] [is_scalar_tower α ℝ (set E)] {s : set E} {a : α} (ha : 0 ≤ a) (x : E) : gauge s (a • x) = a • gauge s x := begin obtain rfl | ha' := ha.eq_or_lt, { rw [zero_smul, gauge_zero, zero_smul] }, rw [gauge_def', gauge_def', ←real.Inf_smul_of_nonneg ha], congr' 1, ext r, simp_rw [set.mem_smul_set, set.mem_sep_eq], split, { rintro ⟨hr, hx⟩, simp_rw mem_Ioi at ⊢ hr, rw ←mem_smul_set_iff_inv_smul_mem₀ hr.ne' at hx, have := smul_pos (inv_pos.2 ha') hr, refine ⟨a⁻¹ • r, ⟨this, _⟩, smul_inv_smul₀ ha'.ne' _⟩, rwa [←mem_smul_set_iff_inv_smul_mem₀ this.ne', smul_assoc, mem_smul_set_iff_inv_smul_mem₀ (inv_ne_zero ha'.ne'), inv_inv] }, { rintro ⟨r, ⟨hr, hx⟩, rfl⟩, rw mem_Ioi at ⊢ hr, rw ←mem_smul_set_iff_inv_smul_mem₀ hr.ne' at hx, have := smul_pos ha' hr, refine ⟨this, _⟩, rw [←mem_smul_set_iff_inv_smul_mem₀ this.ne', smul_assoc], exact smul_mem_smul_set hx } end lemma gauge_smul_left_of_nonneg [mul_action_with_zero α E] [smul_comm_class α ℝ ℝ] [is_scalar_tower α ℝ ℝ] [is_scalar_tower α ℝ E] {s : set E} {a : α} (ha : 0 ≤ a) : gauge (a • s) = a⁻¹ • gauge s := begin obtain rfl | ha' := ha.eq_or_lt, { rw [inv_zero, zero_smul, gauge_of_subset_zero (zero_smul_set_subset _)] }, ext, rw [gauge_def', pi.smul_apply, gauge_def', ←real.Inf_smul_of_nonneg (inv_nonneg.2 ha)], congr' 1, ext r, simp_rw [set.mem_smul_set, set.mem_sep_eq], split, { rintro ⟨hr, y, hy, h⟩, simp_rw [mem_Ioi] at ⊢ hr, refine ⟨a • r, ⟨smul_pos ha' hr, _⟩, inv_smul_smul₀ ha'.ne' _⟩, rwa [smul_inv₀, smul_assoc, ←h, inv_smul_smul₀ ha'.ne'] }, { rintro ⟨r, ⟨hr, hx⟩, rfl⟩, rw mem_Ioi at ⊢ hr, have := smul_pos ha' hr, refine ⟨smul_pos (inv_pos.2 ha') hr, r⁻¹ • x, hx, _⟩, rw [smul_inv₀, smul_assoc, inv_inv] } end lemma gauge_smul_left [module α E] [smul_comm_class α ℝ ℝ] [is_scalar_tower α ℝ ℝ] [is_scalar_tower α ℝ E] {s : set E} (symmetric : ∀ x ∈ s, -x ∈ s) (a : α) : gauge (a • s) = |a|⁻¹ • gauge s := begin rw ←gauge_smul_left_of_nonneg (abs_nonneg a), obtain h | h := abs_choice a, { rw h }, { rw [h, set.neg_smul_set, ←set.smul_set_neg], congr, ext y, refine ⟨symmetric _, λ hy, _⟩, rw ←neg_neg y, exact symmetric _ hy }, { apply_instance } end end linear_ordered_field section is_R_or_C variables [is_R_or_C 𝕜] [module 𝕜 E] [is_scalar_tower ℝ 𝕜 E] lemma gauge_norm_smul (hs : balanced 𝕜 s) (r : 𝕜) (x : E) : gauge s (∥r∥ • x) = gauge s (r • x) := begin rw @is_R_or_C.real_smul_eq_coe_smul 𝕜, obtain rfl | hr := eq_or_ne r 0, { simp only [norm_zero, is_R_or_C.of_real_zero] }, unfold gauge, congr' with θ, refine and_congr_right (λ hθ, (hs.smul _).mem_smul_iff _), rw [is_R_or_C.norm_of_real, norm_norm], end /-- If `s` is balanced, then the Minkowski functional is ℂ-homogeneous. -/ lemma gauge_smul (hs : balanced 𝕜 s) (r : 𝕜) (x : E) : gauge s (r • x) = ∥r∥ * gauge s x := by { rw [←smul_eq_mul, ←gauge_smul_of_nonneg (norm_nonneg r), gauge_norm_smul hs], apply_instance } end is_R_or_C section topological_space variables [topological_space E] [has_continuous_smul ℝ E] lemma interior_subset_gauge_lt_one (s : set E) : interior s ⊆ {x | gauge s x < 1} := begin intros x hx, let f : ℝ → E := λ t, t • x, have hf : continuous f, { continuity }, let s' := f ⁻¹' (interior s), have hs' : is_open s' := hf.is_open_preimage _ is_open_interior, have one_mem : (1 : ℝ) ∈ s', { simpa only [s', f, set.mem_preimage, one_smul] }, obtain ⟨ε, hε₀, hε⟩ := (metric.nhds_basis_closed_ball.1 _).1 (is_open_iff_mem_nhds.1 hs' 1 one_mem), rw real.closed_ball_eq_Icc at hε, have hε₁ : 0 < 1 + ε := hε₀.trans (lt_one_add ε), have : (1 + ε)⁻¹ < 1, { rw inv_lt_one_iff, right, linarith }, refine (gauge_le_of_mem (inv_nonneg.2 hε₁.le) _).trans_lt this, rw mem_inv_smul_set_iff₀ hε₁.ne', exact interior_subset (hε ⟨(sub_le_self _ hε₀.le).trans ((le_add_iff_nonneg_right _).2 hε₀.le), le_rfl⟩), end lemma gauge_lt_one_eq_self_of_open (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : is_open s) : {x | gauge s x < 1} = s := begin refine (gauge_lt_one_subset_self hs₁ ‹_› $ absorbent_nhds_zero $ hs₂.mem_nhds hs₀).antisymm _, convert interior_subset_gauge_lt_one s, exact hs₂.interior_eq.symm, end lemma gauge_lt_one_of_mem_of_open (hs₁ : convex ℝ s) (hs₀ : (0 : E) ∈ s) (hs₂ : is_open s) {x : E} (hx : x ∈ s) : gauge s x < 1 := by rwa ←gauge_lt_one_eq_self_of_open hs₁ hs₀ hs₂ at hx lemma gauge_lt_of_mem_smul (x : E) (ε : ℝ) (hε : 0 < ε) (hs₀ : (0 : E) ∈ s) (hs₁ : convex ℝ s) (hs₂ : is_open s) (hx : x ∈ ε • s) : gauge s x < ε := begin have : ε⁻¹ • x ∈ s, { rwa ←mem_smul_set_iff_inv_smul_mem₀ hε.ne' }, have h_gauge_lt := gauge_lt_one_of_mem_of_open hs₁ hs₀ hs₂ this, rwa [gauge_smul_of_nonneg (inv_nonneg.2 hε.le), smul_eq_mul, inv_mul_lt_iff hε, mul_one] at h_gauge_lt, apply_instance end end topological_space lemma gauge_add_le (hs : convex ℝ s) (absorbs : absorbent ℝ s) (x y : E) : gauge s (x + y) ≤ gauge s x + gauge s y := begin refine le_of_forall_pos_lt_add (λ ε hε, _), obtain ⟨a, ha, ha', hx⟩ := exists_lt_of_gauge_lt absorbs (lt_add_of_pos_right (gauge s x) (half_pos hε)), obtain ⟨b, hb, hb', hy⟩ := exists_lt_of_gauge_lt absorbs (lt_add_of_pos_right (gauge s y) (half_pos hε)), rw mem_smul_set_iff_inv_smul_mem₀ ha.ne' at hx, rw mem_smul_set_iff_inv_smul_mem₀ hb.ne' at hy, suffices : gauge s (x + y) ≤ a + b, { linarith }, have hab : 0 < a + b := add_pos ha hb, apply gauge_le_of_mem hab.le, have := convex_iff_div.1 hs hx hy ha.le hb.le hab, rwa [smul_smul, smul_smul, ←mul_div_right_comm, ←mul_div_right_comm, mul_inv_cancel ha.ne', mul_inv_cancel hb.ne', ←smul_add, one_div, ←mem_smul_set_iff_inv_smul_mem₀ hab.ne'] at this, end section is_R_or_C variables [is_R_or_C 𝕜] [module 𝕜 E] [is_scalar_tower ℝ 𝕜 E] /-- `gauge s` as a seminorm when `s` is balanced, convex and absorbent. -/ @[simps] def gauge_seminorm (hs₀ : balanced 𝕜 s) (hs₁ : convex ℝ s) (hs₂ : absorbent ℝ s) : seminorm 𝕜 E := seminorm.of (gauge s) (gauge_add_le hs₁ hs₂) (gauge_smul hs₀) variables {hs₀ : balanced 𝕜 s} {hs₁ : convex ℝ s} {hs₂ : absorbent ℝ s} [topological_space E] [has_continuous_smul ℝ E] lemma gauge_seminorm_lt_one_of_open (hs : is_open s) {x : E} (hx : x ∈ s) : gauge_seminorm hs₀ hs₁ hs₂ x < 1 := gauge_lt_one_of_mem_of_open hs₁ hs₂.zero_mem hs hx lemma gauge_seminorm_ball_one (hs : is_open s) : (gauge_seminorm hs₀ hs₁ hs₂).ball 0 1 = s := begin rw seminorm.ball_zero_eq, exact gauge_lt_one_eq_self_of_open hs₁ hs₂.zero_mem hs end end is_R_or_C /-- Any seminorm arises as the gauge of its unit ball. -/ @[simp] protected lemma seminorm.gauge_ball (p : seminorm ℝ E) : gauge (p.ball 0 1) = p := begin ext, obtain hp | hp := {r : ℝ | 0 < r ∧ x ∈ r • p.ball 0 1}.eq_empty_or_nonempty, { rw [gauge, hp, real.Inf_empty], by_contra, have hpx : 0 < p x := (map_nonneg _ _).lt_of_ne h, have hpx₂ : 0 < 2 * p x := mul_pos zero_lt_two hpx, refine hp.subset ⟨hpx₂, (2 * p x)⁻¹ • x, _, smul_inv_smul₀ hpx₂.ne' _⟩, rw [p.mem_ball_zero, map_smul_eq_mul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpx₂), inv_mul_lt_iff hpx₂, mul_one], exact lt_mul_of_one_lt_left hpx one_lt_two }, refine is_glb.cInf_eq ⟨λ r, _, λ r hr, le_of_forall_pos_le_add $ λ ε hε, _⟩ hp, { rintro ⟨hr, y, hy, rfl⟩, rw p.mem_ball_zero at hy, rw [map_smul_eq_mul, real.norm_eq_abs, abs_of_pos hr], exact mul_le_of_le_one_right hr.le hy.le }, { have hpε : 0 < p x + ε := add_pos_of_nonneg_of_pos (map_nonneg _ _) hε, refine hr ⟨hpε, (p x + ε)⁻¹ • x, _, smul_inv_smul₀ hpε.ne' _⟩, rw [p.mem_ball_zero, map_smul_eq_mul, real.norm_eq_abs, abs_of_pos (inv_pos.2 hpε), inv_mul_lt_iff hpε, mul_one], exact lt_add_of_pos_right _ hε } end lemma seminorm.gauge_seminorm_ball (p : seminorm ℝ E) : gauge_seminorm (p.balanced_ball_zero 1) (p.convex_ball 0 1) (p.absorbent_ball_zero zero_lt_one) = p := fun_like.coe_injective p.gauge_ball end add_comm_group section norm variables [seminormed_add_comm_group E] [normed_space ℝ E] {s : set E} {r : ℝ} {x : E} lemma gauge_unit_ball (x : E) : gauge (metric.ball (0 : E) 1) x = ∥x∥ := begin obtain rfl | hx := eq_or_ne x 0, { rw [norm_zero, gauge_zero] }, refine (le_of_forall_pos_le_add $ λ ε hε, _).antisymm _, { have := add_pos_of_nonneg_of_pos (norm_nonneg x) hε, refine gauge_le_of_mem this.le _, rw [smul_ball this.ne', smul_zero, real.norm_of_nonneg this.le, mul_one, mem_ball_zero_iff], exact lt_add_of_pos_right _ hε }, refine le_gauge_of_not_mem balanced_ball_zero.star_convex (absorbent_ball_zero zero_lt_one).absorbs (λ h, _), obtain hx' | hx' := eq_or_ne (∥x∥) 0, { rw hx' at h, exact hx (zero_smul_set_subset _ h) }, { rw [mem_smul_set_iff_inv_smul_mem₀ hx', mem_ball_zero_iff, norm_smul, norm_inv, norm_norm, inv_mul_cancel hx'] at h, exact lt_irrefl _ h } end lemma gauge_ball (hr : 0 < r) (x : E) : gauge (metric.ball (0 : E) r) x = ∥x∥ / r := begin rw [←smul_unit_ball_of_pos hr, gauge_smul_left, pi.smul_apply, gauge_unit_ball, smul_eq_mul, abs_of_nonneg hr.le, div_eq_inv_mul], simp_rw [mem_ball_zero_iff, norm_neg], exact λ _, id, end lemma mul_gauge_le_norm (hs : metric.ball (0 : E) r ⊆ s) : r * gauge s x ≤ ∥x∥ := begin obtain hr | hr := le_or_lt r 0, { exact (mul_nonpos_of_nonpos_of_nonneg hr $ gauge_nonneg _).trans (norm_nonneg _) }, rw [mul_comm, ←le_div_iff hr, ←gauge_ball hr], exact gauge_mono (absorbent_ball_zero hr) hs x, end end norm
b51c0e367c5b3bed5ac566a61d29bb1f7641c8c4
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/src/Lean/Elab/Tactic/Basic.lean
6398c777a169de2787c73020b265701675b471b6
[ "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
16,821
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.CollectMVars import Lean.Meta.Tactic.Assumption import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Clear import Lean.Meta.Tactic.Revert import Lean.Meta.Tactic.Subst import Lean.Elab.Util import Lean.Elab.Term import Lean.Elab.Binders namespace Lean.Elab open Meta def goalsToMessageData (goals : List MVarId) : MessageData := MessageData.joinSep (goals.map $ MessageData.ofGoal) m!"\n\n" def Term.reportUnsolvedGoals (goals : List MVarId) : TermElabM Unit := do throwError! "unsolved goals\n{goalsToMessageData goals}" namespace Tactic structure Context where main : MVarId structure State where goals : List MVarId deriving Inhabited structure BacktrackableState where env : Environment mctx : MetavarContext term : Term.State goals : List MVarId abbrev TacticM := ReaderT Context $ StateRefT State TermElabM abbrev Tactic := Syntax → TacticM Unit def saveBacktrackableState : TacticM BacktrackableState := do pure { env := (← getEnv), mctx := (← getMCtx), term := (← getThe Term.State), goals := (← get).goals } def BacktrackableState.restore (b : BacktrackableState) : TacticM Unit := do setEnv b.env setMCtx b.mctx let msgLog ← Term.getMessageLog -- we do not backtrack the message log set b.term Term.setMessageLog msgLog modify fun s => { s with goals := b.goals } @[inline] protected def tryCatch {α} (x : TacticM α) (h : Exception → TacticM α) : TacticM α := do let b ← saveBacktrackableState try x catch ex => b.restore; h ex instance : MonadExcept Exception TacticM where throw := throw tryCatch := Tactic.tryCatch @[inline] protected def orElse {α} (x y : TacticM α) : TacticM α := do try x catch _ => y instance {α} : OrElse (TacticM α) where orElse := Tactic.orElse structure SavedState where core : Core.State meta : Meta.State term : Term.State tactic : State deriving Inhabited def saveAllState : TacticM SavedState := do pure { core := (← getThe Core.State), meta := (← getThe Meta.State), term := (← getThe Term.State), tactic := (← get) } def SavedState.restore (s : SavedState) : TacticM Unit := do set s.core; set s.meta; set s.term; set s.tactic @[inline] def liftTermElabM {α} (x : TermElabM α) : TacticM α := liftM x @[inline] def liftMetaM {α} (x : MetaM α) : TacticM α := liftTermElabM $ Term.liftMetaM x def ensureHasType (expectedType? : Option Expr) (e : Expr) : TacticM Expr := liftTermElabM $ Term.ensureHasType expectedType? e def reportUnsolvedGoals (goals : List MVarId) : TacticM Unit := liftTermElabM $ Term.reportUnsolvedGoals goals protected def getCurrMacroScope : TacticM MacroScope := do pure (← readThe Term.Context).currMacroScope protected def getMainModule : TacticM Name := do pure (← getEnv).mainModule unsafe def mkTacticAttribute : IO (KeyedDeclsAttribute Tactic) := mkElabAttribute Tactic `Lean.Elab.Tactic.tacticElabAttribute `builtinTactic `tactic `Lean.Parser.Tactic `Lean.Elab.Tactic.Tactic "tactic" @[builtinInit mkTacticAttribute] constant tacticElabAttribute : KeyedDeclsAttribute Tactic private def evalTacticUsing (s : SavedState) (stx : Syntax) (tactics : List Tactic) : TacticM Unit := do let rec loop : List Tactic → TacticM Unit | [] => throwErrorAt! stx "unexpected syntax {indentD stx}" | evalFn::evalFns => do try evalFn stx catch | ex@(Exception.error _ _) => match evalFns with | [] => throw ex | evalFns => s.restore; loop evalFns | ex@(Exception.internal id _) => if id == unsupportedSyntaxExceptionId then s.restore; loop evalFns else throw ex loop tactics /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TacticM α) : TacticM α := withTheReader Term.Context (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x mutual partial def expandTacticMacroFns (stx : Syntax) (macros : List Macro) : TacticM Unit := let rec loop : List Macro → TacticM Unit | [] => throwErrorAt! stx "tactic '{stx.getKind}' has not been implemented" | m::ms => do let scp ← getCurrMacroScope try let stx' ← adaptMacro m stx evalTactic stx' catch ex => if ms.isEmpty then throw ex loop ms loop macros partial def expandTacticMacro (stx : Syntax) : TacticM Unit := do let k := stx.getKind let table := (macroAttribute.ext.getState (← getEnv)).table let macroFns := (table.find? k).getD [] expandTacticMacroFns stx macroFns partial def evalTactic : Syntax → TacticM Unit | stx => withRef stx $ withIncRecDepth $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- Macro writers create a sequence of tactics `t₁ ... tₙ` using `mkNullNode #[t₁, ..., tₙ]` stx.getArgs.forM evalTactic else do trace `Elab.step fun _ => stx let env ← getEnv let s ← saveAllState let table := (tacticElabAttribute.ext.getState env).table let k := stx.getKind match table.find? k with | some evalFns => evalTacticUsing s stx evalFns | none => expandTacticMacro stx | _ => throwError "unexpected command" end /-- Adapt a syntax transformation to a regular tactic evaluator. -/ def adaptExpander (exp : Syntax → TacticM Syntax) : Tactic := fun stx => do let stx' ← exp stx withMacroExpansion stx stx' $ evalTactic stx' def getGoals : TacticM (List MVarId) := do pure (← get).goals def setGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := gs } def appendGoals (gs : List MVarId) : TacticM Unit := modify $ fun s => { s with goals := s.goals ++ gs } def pruneSolvedGoals : TacticM Unit := do let gs ← getGoals let gs ← gs.filterM fun g => not <$> isExprMVarAssigned g setGoals gs def getUnsolvedGoals : TacticM (List MVarId) := do pruneSolvedGoals; getGoals def getMainGoal : TacticM (MVarId × List MVarId) := do let (g::gs) ← getUnsolvedGoals | throwError "no goals to be solved"; pure (g, gs) def getMainTag : TacticM Name := do let (g, _) ← getMainGoal pure (← getMVarDecl g).userName def ensureHasNoMVars (e : Expr) : TacticM Unit := do let e ← instantiateMVars e let pendingMVars ← getMVars e discard <| Term.logUnassignedUsingErrorInfos pendingMVars if e.hasExprMVar then throwError! "tactic failed, resulting expression contains metavariables{indentExpr e}" def withMainMVarContext {α} (x : TacticM α) : TacticM α := do let (mvarId, _) ← getMainGoal withMVarContext mvarId x @[inline] def liftMetaMAtMain {α} (x : MVarId → MetaM α) : TacticM α := do let (g, _) ← getMainGoal withMVarContext g $ liftMetaM $ x g @[inline] def liftMetaTacticAux {α} (tactic : MVarId → MetaM (α × List MVarId)) : TacticM α := do let (g, gs) ← getMainGoal withMVarContext g do let (a, gs') ← tactic g setGoals (gs' ++ gs) pure a @[inline] def liftMetaTactic (tactic : MVarId → MetaM (List MVarId)) : TacticM Unit := liftMetaTacticAux fun mvarId => do let gs ← tactic mvarId pure ((), gs) def done : TacticM Unit := do let gs ← getUnsolvedGoals; unless gs.isEmpty do reportUnsolvedGoals gs @[builtinTactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ => done def focus {α} (tactic : TacticM α) : TacticM α := do let (g, gs) ← getMainGoal setGoals [g] let a ← tactic let gs' ← getGoals setGoals (gs' ++ gs) pure a def focusAndDone {α} (tactic : TacticM α) : TacticM α := focus do let a ← tactic; done; pure a /- Close the main goal using the given tactic. If it fails, log the error and `admit` -/ def closeUsingOrAdmit (tac : Syntax) : TacticM Unit := do let (mvarId, rest) ← getMainGoal try evalTactic tac done catch ex => logException ex let mvarType ← inferType (mkMVar mvarId) assignExprMVar mvarId (← mkSorry mvarType (synthetic := true)) setGoals rest def try? {α} (tactic : TacticM α) : TacticM (Option α) := do try pure (some (← tactic)) catch _ => pure none -- TODO: rename? def «try» {α} (tactic : TacticM α) : TacticM Bool := do try discard tactic pure true catch _ => pure false /-- Use `parentTag` to tag untagged goals at `newGoals`. If there are multiple new untagged goals, they are named using `<parentTag>.<newSuffix>_<idx>` where `idx > 0`. If there is only one new untagged goal, then we just use `parentTag` -/ def tagUntaggedGoals (parentTag : Name) (newSuffix : Name) (newGoals : List MVarId) : TacticM Unit := do let mctx ← getMCtx let mut numAnonymous := 0 for g in newGoals do if mctx.isAnonymousMVar g then numAnonymous := numAnonymous + 1 modifyMCtx fun mctx => do let mut mctx := mctx let mut idx := 1 for g in newGoals do if mctx.isAnonymousMVar g then if numAnonymous == 1 then mctx := mctx.renameMVar g parentTag else mctx := mctx.renameMVar g (parentTag ++ newSuffix.appendIndexAfter idx) idx := idx + 1 pure mctx @[builtinTactic seq1] def evalSeq1 : Tactic := fun stx => stx[0].getSepArgs.forM evalTactic @[builtinTactic paren] def evalParen : Tactic := fun stx => evalTactic stx[1] @[builtinTactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx => stx[0].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => withRef stx[2] $ focusAndDone $ stx[1].forArgsM fun seqElem => evalTactic seqElem[0] @[builtinTactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => focus $ evalTactic stx[1] @[builtinTactic Parser.Tactic.allGoals] def evalAllGoals : Tactic := fun stx => do let gs ← getUnsolvedGoals let mut gsNew := [] for g in gs do setGoals [g] evalTactic stx[1] gsNew := gsNew ++ (← getUnsolvedGoals) setGoals gsNew @[builtinTactic tacticSeq] def evalTacticSeq : Tactic := fun stx => evalTactic stx[0] partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit := if h : i < tactics.size then let tactic := tactics.get ⟨i, h⟩ catchInternalId unsupportedSyntaxExceptionId (evalTactic tactic) (fun _ => evalChoiceAux tactics (i+1)) else throwUnsupportedSyntax @[builtinTactic choice] def evalChoice : Tactic := fun stx => evalChoiceAux stx.getArgs 0 @[builtinTactic skip] def evalSkip : Tactic := fun stx => pure () @[builtinTactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx => do let tactic := stx[1] if (← try evalTactic tactic; pure true catch _ => pure false) then throwError "tactic succeeded" @[builtinTactic traceState] def evalTraceState : Tactic := fun stx => do let gs ← getUnsolvedGoals logInfo (goalsToMessageData gs) @[builtinTactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun stx => liftMetaTactic fun mvarId => do Meta.assumption mvarId; pure [] @[builtinTactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => do match stx with | `(tactic| intro) => introStep `_ | `(tactic| intro $h:ident) => introStep h.getId | `(tactic| intro _) => introStep `_ | `(tactic| intro $pat:term) => evalTactic (← `(tactic| intro h; match h with | $pat:term => _; clear h)) | `(tactic| intro $h:term $hs:term*) => evalTactic (← `(tactic| intro $h:term; intro $hs:term*)) | _ => throwUnsupportedSyntax where introStep (n : Name) : TacticM Unit := liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.intro mvarId n pure [mvarId] @[builtinTactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do let matchAlts := stx[1] let stxNew ← liftMacroM $ Term.expandMatchAltsIntoMatchTactic stx matchAlts withMacroExpansion stx stxNew $ evalTactic stxNew private def getIntrosSize : Expr → Nat | Expr.forallE _ _ b _ => getIntrosSize b + 1 | Expr.letE _ _ _ b _ => getIntrosSize b + 1 | _ => 0 /- Recall that `ident' := ident <|> Term.hole` -/ def getNameOfIdent' (id : Syntax) : Name := if id.isIdent then id.getId else `_ @[builtinTactic «intros»] def evalIntros : Tactic := fun stx => match stx with | `(tactic| intros) => liftMetaTactic fun mvarId => do let type ← Meta.getMVarType mvarId let type ← instantiateMVars type let n := getIntrosSize type let (_, mvarId) ← Meta.introN mvarId n pure [mvarId] | `(tactic| intros $ids*) => liftMetaTactic fun mvarId => do let (_, mvarId) ← Meta.introN mvarId ids.size (ids.map getNameOfIdent').toList pure [mvarId] | _ => throwUnsupportedSyntax def getFVarId (id : Syntax) : TacticM FVarId := withRef id do let fvar? ← liftTermElabM $ Term.isLocalIdent? id; match fvar? with | some fvar => pure fvar.fvarId! | none => throwError! "unknown variable '{id.getId}'" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainMVarContext $ ids.mapM getFVarId @[builtinTactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx => match stx with | `(tactic| revert $hs*) => do let (g, gs) ← getMainGoal let fvarIds ← getFVarIds hs let (_, g) ← Meta.revert g fvarIds setGoals (g :: gs) | _ => throwUnsupportedSyntax /- Sort free variables using an order `x < y` iff `x` was defined after `y` -/ private def sortFVarIds (fvarIds : Array FVarId) : TacticM (Array FVarId) := withMainMVarContext do let lctx ← getLCtx pure $ fvarIds.qsort fun fvarId₁ fvarId₂ => match lctx.find? fvarId₁, lctx.find? fvarId₂ with | some d₁, some d₂ => d₁.index > d₂.index | some _, none => false | none, some _ => true | none, none => Name.quickLt fvarId₁ fvarId₂ @[builtinTactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx => match stx with | `(tactic| clear $hs*) => do let fvarIds ← getFVarIds hs let fvarIds ← sortFVarIds fvarIds for fvarId in fvarIds do let (g, gs) ← getMainGoal withMVarContext g do let g ← clear g fvarId setGoals (g :: gs) | _ => throwUnsupportedSyntax def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do for h in hs do let (g, gs) ← getMainGoal; withMVarContext g do let fvarId ← getFVarId h let g ← tac g fvarId setGoals (g :: gs) @[builtinTactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx => match stx with | `(tactic| subst $hs*) => forEachVar hs Meta.subst | _ => throwUnsupportedSyntax /-- First method searches for a metavariable `g` s.t. `tag` is a suffix of its name. If none is found, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/ private def findTag? (gs : List MVarId) (tag : Name) : TacticM (Option MVarId) := do let g? ← gs.findM? (fun g => do pure $ tag.isSuffixOf (← getMVarDecl g).userName); match g? with | some g => pure g | none => gs.findM? (fun g => do pure $ tag.isPrefixOf (← getMVarDecl g).userName) @[builtinTactic «case»] def evalCase : Tactic := fun stx => match stx with | `(tactic| case $tag => $tac:tacticSeq) => do let tag := tag.getId let gs ← getUnsolvedGoals let some g ← findTag? gs tag | throwError "tag not found" let gs := gs.erase g setGoals [g] let savedTag ← liftM $ getMVarTag g liftM $ setMVarTag g Name.anonymous try closeUsingOrAdmit tac finally liftM $ setMVarTag g savedTag done setGoals gs | _ => throwUnsupportedSyntax @[builtinTactic «first»] partial def evalFirst : Tactic := fun stx => do let tacs := stx[2].getSepArgs if tacs.isEmpty then throwUnsupportedSyntax loop tacs 0 where loop (tacs : Array Syntax) (i : Nat) := if i == tacs.size - 1 then evalTactic tacs[i] else evalTactic tacs[i] <|> loop tacs (i+1) builtin_initialize registerTraceClass `Elab.tactic @[inline] def TacticM.run {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM (α × State) := x ctx |>.run s @[inline] def TacticM.run' {α} (x : TacticM α) (ctx : Context) (s : State) : TermElabM α := Prod.fst <$> x.run ctx s end Lean.Elab.Tactic
822e1c74c064a5368c035df34f23e666058afae0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/linear_algebra/matrix.lean
a3d4639791fdf9a56a7746ed8902bd891758d08f
[]
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
42,240
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.linear_algebra.finite_dimensional import Mathlib.linear_algebra.nonsingular_inverse import Mathlib.linear_algebra.multilinear import Mathlib.linear_algebra.dual import Mathlib.PostPort universes u_1 u_3 u_4 u_2 u_6 u_5 u_7 w v u namespace Mathlib /-! # 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. * `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`, the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R` * `matrix.to_lin`: the inverse of `linear_map.to_matrix` * `linear_map.to_matrix'`: the `R`-linear equivalence from `(n → R) →ₗ[R] (m → R)` to `matrix n m R` (with the standard basis on `n → R` and `m → R`) * `matrix.to_lin'`: the inverse of `linear_map.to_matrix'` * `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 -/ protected instance matrix.fintype {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq m] [DecidableEq n] (R : Type u_1) [fintype R] : fintype (matrix m n R) := eq.mpr sorry pi.fintype /-- `matrix.mul_vec M` is a linear map. -/ def matrix.mul_vec_lin {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] (M : matrix m n R) : linear_map R (n → R) (m → R) := linear_map.mk (matrix.mul_vec M) sorry sorry @[simp] theorem matrix.mul_vec_lin_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] (M : matrix m n R) (v : n → R) : coe_fn (matrix.mul_vec_lin M) v = matrix.mul_vec M v := rfl @[simp] theorem matrix.mul_vec_std_basis {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] (M : matrix m n R) (i : m) (j : n) : matrix.mul_vec M (coe_fn (linear_map.std_basis R (fun (_x : n) => R) j) 1) i = M i j := sorry /-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/ def linear_map.to_matrix' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] : linear_equiv R (linear_map R (n → R) (m → R)) (matrix m n R) := linear_equiv.mk (fun (f : linear_map R (n → R) (m → R)) (i : m) (j : n) => coe_fn f (coe_fn (linear_map.std_basis R (fun (ᾰ : n) => R) j) 1) i) sorry sorry matrix.mul_vec_lin sorry sorry /-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`. -/ def matrix.to_lin' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] : linear_equiv R (matrix m n R) (linear_map R (n → R) (m → R)) := linear_equiv.symm linear_map.to_matrix' @[simp] theorem linear_map.to_matrix'_symm {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] : linear_equiv.symm linear_map.to_matrix' = matrix.to_lin' := rfl @[simp] theorem matrix.to_lin'_symm {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] : linear_equiv.symm matrix.to_lin' = linear_map.to_matrix' := rfl @[simp] theorem linear_map.to_matrix'_to_lin' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] (M : matrix m n R) : coe_fn linear_map.to_matrix' (coe_fn matrix.to_lin' M) = M := linear_equiv.apply_symm_apply linear_map.to_matrix' M @[simp] theorem matrix.to_lin'_to_matrix' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] (f : linear_map R (n → R) (m → R)) : coe_fn matrix.to_lin' (coe_fn linear_map.to_matrix' f) = f := linear_equiv.apply_symm_apply matrix.to_lin' f @[simp] theorem linear_map.to_matrix'_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] (f : linear_map R (n → R) (m → R)) (i : m) (j : n) : coe_fn linear_map.to_matrix' f i j = coe_fn f (fun (j' : n) => ite (j' = j) 1 0) i := sorry @[simp] theorem matrix.to_lin'_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] (M : matrix m n R) (v : n → R) : coe_fn (coe_fn matrix.to_lin' M) v = matrix.mul_vec M v := rfl @[simp] theorem matrix.to_lin'_one {R : Type u_1} [comm_ring R] {n : Type u_4} [fintype n] [DecidableEq n] : coe_fn matrix.to_lin' 1 = linear_map.id := sorry @[simp] theorem linear_map.to_matrix'_id {R : Type u_1} [comm_ring R] {n : Type u_4} [fintype n] [DecidableEq n] : coe_fn linear_map.to_matrix' linear_map.id = 1 := sorry @[simp] theorem matrix.to_lin'_mul {R : Type u_1} [comm_ring R] {l : Type u_2} {m : Type u_3} {n : Type u_4} [fintype l] [fintype m] [fintype n] [DecidableEq n] [DecidableEq m] (M : matrix l m R) (N : matrix m n R) : coe_fn matrix.to_lin' (matrix.mul M N) = linear_map.comp (coe_fn matrix.to_lin' M) (coe_fn matrix.to_lin' N) := sorry theorem linear_map.to_matrix'_comp {R : Type u_1} [comm_ring R] {l : Type u_2} {m : Type u_3} {n : Type u_4} [fintype l] [fintype m] [fintype n] [DecidableEq n] [DecidableEq l] (f : linear_map R (n → R) (m → R)) (g : linear_map R (l → R) (n → R)) : coe_fn linear_map.to_matrix' (linear_map.comp f g) = matrix.mul (coe_fn linear_map.to_matrix' f) (coe_fn linear_map.to_matrix' g) := sorry theorem linear_map.to_matrix'_mul {R : Type u_1} [comm_ring R] {m : Type u_3} [fintype m] [DecidableEq m] (f : linear_map R (m → R) (m → R)) (g : linear_map R (m → R) (m → R)) : coe_fn linear_map.to_matrix' (f * g) = matrix.mul (coe_fn linear_map.to_matrix' f) (coe_fn linear_map.to_matrix' g) := linear_map.to_matrix'_comp f g /-- 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_map.to_matrix {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) : linear_equiv R (linear_map R M₁ M₂) (matrix m n R) := linear_equiv.trans (linear_equiv.arrow_congr (is_basis.equiv_fun hv₁) (is_basis.equiv_fun hv₂)) linear_map.to_matrix' /-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/ def matrix.to_lin {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) : linear_equiv R (matrix m n R) (linear_map R M₁ M₂) := linear_equiv.symm (linear_map.to_matrix hv₁ hv₂) @[simp] theorem linear_map.to_matrix_symm {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) : linear_equiv.symm (linear_map.to_matrix hv₁ hv₂) = matrix.to_lin hv₁ hv₂ := rfl @[simp] theorem matrix.to_lin_symm {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) : linear_equiv.symm (matrix.to_lin hv₁ hv₂) = linear_map.to_matrix hv₁ hv₂ := rfl @[simp] theorem matrix.to_lin_to_matrix {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (f : linear_map R M₁ M₂) : coe_fn (matrix.to_lin hv₁ hv₂) (coe_fn (linear_map.to_matrix hv₁ hv₂) f) = f := sorry @[simp] theorem linear_map.to_matrix_to_lin {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (M : matrix m n R) : coe_fn (linear_map.to_matrix hv₁ hv₂) (coe_fn (matrix.to_lin hv₁ hv₂) M) = M := sorry theorem linear_map.to_matrix_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (f : linear_map R M₁ M₂) (i : m) (j : n) : coe_fn (linear_map.to_matrix hv₁ hv₂) f i j = coe_fn (is_basis.equiv_fun hv₂) (coe_fn f (v₁ j)) i := sorry theorem linear_map.to_matrix_transpose_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (f : linear_map R M₁ M₂) (j : n) : matrix.transpose (coe_fn (linear_map.to_matrix hv₁ hv₂) f) j = coe_fn (is_basis.equiv_fun hv₂) (coe_fn f (v₁ j)) := funext fun (i : m) => linear_map.to_matrix_apply hv₁ hv₂ f i j theorem linear_map.to_matrix_apply' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (f : linear_map R M₁ M₂) (i : m) (j : n) : coe_fn (linear_map.to_matrix hv₁ hv₂) f i j = coe_fn (coe_fn (is_basis.repr hv₂) (coe_fn f (v₁ j))) i := linear_map.to_matrix_apply hv₁ hv₂ f i j theorem linear_map.to_matrix_transpose_apply' {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (f : linear_map R M₁ M₂) (j : n) : matrix.transpose (coe_fn (linear_map.to_matrix hv₁ hv₂) f) j = ⇑(coe_fn (is_basis.repr hv₂) (coe_fn f (v₁ j))) := linear_map.to_matrix_transpose_apply hv₁ hv₂ f j theorem matrix.to_lin_apply {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (M : matrix m n R) (v : M₁) : coe_fn (coe_fn (matrix.to_lin hv₁ hv₂) M) v = finset.sum finset.univ fun (j : m) => matrix.mul_vec M (coe_fn (is_basis.equiv_fun hv₁) v) j • v₂ j := sorry @[simp] theorem matrix.to_lin_self {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) (M : matrix m n R) (i : n) : coe_fn (coe_fn (matrix.to_lin hv₁ hv₂) M) (v₁ i) = finset.sum finset.univ fun (j : m) => M j i • v₂ j := sorry @[simp] theorem linear_map.to_matrix_id {R : Type u_1} [comm_ring R] {n : Type u_4} [fintype n] [DecidableEq n] {M₁ : Type u_5} [add_comm_group M₁] [module R M₁] {v₁ : n → M₁} (hv₁ : is_basis R v₁) : coe_fn (linear_map.to_matrix hv₁ hv₁) linear_map.id = 1 := sorry @[simp] theorem matrix.to_lin_one {R : Type u_1} [comm_ring R] {n : Type u_4} [fintype n] [DecidableEq n] {M₁ : Type u_5} [add_comm_group M₁] [module R M₁] {v₁ : n → M₁} (hv₁ : is_basis R v₁) : coe_fn (matrix.to_lin hv₁ hv₁) 1 = linear_map.id := sorry theorem linear_map.to_matrix_range {R : Type u_1} [comm_ring R] {m : Type u_3} {n : Type u_4} [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) [DecidableEq M₁] [DecidableEq M₂] (f : linear_map R M₁ M₂) (k : m) (i : n) : coe_fn (linear_map.to_matrix (is_basis.range hv₁) (is_basis.range hv₂)) f { val := v₂ k, property := set.mem_range_self k } { val := v₁ i, property := set.mem_range_self i } = coe_fn (linear_map.to_matrix hv₁ hv₂) f k i := sorry theorem linear_map.to_matrix_comp {R : Type u_1} [comm_ring R] {l : Type u_2} {m : Type u_3} {n : Type u_4} [fintype l] [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) {M₃ : Type u_7} [add_comm_group M₃] [module R M₃] {v₃ : l → M₃} (hv₃ : is_basis R v₃) [DecidableEq m] (f : linear_map R M₂ M₃) (g : linear_map R M₁ M₂) : coe_fn (linear_map.to_matrix hv₁ hv₃) (linear_map.comp f g) = matrix.mul (coe_fn (linear_map.to_matrix hv₂ hv₃) f) (coe_fn (linear_map.to_matrix hv₁ hv₂) g) := sorry theorem linear_map.to_matrix_mul {R : Type u_1} [comm_ring R] {n : Type u_4} [fintype n] [DecidableEq n] {M₁ : Type u_5} [add_comm_group M₁] [module R M₁] {v₁ : n → M₁} (hv₁ : is_basis R v₁) (f : linear_map R M₁ M₁) (g : linear_map R M₁ M₁) : coe_fn (linear_map.to_matrix hv₁ hv₁) (f * g) = matrix.mul (coe_fn (linear_map.to_matrix hv₁ hv₁) f) (coe_fn (linear_map.to_matrix hv₁ hv₁) g) := sorry theorem matrix.to_lin_mul {R : Type u_1} [comm_ring R] {l : Type u_2} {m : Type u_3} {n : Type u_4} [fintype l] [fintype m] [fintype n] [DecidableEq n] {M₁ : Type u_5} {M₂ : Type u_6} [add_comm_group M₁] [add_comm_group M₂] [module R M₁] [module R M₂] {v₁ : n → M₁} (hv₁ : is_basis R v₁) {v₂ : m → M₂} (hv₂ : is_basis R v₂) {M₃ : Type u_7} [add_comm_group M₃] [module R M₃] {v₃ : l → M₃} (hv₃ : is_basis R v₃) [DecidableEq m] (A : matrix l m R) (B : matrix m n R) : coe_fn (matrix.to_lin hv₁ hv₃) (matrix.mul A B) = linear_map.comp (coe_fn (matrix.to_lin hv₂ hv₃) A) (coe_fn (matrix.to_lin hv₁ hv₂) B) := sorry /-- 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 {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) : matrix ι ι' R := fun (i : ι) (j : ι') => coe_fn (is_basis.equiv_fun he) (v j) i namespace is_basis theorem to_matrix_apply {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) (i : ι) (j : ι') : to_matrix he v i j = coe_fn (equiv_fun he) (v j) i := rfl theorem to_matrix_transpose_apply {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) (j : ι') : matrix.transpose (to_matrix he v) j = ⇑(coe_fn (repr he) (v j)) := funext fun (_x : ι) => rfl theorem to_matrix_eq_to_matrix_constr {ι : Type u_1} [fintype ι] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) [DecidableEq ι] (v : ι → M) : to_matrix he v = coe_fn (linear_map.to_matrix he he) (constr he v) := sorry @[simp] theorem to_matrix_self {ι : Type u_1} [fintype ι] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) [DecidableEq ι] : to_matrix he e = 1 := sorry theorem to_matrix_update {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) (j : ι') [DecidableEq ι'] (x : M) : to_matrix he (function.update v j x) = matrix.update_column (to_matrix he v) j ⇑(coe_fn (repr he) x) := sorry @[simp] theorem sum_to_matrix_smul_self {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) (j : ι') : (finset.sum finset.univ fun (i : ι) => to_matrix he v i j • e i) = v j := sorry @[simp] theorem to_lin_to_matrix {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) (v : ι' → M) [DecidableEq ι'] (hv : is_basis R v) : coe_fn (matrix.to_lin hv he) (to_matrix he v) = linear_map.id := sorry /-- 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 {ι : Type u_1} [fintype ι] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {e : ι → M} (he : is_basis R e) : linear_equiv R (ι → M) (matrix ι ι R) := linear_equiv.mk (to_matrix he) sorry sorry (fun (m : matrix ι ι R) (j : ι) => finset.sum finset.univ fun (i : ι) => m i j • e i) sorry sorry end is_basis @[simp] theorem is_basis_to_matrix_mul_linear_map_to_matrix {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {N : Type u_5} [add_comm_group N] [module R N] {b' : ι' → M} {c : ι → N} {c' : ι' → N} (hb' : is_basis R b') (hc : is_basis R c) (hc' : is_basis R c') (f : linear_map R M N) [DecidableEq ι'] : matrix.mul (is_basis.to_matrix hc c') (coe_fn (linear_map.to_matrix hb' hc') f) = coe_fn (linear_map.to_matrix hb' hc) f := sorry @[simp] theorem linear_map_to_matrix_mul_is_basis_to_matrix {ι : Type u_1} {ι' : Type u_2} [fintype ι] [fintype ι'] {R : Type u_3} {M : Type u_4} [comm_ring R] [add_comm_group M] [module R M] {N : Type u_5} [add_comm_group N] [module R N] {b : ι → M} {b' : ι' → M} {c' : ι' → N} (hb : is_basis R b) (hb' : is_basis R b') (hc' : is_basis R c') (f : linear_map R M N) [DecidableEq ι] [DecidableEq ι'] : matrix.mul (coe_fn (linear_map.to_matrix hb' hc') f) (is_basis.to_matrix hb' b) = coe_fn (linear_map.to_matrix hb hc') f := sorry theorem linear_equiv.is_unit_det {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {M' : Type u_2} [add_comm_group M'] [module R M'] {ι : Type u_3} [DecidableEq ι] [fintype ι] {v : ι → M} {v' : ι → M'} (f : linear_equiv R M M') (hv : is_basis R v) (hv' : is_basis R v') : is_unit (matrix.det (coe_fn (linear_map.to_matrix hv hv') ↑f)) := sorry /-- Builds a linear equivalence from a linear map whose determinant in some bases is a unit. -/ def linear_equiv.of_is_unit_det {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {M' : Type u_2} [add_comm_group M'] [module R M'] {ι : Type u_3} [DecidableEq ι] [fintype ι] {v : ι → M} {v' : ι → M'} {f : linear_map R M M'} {hv : is_basis R v} {hv' : is_basis R v'} (h : is_unit (matrix.det (coe_fn (linear_map.to_matrix hv hv') f))) : linear_equiv R M M' := linear_equiv.mk ⇑f sorry sorry ⇑(coe_fn (matrix.to_lin hv' hv) (coe_fn (linear_map.to_matrix hv hv') f⁻¹)) sorry sorry /-- The determinant of a family of vectors with respect to some basis, as an alternating multilinear map. -/ def is_basis.det {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {ι : Type u_3} [DecidableEq ι] [fintype ι] {e : ι → M} (he : is_basis R e) : alternating_map R M R ι := alternating_map.mk (fun (v : (i : ι) → (fun (i : ι) => M) i) => matrix.det (is_basis.to_matrix he v)) sorry sorry sorry theorem is_basis.det_apply {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {ι : Type u_3} [DecidableEq ι] [fintype ι] {e : ι → M} (he : is_basis R e) (v : ι → M) : coe_fn (is_basis.det he) v = matrix.det (is_basis.to_matrix he v) := rfl theorem is_basis.det_self {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {ι : Type u_3} [DecidableEq ι] [fintype ι] {e : ι → M} (he : is_basis R e) : coe_fn (is_basis.det he) e = 1 := sorry theorem is_basis.iff_det {R : Type} [comm_ring R] {M : Type u_1} [add_comm_group M] [module R M] {ι : Type u_3} [DecidableEq ι] [fintype ι] {e : ι → M} (he : is_basis R e) {v : ι → M} : is_basis R v ↔ is_unit (coe_fn (is_basis.det he) v) := sorry @[simp] theorem linear_map.to_matrix_transpose {K : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {ι₁ : Type u_4} {ι₂ : Type u_5} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] [fintype ι₁] [fintype ι₂] [DecidableEq ι₁] [DecidableEq ι₂] {B₁ : ι₁ → V₁} (h₁ : is_basis K B₁) {B₂ : ι₂ → V₂} (h₂ : is_basis K B₂) (u : linear_map K V₁ V₂) : coe_fn (linear_map.to_matrix (is_basis.dual_basis_is_basis h₂) (is_basis.dual_basis_is_basis h₁)) (coe_fn module.dual.transpose u) = matrix.transpose (coe_fn (linear_map.to_matrix h₁ h₂) u) := sorry theorem linear_map.to_matrix_symm_transpose {K : Type u_1} {V₁ : Type u_2} {V₂ : Type u_3} {ι₁ : Type u_4} {ι₂ : Type u_5} [field K] [add_comm_group V₁] [vector_space K V₁] [add_comm_group V₂] [vector_space K V₂] [fintype ι₁] [fintype ι₂] [DecidableEq ι₁] [DecidableEq ι₂] {B₁ : ι₁ → V₁} (h₁ : is_basis K B₁) {B₂ : ι₂ → V₂} (h₂ : is_basis K B₂) (M : matrix ι₁ ι₂ K) : coe_fn (linear_equiv.symm (linear_map.to_matrix (is_basis.dual_basis_is_basis h₁) (is_basis.dual_basis_is_basis h₂))) (matrix.transpose M) = coe_fn module.dual.transpose (coe_fn (matrix.to_lin h₂ h₁) M) := sorry namespace matrix /-- The diagonal of a square matrix. -/ def diag (n : Type u_2) [fintype n] (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M] : linear_map R (matrix n n M) (n → M) := linear_map.mk (fun (A : matrix n n M) (i : n) => A i i) sorry sorry @[simp] theorem diag_apply {n : Type u_2} [fintype n] {R : Type v} {M : Type w} [semiring R] [add_comm_monoid M] [semimodule R M] (A : matrix n n M) (i : n) : coe_fn (diag n R M) A i = A i i := rfl @[simp] theorem diag_one {n : Type u_2} [fintype n] {R : Type v} [semiring R] [DecidableEq n] : coe_fn (diag n R R) 1 = fun (i : n) => 1 := sorry @[simp] theorem diag_transpose {n : Type u_2} [fintype n] {R : Type v} {M : Type w} [semiring R] [add_comm_monoid M] [semimodule R M] (A : matrix n n M) : coe_fn (diag n R M) (transpose A) = coe_fn (diag n R M) A := rfl /-- The trace of a square matrix. -/ def trace (n : Type u_2) [fintype n] (R : Type v) (M : Type w) [semiring R] [add_comm_monoid M] [semimodule R M] : linear_map R (matrix n n M) M := linear_map.mk (fun (A : matrix n n M) => finset.sum finset.univ fun (i : n) => coe_fn (diag n R M) A i) sorry sorry @[simp] theorem trace_diag {n : Type u_2} [fintype n] {R : Type v} {M : Type w} [semiring R] [add_comm_monoid M] [semimodule R M] (A : matrix n n M) : coe_fn (trace n R M) A = finset.sum finset.univ fun (i : n) => coe_fn (diag n R M) A i := rfl @[simp] theorem trace_one {n : Type u_2} [fintype n] {R : Type v} [semiring R] [DecidableEq n] : coe_fn (trace n R R) 1 = ↑(fintype.card n) := sorry @[simp] theorem trace_transpose {n : Type u_2} [fintype n] {R : Type v} {M : Type w} [semiring R] [add_comm_monoid M] [semimodule R M] (A : matrix n n M) : coe_fn (trace n R M) (transpose A) = coe_fn (trace n R M) A := rfl @[simp] theorem trace_transpose_mul {m : Type u_1} [fintype m] {n : Type u_2} [fintype n] {R : Type v} [semiring R] (A : matrix m n R) (B : matrix n m R) : coe_fn (trace n R R) (matrix.mul (transpose A) (transpose B)) = coe_fn (trace m R R) (matrix.mul A B) := finset.sum_comm theorem trace_mul_comm {m : Type u_1} [fintype m] {n : Type u_2} [fintype n] {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) : coe_fn (trace n S S) (matrix.mul B A) = coe_fn (trace m S S) (matrix.mul A B) := sorry theorem proj_diagonal {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (i : n) (w : n → R) : linear_map.comp (linear_map.proj i) (coe_fn to_lin' (diagonal w)) = w i • linear_map.proj i := sorry theorem diagonal_comp_std_basis {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (w : n → R) (i : n) : linear_map.comp (coe_fn to_lin' (diagonal w)) (linear_map.std_basis R (fun (ᾰ : n) => R) i) = w i • linear_map.std_basis R (fun (ᾰ : n) => R) i := sorry theorem diagonal_to_lin' {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (w : n → R) : coe_fn to_lin' (diagonal w) = linear_map.pi fun (i : n) => w i • linear_map.proj i := sorry /-- An invertible matrix yields a linear equivalence from the free module to itself. -/ def to_linear_equiv {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (P : matrix n n R) (h : is_unit P) : linear_equiv R (n → R) (n → R) := (fun (h' : is_unit (det P)) => linear_equiv.mk (linear_map.to_fun (coe_fn to_lin' P)) sorry sorry ⇑(coe_fn to_lin' (P⁻¹)) sorry sorry) sorry @[simp] theorem to_linear_equiv_apply {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (P : matrix n n R) (h : is_unit P) : ↑(to_linear_equiv P h) = coe_fn to_lin' P := rfl @[simp] theorem to_linear_equiv_symm_apply {n : Type u_1} [fintype n] [DecidableEq n] {R : Type v} [comm_ring R] (P : matrix n n R) (h : is_unit P) : ↑(linear_equiv.symm (to_linear_equiv P h)) = coe_fn to_lin' (P⁻¹) := rfl theorem rank_vec_mul_vec {K : Type u} [field K] {m : Type u} {n : Type u} [fintype m] [fintype n] [DecidableEq n] (w : m → K) (v : n → K) : rank (coe_fn to_lin' (vec_mul_vec w v)) ≤ 1 := sorry theorem ker_diagonal_to_lin' {m : Type u_1} [fintype m] {K : Type u} [field K] [DecidableEq m] (w : m → K) : linear_map.ker (coe_fn to_lin' (diagonal w)) = supr fun (i : m) => supr fun (H : i ∈ set_of fun (i : m) => w i = 0) => linear_map.range (linear_map.std_basis K (fun (ᾰ : m) => K) i) := sorry theorem range_diagonal {m : Type u_1} [fintype m] {K : Type u} [field K] [DecidableEq m] (w : m → K) : linear_map.range (coe_fn to_lin' (diagonal w)) = supr fun (i : m) => supr fun (H : i ∈ set_of fun (i : m) => w i ≠ 0) => linear_map.range (linear_map.std_basis K (fun (ᾰ : m) => K) i) := sorry theorem rank_diagonal {m : Type u_1} [fintype m] {K : Type u} [field K] [DecidableEq m] [DecidableEq K] (w : m → K) : rank (coe_fn to_lin' (diagonal w)) = ↑(fintype.card (Subtype fun (i : m) => w i ≠ 0)) := sorry protected instance finite_dimensional {m : Type u_1} {n : Type u_2} [fintype m] [fintype n] {R : Type v} [field R] : finite_dimensional R (matrix m n R) := linear_equiv.finite_dimensional (linear_equiv.symm (linear_equiv.uncurry R m n)) /-- The dimension of the space of finite dimensional matrices is the product of the number of rows and columns. -/ @[simp] theorem findim_matrix {m : Type u_1} {n : Type u_2} [fintype m] [fintype n] {R : Type v} [field R] : finite_dimensional.findim R (matrix m n R) = fintype.card m * fintype.card n := sorry /-- The natural map that reindexes a matrix's rows and columns with equivalent types is an equivalence. -/ def reindex {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} (eₘ : m ≃ m') (eₙ : n ≃ n') : matrix m n R ≃ matrix m' n' R := equiv.mk (fun (M : matrix m n R) (i : m') (j : n') => M (coe_fn (equiv.symm eₘ) i) (coe_fn (equiv.symm eₙ) j)) (fun (M : matrix m' n' R) (i : m) (j : n) => M (coe_fn eₘ i) (coe_fn eₙ j)) sorry sorry @[simp] theorem reindex_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : coe_fn (reindex eₘ eₙ) M = fun (i : m') (j : n') => M (coe_fn (equiv.symm eₘ) i) (coe_fn (equiv.symm eₙ) j) := rfl @[simp] theorem reindex_symm_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : coe_fn (equiv.symm (reindex eₘ eₙ)) M = fun (i : m) (j : n) => M (coe_fn eₘ i) (coe_fn 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 {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') : linear_equiv R (matrix m n R) (matrix m' n' R) := linear_equiv.mk (equiv.to_fun (reindex eₘ eₙ)) sorry sorry (equiv.inv_fun (reindex eₘ eₙ)) sorry sorry @[simp] theorem reindex_linear_equiv_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : coe_fn (reindex_linear_equiv eₘ eₙ) M = fun (i : m') (j : n') => M (coe_fn (equiv.symm eₘ) i) (coe_fn (equiv.symm eₙ) j) := rfl @[simp] theorem reindex_linear_equiv_symm_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m' n' R) : coe_fn (linear_equiv.symm (reindex_linear_equiv eₘ eₙ)) M = fun (i : m) (j : n) => M (coe_fn eₘ i) (coe_fn eₙ j) := rfl theorem reindex_mul {l : Type u_1} {m : Type u_2} {n : Type u_3} [fintype l] [fintype m] [fintype n] {l' : Type u_4} {m' : Type u_5} {n' : Type u_6} [fintype l'] [fintype m'] [fintype n'] {R : Type v} [semiring R] (eₘ : m ≃ m') (eₙ : n ≃ n') (eₗ : l ≃ l') (M : matrix m n R) (N : matrix n l R) : matrix.mul (coe_fn (reindex_linear_equiv eₘ eₙ) M) (coe_fn (reindex_linear_equiv eₙ eₗ) N) = coe_fn (reindex_linear_equiv eₘ eₗ) (matrix.mul M N) := sorry /-- 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 {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [comm_semiring R] [DecidableEq m] [DecidableEq n] (e : m ≃ n) : alg_equiv R (matrix m m R) (matrix n n R) := alg_equiv.mk (linear_equiv.to_fun (reindex_linear_equiv e e)) (linear_equiv.inv_fun (reindex_linear_equiv e e)) sorry sorry sorry sorry sorry @[simp] theorem reindex_alg_equiv_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [comm_semiring R] [DecidableEq m] [DecidableEq n] (e : m ≃ n) (M : matrix m m R) : coe_fn (reindex_alg_equiv e) M = fun (i j : n) => M (coe_fn (equiv.symm e) i) (coe_fn (equiv.symm e) j) := rfl @[simp] theorem reindex_alg_equiv_symm_apply {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [comm_semiring R] [DecidableEq m] [DecidableEq n] (e : m ≃ n) (M : matrix n n R) : coe_fn (alg_equiv.symm (reindex_alg_equiv e)) M = fun (i j : m) => M (coe_fn e i) (coe_fn e j) := rfl theorem reindex_transpose {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {m' : Type u_5} {n' : Type u_6} [fintype m'] [fintype n'] {R : Type v} (eₘ : m ≃ m') (eₙ : n ≃ n') (M : matrix m n R) : transpose (coe_fn (reindex eₘ eₙ) M) = coe_fn (reindex eₙ eₘ) (transpose M) := rfl /-- `simp` version of `det_reindex_self` `det_reindex_self` is not a good simp lemma because `reindex_apply` fires before. So we have this lemma to continue from there. -/ @[simp] theorem det_reindex_self' {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [DecidableEq m] [DecidableEq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : (det fun (i j : n) => A (coe_fn (equiv.symm e) i) (coe_fn (equiv.symm e) j)) = det A := sorry /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ theorem det_reindex_self {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [DecidableEq m] [DecidableEq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (coe_fn (reindex e e) A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ theorem det_reindex_linear_equiv_self {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [DecidableEq m] [DecidableEq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (coe_fn (reindex_linear_equiv e e) A) = det A := det_reindex_self' e A /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_reindex_self'`. -/ theorem det_reindex_alg_equiv {m : Type u_2} {n : Type u_3} [fintype m] [fintype n] {R : Type v} [DecidableEq m] [DecidableEq n] [comm_ring R] (e : m ≃ n) (A : matrix m m R) : det (coe_fn (reindex_alg_equiv e) A) = det A := det_reindex_self' e A end matrix namespace linear_map /-- 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} [DecidableEq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : linear_map R (linear_map R M M) R := comp (matrix.trace ι R R) ↑(to_matrix hb hb) @[simp] theorem trace_aux_def (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [DecidableEq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) (f : linear_map R M M) : coe_fn (trace_aux R hb) f = coe_fn (matrix.trace ι R R) (coe_fn (to_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} [DecidableEq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type w} [DecidableEq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := sorry theorem trace_aux_range (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] {ι : Type w} [DecidableEq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) : trace_aux R (is_basis.range hb) = trace_aux R hb := sorry /-- 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 u_1} [DecidableEq ι] [fintype ι] {b : ι → M} (hb : is_basis R b) {κ : Type u_2} [DecidableEq κ] [fintype κ] {c : κ → M} (hc : is_basis R c) : trace_aux R hb = trace_aux R hc := sorry /-- 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] : linear_map R (linear_map R M M) R := dite (∃ (s : finset M), is_basis R fun (x : ↥↑s) => ↑x) (fun (H : ∃ (s : finset M), is_basis R fun (x : ↥↑s) => ↑x) => trace_aux R sorry) fun (H : ¬∃ (s : finset M), is_basis R fun (x : ↥↑s) => ↑x) => 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 ι] [DecidableEq ι] {b : ι → M} (hb : is_basis R b) (f : linear_map R M M) : coe_fn (trace R M) f = coe_fn (matrix.trace ι R R) (coe_fn (to_matrix hb hb) f) := sorry theorem trace_mul_comm (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] (f : linear_map R M M) (g : linear_map R M M) : coe_fn (trace R M) (f * g) = coe_fn (trace R M) (g * f) := sorry protected instance finite_dimensional {K : Type u_1} [field K] {V : Type u_2} [add_comm_group V] [vector_space K V] [finite_dimensional K V] {W : Type u_3} [add_comm_group W] [vector_space K W] [finite_dimensional K W] : finite_dimensional K (linear_map K V W) := Exists.dcases_on (finite_dimensional.exists_is_basis_finset K V) fun (bV : finset V) (hbV : is_basis K coe) => Exists.dcases_on (finite_dimensional.exists_is_basis_finset K W) fun (bW : finset W) (hbW : is_basis K coe) => linear_equiv.finite_dimensional (linear_equiv.symm (to_matrix hbV hbW)) /-- The dimension of the space of linear transformations is the product of the dimensions of the domain and codomain. -/ @[simp] theorem findim_linear_map {K : Type u_1} [field K] {V : Type u_2} [add_comm_group V] [vector_space K V] [finite_dimensional K V] {W : Type u_3} [add_comm_group W] [vector_space K W] [finite_dimensional K W] : finite_dimensional.findim K (linear_map K V W) = finite_dimensional.findim K V * finite_dimensional.findim K W := sorry 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] {n : Type u_1} [fintype n] [DecidableEq n] : alg_equiv R (module.End R (n → R)) (matrix n n R) := alg_equiv.mk (linear_equiv.to_fun linear_map.to_matrix') (linear_equiv.inv_fun linear_map.to_matrix') sorry sorry sorry sorry sorry /-- 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₁ : Type u_1} {M₂ : Type (max u_2 u_3)} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] (e : linear_equiv R M₁ M₂) : alg_equiv R (module.End R M₁) (module.End R M₂) := alg_equiv.mk (linear_equiv.to_fun (linear_equiv.conj e)) (linear_equiv.inv_fun (linear_equiv.conj e)) sorry sorry sorry sorry sorry /-- 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} {n : Type u_1} [fintype n] [comm_ring R] [add_comm_group M] [module R M] [DecidableEq n] {b : n → M} (h : is_basis R b) : alg_equiv R (module.End R M) (matrix n n R) := alg_equiv.trans (linear_equiv.alg_conj (is_basis.equiv_fun h)) alg_equiv_matrix' @[simp] theorem matrix.dot_product_std_basis_eq_mul {R : Type v} [semiring R] {n : Type w} [fintype n] [DecidableEq n] (v : n → R) (c : R) (i : n) : matrix.dot_product v (coe_fn (linear_map.std_basis R (fun (_x : n) => R) i) c) = v i * c := sorry @[simp] theorem matrix.dot_product_std_basis_one {R : Type v} [semiring R] {n : Type w} [fintype n] [DecidableEq n] (v : n → R) (i : n) : matrix.dot_product v (coe_fn (linear_map.std_basis R (fun (_x : n) => R) i) 1) = v i := sorry theorem matrix.dot_product_eq {R : Type v} [semiring R] {n : Type w} [fintype n] (v : n → R) (w : n → R) (h : ∀ (u : n → R), matrix.dot_product v u = matrix.dot_product w u) : v = w := sorry theorem matrix.dot_product_eq_iff {R : Type v} [semiring R] {n : Type w} [fintype n] {v : n → R} {w : n → R} : (∀ (u : n → R), matrix.dot_product v u = matrix.dot_product w u) ↔ v = w := { mp := fun (h : ∀ (u : n → R), matrix.dot_product v u = matrix.dot_product w u) => matrix.dot_product_eq v w h, mpr := fun (h : v = w) (_x : n → R) => h ▸ rfl } theorem matrix.dot_product_eq_zero {R : Type v} [semiring R] {n : Type w} [fintype n] (v : n → R) (h : ∀ (w : n → R), matrix.dot_product v w = 0) : v = 0 := matrix.dot_product_eq v 0 fun (u : n → R) => Eq.symm (h u) ▸ Eq.symm (matrix.zero_dot_product u) theorem matrix.dot_product_eq_zero_iff {R : Type v} [semiring R] {n : Type w} [fintype n] {v : n → R} : (∀ (w : n → R), matrix.dot_product v w = 0) ↔ v = 0 := { mp := fun (h : ∀ (w : n → R), matrix.dot_product v w = 0) => matrix.dot_product_eq_zero v h, mpr := fun (h : v = 0) (w : n → R) => Eq.symm h ▸ matrix.zero_dot_product w }
fdd8cb363ab0cc40542dbd5dc3104bca9e921228
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/tropical/basic.lean
119ee6a555244b31b2eee16e55732b0f221086e1
[ "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
15,946
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 algebra.group_power.order import algebra.smul_with_zero /-! # Tropical algebraic structures This file defines algebraic structures of the (min-)tropical numbers, up to the tropical semiring. Some basic lemmas about conversion from the base type `R` to `tropical R` are provided, as well as the expected implementations of tropical addition and tropical multiplication. ## Main declarations * `tropical R`: The type synonym of the tropical interpretation of `R`. If `[linear_order R]`, then addition on `R` is via `min`. * `semiring (tropical R)`: A `linear_ordered_add_comm_monoid_with_top R` induces a `semiring (tropical R)`. If one solely has `[linear_ordered_add_comm_monoid R]`, then the "tropicalization of `R`" would be `tropical (with_top R)`. ## Implementation notes The tropical structure relies on `has_top` and `min`. For the max-tropical numbers, use `order_dual R`. Inspiration was drawn from the implementation of `additive`/`multiplicative`/`opposite`, where a type synonym is created with some barebones API, and quickly made irreducible. Algebraic structures are provided with as few typeclass assumptions as possible, even though most references rely on `semiring (tropical R)` for building up the whole theory. ## References followed * https://arxiv.org/pdf/math/0408099.pdf * https://www.mathenjeans.fr/sites/default/files/sujets/tropical_geometry_-_casagrande.pdf -/ universes u v variables (R : Type u) /-- The tropicalization of a type `R`. -/ def tropical : Type u := R variables {R} namespace tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def trop : R → tropical R := id /-- Reinterpret `x : tropical R` as an element of `R`. See `tropical.trop_equiv` for the equivalence. -/ @[pp_nodot] def untrop : tropical R → R := id lemma trop_injective : function.injective (trop : R → tropical R) := λ _ _, id lemma untrop_injective : function.injective (untrop : tropical R → R) := λ _ _, id @[simp] lemma trop_inj_iff (x y : R) : trop x = trop y ↔ x = y := iff.rfl @[simp] lemma untrop_inj_iff (x y : tropical R) : untrop x = untrop y ↔ x = y := iff.rfl @[simp] lemma trop_untrop (x : tropical R) : trop (untrop x) = x := rfl @[simp] lemma untrop_trop (x : R) : untrop (trop x) = x := rfl lemma left_inverse_trop : function.left_inverse (trop : R → tropical R) untrop := trop_untrop lemma right_inverse_trop : function.right_inverse (trop : R → tropical R) untrop := trop_untrop attribute [irreducible] tropical /-- Reinterpret `x : R` as an element of `tropical R`. See `tropical.trop_order_iso` for the order-preserving equivalence. -/ def trop_equiv : R ≃ tropical R := { to_fun := trop, inv_fun := untrop, left_inv := untrop_trop, right_inv := trop_untrop } @[simp] lemma trop_equiv_coe_fn : (trop_equiv : R → tropical R) = trop := rfl @[simp] lemma trop_equiv_symm_coe_fn : (trop_equiv.symm : tropical R → R) = untrop := rfl lemma trop_eq_iff_eq_untrop {x : R} {y} : trop x = y ↔ x = untrop y := trop_equiv.apply_eq_iff_eq_symm_apply lemma untrop_eq_iff_eq_trop {x} {y : R} : untrop x = y ↔ x = trop y := trop_equiv.symm.apply_eq_iff_eq_symm_apply lemma injective_trop : function.injective (trop : R → tropical R) := trop_equiv.injective lemma injective_untrop : function.injective (untrop : tropical R → R) := trop_equiv.symm.injective lemma surjective_trop : function.surjective (trop : R → tropical R) := trop_equiv.surjective lemma surjective_untrop : function.surjective (untrop : tropical R → R) := trop_equiv.symm.surjective instance [inhabited R] : inhabited (tropical R) := ⟨trop default⟩ /-- Recursing on a `x' : tropical R` is the same as recursing on an `x : R` reinterpreted as a term of `tropical R` via `trop x`. -/ @[simp] def trop_rec {F : Π (X : tropical R), Sort v} (h : Π X, F (trop X)) : Π X, F X := λ X, h (untrop X) instance [decidable_eq R] : decidable_eq (tropical R) := λ x y, decidable_of_iff _ injective_untrop.eq_iff section order instance [has_le R] : has_le (tropical R) := { le := λ x y, untrop x ≤ untrop y } @[simp] lemma untrop_le_iff [has_le R] {x y : tropical R} : untrop x ≤ untrop y ↔ x ≤ y := iff.rfl instance decidable_le [has_le R] [decidable_rel ((≤) : R → R → Prop)] : decidable_rel ((≤) : tropical R → tropical R → Prop) := λ x y, ‹decidable_rel (≤)› (untrop x) (untrop y) instance [has_lt R] : has_lt (tropical R) := { lt := λ x y, untrop x < untrop y } @[simp] lemma untrop_lt_iff [has_lt R] {x y : tropical R} : untrop x < untrop y ↔ x < y := iff.rfl instance decidable_lt [has_lt R] [decidable_rel ((<) : R → R → Prop)] : decidable_rel ((<) : tropical R → tropical R → Prop) := λ x y, ‹decidable_rel (<)› (untrop x) (untrop y) instance [preorder R] : preorder (tropical R) := { le_refl := λ _, le_rfl, le_trans := λ _ _ _ h h', le_trans h h', lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, ..tropical.has_le, ..tropical.has_lt } /-- Reinterpret `x : R` as an element of `tropical R`, preserving the order. -/ def trop_order_iso [preorder R] : R ≃o tropical R := { map_rel_iff' := λ _ _, untrop_le_iff, ..trop_equiv } @[simp] lemma trop_order_iso_coe_fn [preorder R] : (trop_order_iso : R → tropical R) = trop := rfl @[simp] lemma trop_order_iso_symm_coe_fn [preorder R] : (trop_order_iso.symm : tropical R → R) = untrop := rfl lemma trop_monotone [preorder R] : monotone (trop : R → tropical R) := λ _ _, id lemma untrop_monotone [preorder R] : monotone (untrop : tropical R → R) := λ _ _, id instance [partial_order R] : partial_order (tropical R) := { le_antisymm := λ _ _ h h', untrop_injective (le_antisymm h h'), ..tropical.preorder } instance [has_top R] : has_zero (tropical R) := ⟨trop ⊤⟩ instance [has_top R] : has_top (tropical R) := ⟨0⟩ @[simp] lemma untrop_zero [has_top R] : untrop (0 : tropical R) = ⊤ := rfl @[simp] lemma trop_top [has_top R] : trop (⊤ : R) = 0 := rfl @[simp] lemma trop_coe_ne_zero (x : R) : trop (x : with_top R) ≠ 0 . @[simp] lemma zero_ne_trop_coe (x : R) : (0 : tropical (with_top R)) ≠ trop x . @[simp] lemma le_zero [has_le R] [order_top R] (x : tropical R) : x ≤ 0 := le_top instance [has_le R] [order_top R] : order_top (tropical R) := { le_top := λ _, le_top, ..tropical.has_top } variable [linear_order R] /-- Tropical addition is the minimum of two underlying elements of `R`. -/ instance : has_add (tropical R) := ⟨λ x y, trop (min (untrop x) (untrop y))⟩ instance : add_comm_semigroup (tropical R) := { add := (+), add_assoc := λ _ _ _, untrop_injective (min_assoc _ _ _), add_comm := λ _ _, untrop_injective (min_comm _ _) } @[simp] lemma untrop_add (x y : tropical R) : untrop (x + y) = min (untrop x) (untrop y) := rfl @[simp] lemma trop_min (x y : R) : trop (min x y) = trop x + trop y := rfl @[simp] lemma trop_inf (x y : R) : trop (x ⊓ y) = trop x + trop y := rfl lemma trop_add_def (x y : tropical R) : x + y = trop (min (untrop x) (untrop y)) := rfl instance : linear_order (tropical R) := { le_total := λ a b, le_total (untrop a) (untrop b), decidable_le := tropical.decidable_le, decidable_lt := tropical.decidable_lt, decidable_eq := tropical.decidable_eq, max := λ a b, trop (max (untrop a) (untrop b)), max_def := begin ext x y, rw [max_default, max_def, apply_ite trop, trop_untrop, trop_untrop, if_congr untrop_le_iff rfl rfl], end, min := (+), min_def := begin ext x y, rw [trop_add_def, min_default, min_def, apply_ite trop, trop_untrop, trop_untrop, if_congr untrop_le_iff rfl rfl], end, ..tropical.partial_order } @[simp] lemma untrop_sup (x y : tropical R) : untrop (x ⊔ y) = untrop x ⊔ untrop y := rfl @[simp] lemma untrop_max (x y : tropical R) : untrop (max x y) = max (untrop x) (untrop y) := rfl @[simp] lemma min_eq_add : (min : tropical R → tropical R → tropical R) = (+) := rfl @[simp] lemma inf_eq_add : ((⊓) : tropical R → tropical R → tropical R) = (+) := rfl lemma trop_max_def (x y : tropical R) : max x y = trop (max (untrop x) (untrop y)) := rfl lemma trop_sup_def (x y : tropical R) : x ⊔ y = trop (untrop x ⊔ untrop y) := rfl @[simp] lemma add_eq_left ⦃x y : tropical R⦄ (h : x ≤ y) : x + y = x := untrop_injective (by simpa using h) @[simp] lemma add_eq_right ⦃x y : tropical R⦄ (h : y ≤ x) : x + y = y := untrop_injective (by simpa using h) lemma add_eq_left_iff {x y : tropical R} : x + y = x ↔ x ≤ y := by rw [trop_add_def, trop_eq_iff_eq_untrop, ←untrop_le_iff, min_eq_left_iff] lemma add_eq_right_iff {x y : tropical R} : x + y = y ↔ y ≤ x := by rw [trop_add_def, trop_eq_iff_eq_untrop, ←untrop_le_iff, min_eq_right_iff] @[simp] lemma add_self (x : tropical R) : x + x = x := untrop_injective (min_eq_right le_rfl) @[simp] lemma bit0 (x : tropical R) : bit0 x = x := add_self x lemma add_eq_iff {x y z : tropical R} : x + y = z ↔ x = z ∧ x ≤ y ∨ y = z ∧ y ≤ x := by { rw [trop_add_def, trop_eq_iff_eq_untrop], simp [min_eq_iff] } @[simp] lemma add_eq_zero_iff {a b : tropical (with_top R)} : a + b = 0 ↔ a = 0 ∧ b = 0 := begin rw add_eq_iff, split, { rintro (⟨rfl, h⟩|⟨rfl, h⟩), { exact ⟨rfl, le_antisymm (le_zero _) h⟩ }, { exact ⟨le_antisymm (le_zero _) h, rfl⟩ } }, { rintro ⟨rfl, rfl⟩, simp } end instance [order_top R] : add_comm_monoid (tropical R) := { zero_add := λ _, untrop_injective (min_top_left _), add_zero := λ _, untrop_injective (min_top_right _), ..tropical.has_zero, ..tropical.add_comm_semigroup } end order section monoid /-- Tropical multiplication is the addition in the underlying `R`. -/ instance [has_add R] : has_mul (tropical R) := ⟨λ x y, trop (untrop x + untrop y)⟩ @[simp] lemma trop_add [has_add R] (x y : R) : trop (x + y) = trop x * trop y := rfl @[simp] lemma untrop_mul [has_add R] (x y : tropical R) : untrop (x * y) = untrop x + untrop y := rfl lemma trop_mul_def [has_add R] (x y : tropical R) : x * y = trop (untrop x + untrop y) := rfl instance [has_zero R] : has_one (tropical R) := ⟨trop 0⟩ @[simp] lemma trop_zero [has_zero R] : trop (0 : R) = 1 := rfl @[simp] lemma untrop_one [has_zero R] : untrop (1 : tropical R) = 0 := rfl instance [has_zero R] : nontrivial (tropical (with_top R)) := ⟨⟨0, 1, trop_injective.ne with_top.top_ne_coe⟩⟩ instance [has_neg R] : has_inv (tropical R) := ⟨λ x, trop (- untrop x)⟩ @[simp] lemma untrop_inv [has_neg R] (x : tropical R) : untrop x⁻¹ = - untrop x := rfl instance [has_sub R] : has_div (tropical R) := ⟨λ x y, trop (untrop x - untrop y)⟩ @[simp] lemma untrop_div [has_sub R] (x y : tropical R) : untrop (x / y) = untrop x - untrop y := rfl instance [add_semigroup R] : semigroup (tropical R) := { mul := (*), mul_assoc := λ _ _ _, untrop_injective (add_assoc _ _ _) } instance [add_comm_semigroup R] : comm_semigroup (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.semigroup } instance {α : Type*} [has_scalar α R] : has_pow (tropical R) α := { pow := λ x n, trop $ n • untrop x } @[simp] lemma untrop_pow {α : Type*} [has_scalar α R] (x : tropical R) (n : α) : untrop (x ^ n) = n • untrop x := rfl @[simp] lemma trop_smul {α : Type*} [has_scalar α R] (x : R) (n : α) : trop (n • x) = trop x ^ n := rfl instance [add_zero_class R] : mul_one_class (tropical R) := { one := 1, mul := (*), one_mul := λ _, untrop_injective $ zero_add _, mul_one := λ _, untrop_injective $ add_zero _ } instance [add_monoid R] : monoid (tropical R) := { npow := λ n x, x ^ n, npow_zero' := λ _, untrop_injective $ zero_smul _ _, npow_succ' := λ _ _, untrop_injective $ succ_nsmul _ _, ..tropical.mul_one_class, ..tropical.semigroup } @[simp] lemma trop_nsmul [add_monoid R] (x : R) (n : ℕ) : trop (n • x) = trop x ^ n := rfl instance [add_comm_monoid R] : comm_monoid (tropical R) := { ..tropical.monoid, ..tropical.comm_semigroup } instance [add_group R] : group (tropical R) := { inv := has_inv.inv, mul_left_inv := λ _, untrop_injective $ add_left_neg _, zpow := λ n x, trop $ n • untrop x, zpow_zero' := λ _, untrop_injective $ zero_zsmul _, zpow_succ' := λ _ _, untrop_injective $ add_group.zsmul_succ' _ _, zpow_neg' := λ _ _, untrop_injective $ add_group.zsmul_neg' _ _, ..tropical.monoid } instance [add_comm_group R] : comm_group (tropical R) := { mul_comm := λ _ _, untrop_injective (add_comm _ _), ..tropical.group } @[simp] lemma untrop_zpow [add_group R] (x : tropical R) (n : ℤ) : untrop (x ^ n) = n • untrop x := rfl @[simp] lemma trop_zsmul [add_group R] (x : R) (n : ℤ) : trop (n • x) = trop x ^ n := rfl end monoid section distrib instance covariant_mul [has_le R] [has_add R] [covariant_class R R (+) (≤)] : covariant_class (tropical R) (tropical R) (*) (≤) := ⟨λ x y z h, add_le_add_left h _⟩ instance covariant_swap_mul [has_le R] [has_add R] [covariant_class R R (function.swap (+)) (≤)] : covariant_class (tropical R) (tropical R) (function.swap (*)) (≤) := ⟨λ x y z h, add_le_add_right h _⟩ instance covariant_add [linear_order R] : covariant_class (tropical R) (tropical R) (+) (≤) := ⟨λ x y z h, begin cases le_total x y with hx hy, { rw [add_eq_left hx, add_eq_left (hx.trans h)] }, { rw [add_eq_right hy], cases le_total x z with hx hx, { rwa [add_eq_left hx] }, { rwa [add_eq_right hx] } } end⟩ instance covariant_mul_lt [has_lt R] [has_add R] [covariant_class R R (+) (<)] : covariant_class (tropical R) (tropical R) (*) (<) := ⟨λ x y z h, add_lt_add_left h _⟩ instance covariant_swap_mul_lt [preorder R] [has_add R] [covariant_class R R (function.swap (+)) (<)] : covariant_class (tropical R) (tropical R) (function.swap (*)) (<) := ⟨λ x y z h, add_lt_add_right h _⟩ instance [linear_order R] [has_add R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] : distrib (tropical R) := { mul := (*), add := (+), left_distrib := λ _ _ _, untrop_injective (min_add_add_left _ _ _).symm, right_distrib := λ _ _ _, untrop_injective (min_add_add_right _ _ _).symm } @[simp] lemma add_pow [linear_order R] [add_monoid R] [covariant_class R R (+) (≤)] [covariant_class R R (function.swap (+)) (≤)] (x y : tropical R) (n : ℕ) : (x + y) ^ n = x ^ n + y ^ n := begin cases le_total x y with h h, { rw [add_eq_left h, add_eq_left (pow_le_pow_of_le_left' h _)] }, { rw [add_eq_right h, add_eq_right (pow_le_pow_of_le_left' h _)] } end end distrib section semiring variable [linear_ordered_add_comm_monoid_with_top R] instance : comm_semiring (tropical R) := { zero_mul := λ _, untrop_injective (top_add _), mul_zero := λ _, untrop_injective (add_top _), ..tropical.has_zero, ..tropical.distrib, ..tropical.add_comm_monoid, ..tropical.comm_monoid } @[simp] lemma succ_nsmul {R} [linear_order R] [order_top R] (x : tropical R) (n : ℕ) : (n + 1) • x = x := begin induction n with n IH, { simp }, { rw [add_nsmul, IH, one_nsmul, add_self] } end -- TODO: find/create the right classes to make this hold (for enat, ennreal, etc) -- Requires `zero_eq_bot` to be true -- lemma add_eq_zero_iff {a b : tropical R} : -- a + b = 1 ↔ a = 1 ∨ b = 1 := sorry @[simp] lemma mul_eq_zero_iff {R : Type*} [linear_ordered_add_comm_monoid R] {a b : tropical (with_top R)} : a * b = 0 ↔ a = 0 ∨ b = 0 := by simp [←untrop_inj_iff, with_top.add_eq_top] instance {R : Type*} [linear_ordered_add_comm_monoid R] : no_zero_divisors (tropical (with_top R)) := ⟨λ _ _, mul_eq_zero_iff.mp⟩ end semiring end tropical
24ae1205e580746c587f4dcbf79b968fd928e5ad
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/library/data/finset/basic.lean
82164ccec10787399ce48e5acd40161cff700f66
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
28,596
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Jeremy Avigad Finite sets. -/ import data.fintype.basic data.nat data.list.perm algebra.binary open nat quot list subtype binary function eq.ops open [decl] perm definition nodup_list (A : Type) := {l : list A | nodup l} variable {A : Type} definition to_nodup_list_of_nodup {l : list A} (n : nodup l) : nodup_list A := tag l n definition to_nodup_list [decidable_eq A] (l : list A) : nodup_list A := @to_nodup_list_of_nodup A (erase_dup l) (nodup_erase_dup l) private definition eqv (l₁ l₂ : nodup_list A) := perm (elt_of l₁) (elt_of l₂) local infix ~ := eqv private definition eqv.refl (l : nodup_list A) : l ~ l := !perm.refl private definition eqv.symm {l₁ l₂ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₁ := perm.symm private definition eqv.trans {l₁ l₂ l₃ : nodup_list A} : l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := perm.trans definition finset.nodup_list_setoid [instance] (A : Type) : setoid (nodup_list A) := setoid.mk (@eqv A) (mk_equivalence (@eqv A) (@eqv.refl A) (@eqv.symm A) (@eqv.trans A)) definition finset (A : Type) : Type := quot (finset.nodup_list_setoid A) namespace finset -- give finset notation higher priority than set notation, so that it is tried first protected definition prio : num := num.succ std.priority.default definition to_finset_of_nodup (l : list A) (n : nodup l) : finset A := ⟦to_nodup_list_of_nodup n⟧ definition to_finset [decidable_eq A] (l : list A) : finset A := ⟦to_nodup_list l⟧ lemma to_finset_eq_of_nodup [decidable_eq A] {l : list A} (n : nodup l) : to_finset_of_nodup l n = to_finset l := assert P : to_nodup_list_of_nodup n = to_nodup_list l, from begin rewrite [↑to_nodup_list, ↑to_nodup_list_of_nodup], congruence, rewrite [erase_dup_eq_of_nodup n] end, quot.sound (eq.subst P !setoid.refl) definition has_decidable_eq [instance] [decidable_eq A] : decidable_eq (finset A) := λ s₁ s₂, quot.rec_on_subsingleton₂ s₁ s₂ (λ l₁ l₂, match decidable_perm (elt_of l₁) (elt_of l₂) with | decidable.inl e := decidable.inl (quot.sound e) | decidable.inr n := decidable.inr (λ e : ⟦l₁⟧ = ⟦l₂⟧, absurd (quot.exact e) n) end) definition mem (a : A) (s : finset A) : Prop := quot.lift_on s (λ l, a ∈ elt_of l) (λ l₁ l₂ (e : l₁ ~ l₂), propext (iff.intro (λ ainl₁, mem_perm e ainl₁) (λ ainl₂, mem_perm (perm.symm e) ainl₂))) infix [priority finset.prio] ∈ := mem notation [priority finset.prio] a ∉ b := ¬ mem a b theorem mem_of_mem_list {a : A} {l : nodup_list A} : a ∈ elt_of l → a ∈ ⟦l⟧ := λ ainl, ainl theorem mem_list_of_mem {a : A} {l : nodup_list A} : a ∈ ⟦l⟧ → a ∈ elt_of l := λ ainl, ainl definition decidable_mem [instance] [h : decidable_eq A] : ∀ (a : A) (s : finset A), decidable (a ∈ s) := λ a s, quot.rec_on_subsingleton s (λ l, match list.decidable_mem a (elt_of l) with | decidable.inl p := decidable.inl (mem_of_mem_list p) | decidable.inr n := decidable.inr (λ p, absurd (mem_list_of_mem p) n) end) theorem mem_to_finset [decidable_eq A] {a : A} {l : list A} : a ∈ l → a ∈ to_finset l := λ ainl, mem_erase_dup ainl theorem mem_to_finset_of_nodup {a : A} {l : list A} (n : nodup l) : a ∈ l → a ∈ to_finset_of_nodup l n := λ ainl, ainl /- extensionality -/ theorem ext {s₁ s₂ : finset A} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ e, quot.sound (perm_ext (has_property l₁) (has_property l₂) e)) /- empty -/ definition empty : finset A := to_finset_of_nodup [] nodup_nil notation [priority finset.prio] `∅` := !empty theorem not_mem_empty [simp] (a : A) : a ∉ ∅ := λ aine : a ∈ ∅, aine theorem mem_empty_iff [simp] (x : A) : x ∈ ∅ ↔ false := iff_false_intro !not_mem_empty theorem mem_empty_eq (x : A) : x ∈ ∅ = false := propext !mem_empty_iff theorem eq_empty_of_forall_not_mem {s : finset A} (H : ∀x, ¬ x ∈ s) : s = ∅ := ext (take x, iff_false_intro (H x)) /- universe -/ definition univ [h : fintype A] : finset A := to_finset_of_nodup (@fintype.elems A h) (@fintype.unique A h) theorem mem_univ [fintype A] (x : A) : x ∈ univ := fintype.complete x theorem mem_univ_eq [fintype A] (x : A) : x ∈ univ = true := propext (iff_true_intro !mem_univ) /- card -/ definition card (s : finset A) : nat := quot.lift_on s (λ l, length (elt_of l)) (λ l₁ l₂ p, length_eq_length_of_perm p) theorem card_empty : card (@empty A) = 0 := rfl lemma ne_empty_of_card_eq_succ {s : finset A} {n : nat} : card s = succ n → s ≠ ∅ := by intros; substvars; contradiction /- insert -/ section insert variable [h : decidable_eq A] include h definition insert (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (insert a (elt_of l)) (nodup_insert a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (perm_insert a p)) -- set builder notation notation [priority finset.prio] `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem mem_insert (a : A) (s : finset A) : a ∈ insert a s := quot.induction_on s (λ l : nodup_list A, mem_to_finset_of_nodup _ !list.mem_insert) theorem mem_insert_of_mem {a : A} {s : finset A} (b : A) : a ∈ s → a ∈ insert b s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), mem_to_finset_of_nodup _ (list.mem_insert_of_mem _ ainl)) theorem eq_or_mem_of_mem_insert {x a : A} {s : finset A} : x ∈ insert a s → x = a ∨ x ∈ s := quot.induction_on s (λ l : nodup_list A, λ H, list.eq_or_mem_of_mem_insert H) theorem mem_of_mem_insert_of_ne {x a : A} {s : finset A} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_iff (x a : A) (s : finset A) : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem) theorem mem_insert_eq (x a : A) (s : finset A) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext !mem_insert_iff theorem mem_singleton_iff (x a : A) : x ∈ '{a} ↔ (x = a) := by rewrite [mem_insert_eq, mem_empty_eq, or_false] theorem mem_singleton (a : A) : a ∈ '{a} := mem_insert a ∅ theorem mem_singleton_of_eq {x a : A} (H : x = a) : x ∈ '{a} := by rewrite H; apply mem_insert theorem eq_of_mem_singleton {x a : A} (H : x ∈ '{a}) : x = a := iff.mp !mem_singleton_iff H theorem eq_of_singleton_eq {a b : A} (H : '{a} = '{b}) : a = b := have a ∈ '{b}, by rewrite -H; apply mem_singleton, eq_of_mem_singleton this theorem insert_eq_of_mem {a : A} {s : finset A} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem singleton_ne_empty (a : A) : '{a} ≠ ∅ := begin intro H, apply not_mem_empty a, rewrite -H, apply mem_insert end theorem pair_eq_singleton (a : A) : '{a, a} = '{a} := by rewrite [insert_eq_of_mem !mem_singleton] -- useful in proofs by induction theorem forall_of_forall_insert {P : A → Prop} {a : A} {s : finset A} (H : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := λ x xs, H x (!mem_insert_of_mem xs) theorem insert.comm (x y : A) (s : finset A) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) theorem card_insert_of_mem {a : A} {s : finset A} : a ∈ s → card (insert a s) = card s := quot.induction_on s (λ (l : nodup_list A) (ainl : a ∈ ⟦l⟧), list.length_insert_of_mem ainl) theorem card_insert_of_not_mem {a : A} {s : finset A} : a ∉ s → card (insert a s) = card s + 1 := quot.induction_on s (λ (l : nodup_list A) (nainl : a ∉ ⟦l⟧), list.length_insert_of_not_mem nainl) theorem card_insert_le (a : A) (s : finset A) : card (insert a s) ≤ card s + 1 := if H : a ∈ s then by rewrite [card_insert_of_mem H]; apply le_succ else by rewrite [card_insert_of_not_mem H] protected theorem induction [recursor 6] {P : finset A → Prop} (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀{s : finset A}, a ∉ s → P s → P (insert a s)) : ∀s, P s := take s, quot.induction_on s (take u, subtype.destruct u (take l, list.induction_on l (assume nodup_l, H1) (take a l', assume IH nodup_al', assert aux₁: a ∉ l', from not_mem_of_nodup_cons nodup_al', assert e : list.insert a l' = a :: l', from insert_eq_of_not_mem aux₁, assert nodup l', from nodup_of_nodup_cons nodup_al', assert P (quot.mk (subtype.tag l' this)), from IH this, assert P (insert a (quot.mk (subtype.tag l' _))), from H2 aux₁ this, begin revert nodup_al', rewrite [-e], intros, apply this end))) protected theorem induction_on {P : finset A → Prop} (s : finset A) (H1 : P empty) (H2 : ∀ ⦃a : A⦄, ∀ {s : finset A}, a ∉ s → P s → P (insert a s)) : P s := finset.induction H1 H2 s theorem exists_mem_of_ne_empty {s : finset A} : s ≠ ∅ → ∃ a : A, a ∈ s := begin induction s with a s nin ih, {intro h, exact absurd rfl h}, {intro h, existsi a, apply mem_insert} end theorem eq_empty_of_card_eq_zero {s : finset A} (H : card s = 0) : s = ∅ := begin induction s with a s' H1 IH, { reflexivity }, { rewrite (card_insert_of_not_mem H1) at H, apply nat.no_confusion H} end end insert /- erase -/ section erase variable [h : decidable_eq A] include h definition erase (a : A) (s : finset A) : finset A := quot.lift_on s (λ l, to_finset_of_nodup (erase a (elt_of l)) (nodup_erase_of_nodup a (has_property l))) (λ (l₁ l₂ : nodup_list A) (p : l₁ ~ l₂), quot.sound (erase_perm_erase_of_perm a p)) theorem not_mem_erase (a : A) (s : finset A) : a ∉ erase a s := quot.induction_on s (λ l, list.mem_erase_of_nodup _ (has_property l)) theorem card_erase_of_mem {a : A} {s : finset A} : a ∈ s → card (erase a s) = pred (card s) := quot.induction_on s (λ l ainl, list.length_erase_of_mem ainl) theorem card_erase_of_not_mem {a : A} {s : finset A} : a ∉ s → card (erase a s) = card s := quot.induction_on s (λ l nainl, list.length_erase_of_not_mem nainl) theorem erase_empty (a : A) : erase a ∅ = ∅ := rfl theorem ne_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ≠ a := by intro h beqa; subst b; exact absurd h !not_mem_erase theorem mem_of_mem_erase {a b : A} {s : finset A} : b ∈ erase a s → b ∈ s := quot.induction_on s (λ l bin, mem_of_mem_erase bin) theorem mem_erase_of_ne_of_mem {a b : A} {s : finset A} : a ≠ b → a ∈ s → a ∈ erase b s := quot.induction_on s (λ l n ain, list.mem_erase_of_ne_of_mem n ain) theorem mem_erase_iff (a b : A) (s : finset A) : a ∈ erase b s ↔ a ∈ s ∧ a ≠ b := iff.intro (assume H, and.intro (mem_of_mem_erase H) (ne_of_mem_erase H)) (assume H, mem_erase_of_ne_of_mem (and.right H) (and.left H)) theorem mem_erase_eq (a b : A) (s : finset A) : a ∈ erase b s = (a ∈ s ∧ a ≠ b) := propext !mem_erase_iff open decidable theorem erase_insert {a : A} {s : finset A} : a ∉ s → erase a (insert a s) = s := λ anins, finset.ext (λ b, by_cases (λ beqa : b = a, iff.intro (λ bin, by subst b; exact absurd bin !not_mem_erase) (λ bin, by subst b; contradiction)) (λ bnea : b ≠ a, iff.intro (λ bin, assert b ∈ insert a s, from mem_of_mem_erase bin, mem_of_mem_insert_of_ne this bnea) (λ bin, have b ∈ insert a s, from mem_insert_of_mem _ bin, mem_erase_of_ne_of_mem bnea this))) theorem insert_erase {a : A} {s : finset A} : a ∈ s → insert a (erase a s) = s := λ ains, finset.ext (λ b, by_cases (suppose b = a, iff.intro (λ bin, by subst b; assumption) (λ bin, by subst b; apply mem_insert)) (suppose b ≠ a, iff.intro (λ bin, mem_of_mem_erase (mem_of_mem_insert_of_ne bin `b ≠ a`)) (λ bin, mem_insert_of_mem _ (mem_erase_of_ne_of_mem `b ≠ a` bin)))) end erase /- union -/ section union variable [h : decidable_eq A] include h definition union (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.union (elt_of l₁) (elt_of l₂)) (nodup_union_of_nodup_of_nodup (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_union p₁ p₂)) infix [priority finset.prio] ∪ := union theorem mem_union_left {a : A} {s₁ : finset A} (s₂ : finset A) : a ∈ s₁ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁, list.mem_union_left _ ainl₁) theorem mem_union_l {a : A} {s₁ : finset A} {s₂ : finset A} : a ∈ s₁ → a ∈ s₁ ∪ s₂ := mem_union_left s₂ theorem mem_union_right {a : A} {s₂ : finset A} (s₁ : finset A) : a ∈ s₂ → a ∈ s₁ ∪ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₂, list.mem_union_right _ ainl₂) theorem mem_union_r {a : A} {s₂ : finset A} {s₁ : finset A} : a ∈ s₂ → a ∈ s₁ ∪ s₂ := mem_union_right s₁ theorem mem_or_mem_of_mem_union {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∪ s₂ → a ∈ s₁ ∨ a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_or_mem_of_mem_union ainl₁l₂) theorem mem_union_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := iff.intro (λ h, mem_or_mem_of_mem_union h) (λ d, or.elim d (λ i, mem_union_left _ i) (λ i, mem_union_right _ i)) theorem mem_union_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∪ s₂) = (a ∈ s₁ ∨ a ∈ s₂) := propext !mem_union_iff theorem union_comm (s₁ s₂ : finset A) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext (λ a, by rewrite [*mem_union_eq]; exact or.comm) theorem union_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext (λ a, by rewrite [*mem_union_eq]; exact or.assoc) theorem union_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union_comm union_assoc s₁ s₂ s₃ theorem union_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union_comm union_assoc s₁ s₂ s₃ theorem union_self (s : finset A) : s ∪ s = s := ext (λ a, iff.intro (λ ain, or.elim (mem_or_mem_of_mem_union ain) (λ i, i) (λ i, i)) (λ i, mem_union_left _ i)) theorem union_empty (s : finset A) : s ∪ ∅ = s := ext (λ a, iff.intro (suppose a ∈ s ∪ ∅, or.elim (mem_or_mem_of_mem_union this) (λ i, i) (λ i, absurd i !not_mem_empty)) (suppose a ∈ s, mem_union_left _ this)) theorem empty_union (s : finset A) : ∅ ∪ s = s := calc ∅ ∪ s = s ∪ ∅ : union_comm ... = s : union_empty theorem insert_eq (a : A) (s : finset A) : insert a s = '{a} ∪ s := ext (take x, by rewrite [mem_insert_iff, mem_union_iff, mem_singleton_iff]) theorem insert_union (a : A) (s t : finset A) : insert a (s ∪ t) = insert a s ∪ t := by rewrite [insert_eq, insert_eq a s, union_assoc] end union /- inter -/ section inter variable [h : decidable_eq A] include h definition inter (s₁ s₂ : finset A) : finset A := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.inter (elt_of l₁) (elt_of l₂)) (nodup_inter_of_nodup _ (has_property l₁))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_inter p₁ p₂)) infix [priority finset.prio] ∩ := inter theorem mem_of_mem_inter_left {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_left ainl₁l₂) theorem mem_of_mem_inter_right {a : A} {s₁ s₂ : finset A} : a ∈ s₁ ∩ s₂ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁l₂, list.mem_of_mem_inter_right ainl₁l₂) theorem mem_inter {a : A} {s₁ s₂ : finset A} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ ainl₁ ainl₂, list.mem_inter_of_mem_of_mem ainl₁ ainl₂) theorem mem_inter_iff (a : A) (s₁ s₂ : finset A) : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := iff.intro (λ h, and.intro (mem_of_mem_inter_left h) (mem_of_mem_inter_right h)) (λ h, mem_inter (and.elim_left h) (and.elim_right h)) theorem mem_inter_eq (a : A) (s₁ s₂ : finset A) : (a ∈ s₁ ∩ s₂) = (a ∈ s₁ ∧ a ∈ s₂) := propext !mem_inter_iff theorem inter_comm (s₁ s₂ : finset A) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext (λ a, by rewrite [*mem_inter_eq]; exact and.comm) theorem inter_assoc (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext (λ a, by rewrite [*mem_inter_eq]; exact and.assoc) theorem inter_left_comm (s₁ s₂ s₃ : finset A) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_right_comm (s₁ s₂ s₃ : finset A) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter_comm inter_assoc s₁ s₂ s₃ theorem inter_self (s : finset A) : s ∩ s = s := ext (λ a, iff.intro (λ h, mem_of_mem_inter_right h) (λ h, mem_inter h h)) theorem inter_empty (s : finset A) : s ∩ ∅ = ∅ := ext (λ a, iff.intro (suppose a ∈ s ∩ ∅, absurd (mem_of_mem_inter_right this) !not_mem_empty) (suppose a ∈ ∅, absurd this !not_mem_empty)) theorem empty_inter (s : finset A) : ∅ ∩ s = ∅ := calc ∅ ∩ s = s ∩ ∅ : inter_comm ... = ∅ : inter_empty theorem singleton_inter_of_mem {a : A} {s : finset A} (H : a ∈ s) : '{a} ∩ s = '{a} := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff], exact iff.intro (suppose x = a ∧ x ∈ s, and.left this) (suppose x = a, and.intro this (eq.subst (eq.symm this) H)) end) theorem singleton_inter_of_not_mem {a : A} {s : finset A} (H : a ∉ s) : '{a} ∩ s = ∅ := ext (take x, begin rewrite [mem_inter_eq, !mem_singleton_iff, mem_empty_eq], exact iff.intro (suppose x = a ∧ x ∈ s, H (eq.subst (and.left this) (and.right this))) (false.elim) end) end inter /- distributivity laws -/ section inter variable [h : decidable_eq A] include h theorem inter_distrib_left (s t u : finset A) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.left_distrib) theorem inter_distrib_right (s t u : finset A) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, by rewrite [mem_inter_eq, *mem_union_eq, *mem_inter_eq]; apply and.right_distrib) theorem union_distrib_left (s t u : finset A) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.left_distrib) theorem union_distrib_right (s t u : finset A) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, by rewrite [mem_union_eq, *mem_inter_eq, *mem_union_eq]; apply or.right_distrib) end inter /- disjoint -/ -- Mainly for internal use; library will use s₁ ∩ s₂ = ∅. Note that it does not require decidable equality. definition disjoint (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, disjoint (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ d₁ a (ainw₁ : a ∈ elt_of w₁), have a ∈ elt_of v₁, from mem_perm (perm.symm p₁) ainw₁, have a ∉ elt_of v₂, from disjoint_left d₁ this, not_mem_perm p₂ this) (λ d₂ a (ainv₁ : a ∈ elt_of v₁), have a ∈ elt_of w₁, from mem_perm p₁ ainv₁, have a ∉ elt_of w₂, from disjoint_left d₂ this, not_mem_perm (perm.symm p₂) this))) theorem disjoint.elim {s₁ s₂ : finset A} {x : A} : disjoint s₁ s₂ → x ∈ s₁ → x ∈ s₂ → false := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H H1 H2, H x H1 H2) theorem disjoint.intro {s₁ s₂ : finset A} : (∀{x : A}, x ∈ s₁ → x ∈ s₂ → false) → disjoint s₁ s₂ := quot.induction_on₂ s₁ s₂ (take u₁ u₂, assume H, H) theorem inter_eq_empty_of_disjoint [h : decidable_eq A] {s₁ s₂ : finset A} (H : disjoint s₁ s₂) : s₁ ∩ s₂ = ∅ := ext (take x, iff_false_intro (assume H1, disjoint.elim H (mem_of_mem_inter_left H1) (mem_of_mem_inter_right H1))) theorem disjoint_of_inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : s₁ ∩ s₂ = ∅) : disjoint s₁ s₂ := disjoint.intro (take x H1 H2, have x ∈ s₁ ∩ s₂, from mem_inter H1 H2, !not_mem_empty (eq.subst H this)) theorem disjoint.comm {s₁ s₂ : finset A} : disjoint s₁ s₂ → disjoint s₂ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ d, list.disjoint.comm d) theorem inter_eq_empty [h : decidable_eq A] {s₁ s₂ : finset A} (H : ∀x : A, x ∈ s₁ → x ∈ s₂ → false) : s₁ ∩ s₂ = ∅ := inter_eq_empty_of_disjoint (disjoint.intro H) /- subset -/ definition subset (s₁ s₂ : finset A) : Prop := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, sublist (elt_of l₁) (elt_of l₂)) (λ v₁ v₂ w₁ w₂ p₁ p₂, propext (iff.intro (λ s₁ a i, mem_perm p₂ (s₁ a (mem_perm (perm.symm p₁) i))) (λ s₂ a i, mem_perm (perm.symm p₂) (s₂ a (mem_perm p₁ i))))) infix [priority finset.prio] ⊆ := subset theorem empty_subset (s : finset A) : ∅ ⊆ s := quot.induction_on s (λ l, list.nil_sub (elt_of l)) theorem subset_univ [h : fintype A] (s : finset A) : s ⊆ univ := quot.induction_on s (λ l a i, fintype.complete a) theorem subset.refl (s : finset A) : s ⊆ s := quot.induction_on s (λ l, list.sub.refl (elt_of l)) theorem subset.trans {s₁ s₂ s₃ : finset A} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := quot.induction_on₃ s₁ s₂ s₃ (λ l₁ l₂ l₃ h₁ h₂, list.sub.trans h₁ h₂) theorem mem_of_subset_of_mem {s₁ s₂ : finset A} {a : A} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h₁ h₂, h₁ a h₂) theorem subset.antisymm {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext (take x, iff.intro (assume H, mem_of_subset_of_mem H₁ H) (assume H, mem_of_subset_of_mem H₂ H)) -- alternative name theorem eq_of_subset_of_subset {s₁ s₂ : finset A} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := subset.antisymm H₁ H₂ theorem subset_of_forall {s₁ s₂ : finset A} : (∀x, x ∈ s₁ → x ∈ s₂) → s₁ ⊆ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ H, H) theorem subset_insert [h : decidable_eq A] (s : finset A) (a : A) : s ⊆ insert a s := subset_of_forall (take x, suppose x ∈ s, mem_insert_of_mem _ this) theorem eq_empty_of_subset_empty {x : finset A} (H : x ⊆ ∅) : x = ∅ := subset.antisymm H (empty_subset x) theorem subset_empty_iff (x : finset A) : x ⊆ ∅ ↔ x = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) section variable [decA : decidable_eq A] include decA theorem erase_subset_erase (a : A) {s t : finset A} (H : s ⊆ t) : erase a s ⊆ erase a t := begin apply subset_of_forall, intro x, rewrite *mem_erase_eq, intro H', show x ∈ t ∧ x ≠ a, from and.intro (mem_of_subset_of_mem H (and.left H')) (and.right H') end theorem erase_subset (a : A) (s : finset A) : erase a s ⊆ s := begin apply subset_of_forall, intro x, rewrite mem_erase_eq, intro H, apply and.left H end theorem erase_eq_of_not_mem {a : A} {s : finset A} (anins : a ∉ s) : erase a s = s := eq_of_subset_of_subset !erase_subset (subset_of_forall (take x, assume xs : x ∈ s, have x ≠ a, from assume H', anins (eq.subst H' xs), mem_erase_of_ne_of_mem this xs)) theorem erase_insert_subset (a : A) (s : finset A) : erase a (insert a s) ⊆ s := decidable.by_cases (assume ains : a ∈ s, by rewrite [insert_eq_of_mem ains]; apply erase_subset) (assume nains : a ∉ s, by rewrite [!erase_insert nains]; apply subset.refl) theorem erase_subset_of_subset_insert {a : A} {s t : finset A} (H : s ⊆ insert a t) : erase a s ⊆ t := subset.trans (!erase_subset_erase H) !erase_insert_subset theorem insert_erase_subset (a : A) (s : finset A) : s ⊆ insert a (erase a s) := decidable.by_cases (assume ains : a ∈ s, by rewrite [!insert_erase ains]; apply subset.refl) (assume nains : a ∉ s, by rewrite[erase_eq_of_not_mem nains]; apply subset_insert) theorem insert_subset_insert (a : A) {s t : finset A} (H : s ⊆ t) : insert a s ⊆ insert a t := begin apply subset_of_forall, intro x, rewrite *mem_insert_eq, intro H', cases H' with [xeqa, xins], exact (or.inl xeqa), exact (or.inr (mem_of_subset_of_mem H xins)) end theorem subset_insert_of_erase_subset {s t : finset A} {a : A} (H : erase a s ⊆ t) : s ⊆ insert a t := subset.trans (insert_erase_subset a s) (!insert_subset_insert H) theorem subset_insert_iff (s t : finset A) (a : A) : s ⊆ insert a t ↔ erase a s ⊆ t := iff.intro !erase_subset_of_subset_insert !subset_insert_of_erase_subset end /- upto -/ section upto definition upto (n : nat) : finset nat := to_finset_of_nodup (list.upto n) (nodup_upto n) theorem card_upto : ∀ n, card (upto n) = n := list.length_upto theorem lt_of_mem_upto {n a : nat} : a ∈ upto n → a < n := list.lt_of_mem_upto theorem mem_upto_succ_of_mem_upto {n a : nat} : a ∈ upto n → a ∈ upto (succ n) := list.mem_upto_succ_of_mem_upto theorem mem_upto_of_lt {n a : nat} : a < n → a ∈ upto n := list.mem_upto_of_lt theorem mem_upto_iff (a n : nat) : a ∈ upto n ↔ a < n := iff.intro lt_of_mem_upto mem_upto_of_lt theorem mem_upto_eq (a n : nat) : a ∈ upto n = (a < n) := propext !mem_upto_iff end upto theorem upto_zero : upto 0 = ∅ := rfl theorem upto_succ (n : ℕ) : upto (succ n) = upto n ∪ '{n} := begin apply ext, intro x, rewrite [mem_union_iff, *mem_upto_iff, mem_singleton_iff, lt_succ_iff_le, nat.le_iff_lt_or_eq], end /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) ↔ false := iff.intro (assume H, obtain x (H1 : x ∈ ∅ ∧ P x), from H, !not_mem_empty (and.left H1)) (assume H, false.elim H) theorem exists_mem_empty_eq {A : Type} (P : A → Prop) : (∃ x, x ∈ ∅ ∧ P x) = false := propext !exists_mem_empty_iff theorem exists_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) ↔ P a ∨ (∃ x, x ∈ s ∧ P x) := iff.intro (assume H, obtain x [H1 H2], from H, or.elim (eq_or_mem_of_mem_insert H1) (suppose x = a, or.inl (eq.subst this H2)) (suppose x ∈ s, or.inr (exists.intro x (and.intro this H2)))) (assume H, or.elim H (suppose P a, exists.intro a (and.intro !mem_insert this)) (suppose ∃ x, x ∈ s ∧ P x, obtain x [H2 H3], from this, exists.intro x (and.intro (!mem_insert_of_mem H2) H3))) theorem exists_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∃ x, x ∈ insert a s ∧ P x) = (P a ∨ (∃ x, x ∈ s ∧ P x)) := propext !exists_mem_insert_iff theorem forall_mem_empty_iff {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) ↔ true := iff.intro (assume H, trivial) (assume H, take x, assume H', absurd H' !not_mem_empty) theorem forall_mem_empty_eq {A : Type} (P : A → Prop) : (∀ x, x ∈ ∅ → P x) = true := propext !forall_mem_empty_iff theorem forall_mem_insert_iff {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) ↔ P a ∧ (∀ x, x ∈ s → P x) := iff.intro (assume H, and.intro (H _ !mem_insert) (take x, assume H', H _ (!mem_insert_of_mem H'))) (assume H, take x, assume H' : x ∈ insert a s, or.elim (eq_or_mem_of_mem_insert H') (suppose x = a, eq.subst (eq.symm this) (and.left H)) (suppose x ∈ s, and.right H _ this)) theorem forall_mem_insert_eq {A : Type} [d : decidable_eq A] (a : A) (s : finset A) (P : A → Prop) : (∀ x, x ∈ insert a s → P x) = (P a ∧ (∀ x, x ∈ s → P x)) := propext !forall_mem_insert_iff end finset
808b2a949a64355b6616f25123221704530b3bb9
d406927ab5617694ec9ea7001f101b7c9e3d9702
/archive/examples/prop_encodable.lean
4890ca2837d89d29ec30b8428b548130986c1d02
[ "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
2,983
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.W.basic /-! # W types The file `data/W.lean` shows that if `α` is an an encodable fintype and for every `a : α`, `β a` is encodable, then `W β` is encodable. As an example of how this can be used, we show that the type of propositional formulas with variables labeled from an encodable type is encodable. The strategy is to define a type of labels corresponding to the constructors. From the definition (using `sum`, `unit`, and an encodable type), Lean can infer that it is encodable. We then define a map from propositional formulas to the corresponding `Wfin` type, and show that map has a left inverse. We mark the auxiliary constructions `private`, since their only purpose is to show encodability. -/ /-- Propositional formulas with labels from `α`. -/ inductive prop_form (α : Type*) | var : α → prop_form | not : prop_form → prop_form | and : prop_form → prop_form → prop_form | or : prop_form → prop_form → prop_form /-! The next three functions make it easier to construct functions from a small `fin`. -/ section variable {α : Type*} /-- the trivial function out of `fin 0`. -/ def mk_fn0 : fin 0 → α | ⟨_, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 1` -/ def mk_fn1 (t : α) : fin 1 → α | ⟨0, _⟩ := t | ⟨n+1, h⟩ := absurd h dec_trivial /-- defines a function out of `fin 2` -/ def mk_fn2 (s t : α) : fin 2 → α | ⟨0, _⟩ := s | ⟨1, _⟩ := t | ⟨n+2, h⟩ := absurd h dec_trivial attribute [simp] mk_fn0 mk_fn1 mk_fn2 end namespace prop_form private def constructors (α : Type*) := α ⊕ unit ⊕ unit ⊕ unit local notation `cvar ` a := sum.inl a local notation `cnot` := sum.inr (sum.inl unit.star) local notation `cand` := sum.inr (sum.inr (sum.inr unit.star)) local notation `cor` := sum.inr (sum.inr (sum.inl unit.star)) @[simp] private def arity (α : Type*) : constructors α → nat | (cvar a) := 0 | cnot := 1 | cand := 2 | cor := 2 variable {α : Type*} private def f : prop_form α → W_type (λ i, fin (arity α i)) | (var a) := ⟨cvar a, mk_fn0⟩ | (not p) := ⟨cnot, mk_fn1 (f p)⟩ | (and p q) := ⟨cand, mk_fn2 (f p) (f q)⟩ | (or p q) := ⟨cor, mk_fn2 (f p) (f q)⟩ private def finv : W_type (λ i, fin (arity α i)) → prop_form α | ⟨cvar a, fn⟩ := var a | ⟨cnot, fn⟩ := not (finv (fn ⟨0, dec_trivial⟩)) | ⟨cand, fn⟩ := and (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) | ⟨cor, fn⟩ := or (finv (fn ⟨0, dec_trivial⟩)) (finv (fn ⟨1, dec_trivial⟩)) instance [encodable α] : encodable (prop_form α) := begin haveI : encodable (constructors α), { unfold constructors, apply_instance }, exact encodable.of_left_inverse f finv (by { intro p, induction p; simp [f, finv, *] }) end end prop_form
9bb6adb8e3ab927230daff6dcd7558baa531473f
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/fully_faithful.lean
c54f0195653dd899ab9e36be66ad1b0ab2ba8c68
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
5,671
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import logic.function category_theory.isomorphism universes v₁ v₂ v₃ u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory variables {C : Type u₁} [𝒞 : category.{v₁} C] {D : Type u₂} [𝒟 : category.{v₂} D] include 𝒞 𝒟 /-- A functor `F : C ⥤ D` is full if for each `X Y : C`, `F.map` is surjective. In fact, we use a constructive definition, so the `full F` typeclass contains data, specifying a particular preimage of each `f : F.obj X ⟶ F.obj Y`. -/ class full (F : C ⥤ D) := (preimage : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), X ⟶ Y) (witness' : ∀ {X Y : C} (f : (F.obj X) ⟶ (F.obj Y)), F.map (preimage f) = f . obviously) restate_axiom full.witness' attribute [simp] full.witness /-- A functor `F : C ⥤ D` is faithful if for each `X Y : C`, `F.map` is injective.-/ class faithful (F : C ⥤ D) : Prop := (injectivity' [] : ∀ {X Y : C}, function.injective (@functor.map _ _ _ _ F X Y) . obviously) restate_axiom faithful.injectivity' namespace functor lemma injectivity (F : C ⥤ D) [faithful F] {X Y : C} : function.injective $ @functor.map _ _ _ _ F X Y := faithful.injectivity F /-- The specified preimage of a morphism under a full functor. -/ def preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : X ⟶ Y := full.preimage.{v₁ v₂} f @[simp] lemma image_preimage (F : C ⥤ D) [full F] {X Y : C} (f : F.obj X ⟶ F.obj Y) : F.map (preimage F f) = f := by unfold preimage; obviously end functor variables {F : C ⥤ D} [full F] [faithful F] {X Y Z : C} @[simp] lemma preimage_id : F.preimage (𝟙 (F.obj X)) = 𝟙 X := F.injectivity (by simp) @[simp] lemma preimage_comp (f : F.obj X ⟶ F.obj Y) (g : F.obj Y ⟶ F.obj Z) : F.preimage (f ≫ g) = F.preimage f ≫ F.preimage g := F.injectivity (by simp) @[simp] lemma preimage_map (f : X ⟶ Y) : F.preimage (F.map f) = f := F.injectivity (by simp) /-- If `F : C ⥤ D` is fully faithful, every isomorphism `F.obj X ≅ F.obj Y` has a preimage. -/ def preimage_iso (f : (F.obj X) ≅ (F.obj Y)) : X ≅ Y := { hom := F.preimage f.hom, inv := F.preimage f.inv, hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp), } @[simp] lemma preimage_iso_hom (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).hom = F.preimage f.hom := rfl @[simp] lemma preimage_iso_inv (f : (F.obj X) ≅ (F.obj Y)) : (preimage_iso f).inv = F.preimage (f.inv) := rfl @[simp] lemma preimage_iso_map_iso (f : X ≅ Y) : preimage_iso (F.map_iso f) = f := by tidy variables (F) def is_iso_of_fully_faithful (f : X ⟶ Y) [is_iso (F.map f)] : is_iso f := { inv := F.preimage (inv (F.map f)), hom_inv_id' := F.injectivity (by simp), inv_hom_id' := F.injectivity (by simp) } end category_theory namespace category_theory variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 instance full.id : full (𝟭 C) := { preimage := λ _ _ f, f } instance faithful.id : faithful (𝟭 C) := by obviously variables {D : Type u₂} [𝒟 : category.{v₂} D] {E : Type u₃} [ℰ : category.{v₃} E] include 𝒟 ℰ variables (F : C ⥤ D) (G : D ⥤ E) instance faithful.comp [faithful F] [faithful G] : faithful (F ⋙ G) := { injectivity' := λ _ _ _ _ p, F.injectivity (G.injectivity p) } lemma faithful.of_comp [faithful $ F ⋙ G] : faithful F := { injectivity' := λ X Y, (F ⋙ G).injectivity.of_comp } variables {F G} lemma faithful.of_comp_eq {H : C ⥤ E} [ℋ : faithful H] (h : F ⋙ G = H) : faithful F := @faithful.of_comp _ _ _ _ _ _ F G (h.symm ▸ ℋ) alias faithful.of_comp_eq ← eq.faithful_of_comp variables (F G) /-- “Divide” a functor by a faithful functor. -/ protected def faithful.div (F : C ⥤ E) (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : C ⥤ D := { obj := obj, map := @map, map_id' := begin assume X, apply G.injectivity, apply eq_of_heq, transitivity F.map (𝟙 X), from h_map, rw [F.map_id, G.map_id, h_obj X] end, map_comp' := begin assume X Y Z f g, apply G.injectivity, apply eq_of_heq, transitivity F.map (f ≫ g), from h_map, rw [F.map_comp, G.map_comp], congr' 1; try { exact (h_obj _).symm }; exact h_map.symm end } lemma faithful.div_comp (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : (faithful.div F G obj @h_obj @map @h_map) ⋙ G = F := begin tactic.unfreeze_local_instances, cases F with F_obj _ _ _; cases G with G_obj _ _ _, unfold faithful.div functor.comp, unfold_projs at h_obj, have: F_obj = G_obj ∘ obj := (funext h_obj).symm, subst this, congr, funext, exact eq_of_heq h_map end lemma faithful.div_faithful (F : C ⥤ E) [faithful F] (G : D ⥤ E) [faithful G] (obj : C → D) (h_obj : ∀ X, G.obj (obj X) = F.obj X) (map : Π {X Y}, (X ⟶ Y) → (obj X ⟶ obj Y)) (h_map : ∀ {X Y} {f : X ⟶ Y}, G.map (map f) == F.map f) : faithful (faithful.div F G obj @h_obj @map @h_map) := (faithful.div_comp F G _ h_obj _ @h_map).faithful_of_comp instance full.comp [full F] [full G] : full (F ⋙ G) := { preimage := λ _ _ f, F.preimage (G.preimage f) } end category_theory
7bde2487fef74e773935cdf76b9a63056ef001e6
618003631150032a5676f229d13a079ac875ff77
/src/data/equiv/basic.lean
63d07be6b0895f9d2078da0e1b7185c196f0507a
[ "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
57,517
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import data.set.function import data.option.basic import algebra.group.basic open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv /-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/ def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α := ⟨f, f, h.left_inverse, h.right_inverse⟩ namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl /-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. We can't use `function.injective` here but mimic its signature by using `⦃e₁ e₂⦄`. -/ theorem coe_fn_injective : ∀ ⦃e₁ e₂ : equiv α β⦄, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂), by simp * @[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := coe_fn_injective (funext H) @[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simp] lemma to_fun_as_coe (e : α ≃ β) (a : α) : e.to_fun a = e a := rfl @[simp] lemma inv_fun_as_coe (e : α ≃ β) (b : β) : e.inv_fun b = e.symm b := rfl protected theorem injective : ∀ f : α ≃ β, injective f | ⟨f, g, h₁, h₂⟩ := h₁.injective protected theorem surjective : ∀ f : α ≃ β, surjective f | ⟨f, g, h₁, h₂⟩ := h₂.surjective protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α := e.injective.comap_subsingleton protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.injective.eq_iff lemma nonempty_iff_nonempty : α ≃ β → (nonempty α ↔ nonempty β) | ⟨f, g, _, _⟩ := nonempty.congr f g protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq (f : α ≃ β) (x y : α) : f x = f y ↔ x = y := f.injective.eq_iff theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) (x : α) (y : β) : f x = y ↔ x = f.symm y := begin conv_lhs { rw ←apply_symm_apply f y, }, rw apply_eq_iff_eq, end @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by { rw [← set.image_comp], simp } protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply symm_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.symm_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_symm_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ /-- equivalence of propositions is the same as iff -/ def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := { to_fun := h.mp, inv_fun := h.mpr, left_inv := λ x, rfl, right_inv := λ y, rfl } @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂.to_fun ∘ f ∘ e₁.inv_fun, inv_fun := λ f, e₂.inv_fun ∘ f ∘ e₁.to_fun, left_inv := λ f, funext $ λ x, by simp, right_inv := λ f, funext $ λ x, by simp } @[simp] lemma arrow_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (f : α₁ → β₁) (x : α₂) : arrow_congr e₁ e₂ f x = (e₂ $ f $ e₁.symm x) := rfl lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl /-- A version of `equiv.arrow_congr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ @[congr] def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := equiv.arrow_congr hα hβ @[simp] lemma arrow_congr'_apply {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (f : α₁ → β₁) (x : α₂) : arrow_congr' e₁ e₂ f x = (e₂ $ f $ e₁.symm x) := rfl @[simp] lemma arrow_congr'_refl {α β : Type*} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') := rfl @[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_apply (e : α ≃ β) (f : α → α) (x : β) : e.conj f x = (e $ f $ e.symm x) := rfl @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by { funext x, cases x, refl }, λ u, rfl⟩ def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/ @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem coe_prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : ⇑(prod_congr e₁ e₂) = prod.map e₁ e₂ := rfl @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/ def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] lemma coe_prod_comm (α β) : ⇑(prod_comm α β)= prod.swap := rfl @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl @[simp] theorem prod_assoc_sym_apply {α β γ : Sort*} (p : α × (β × γ)) : (prod_assoc α β γ).symm p = ⟨⟨p.1, p.2.1⟩, p.2.2⟩ := rfl section /-- `punit` is a right identity for type product up to an equivalence. -/ def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl /-- `punit` is a left identity for type product up to an equivalence. -/ def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Type*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/ def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ @[simp] theorem sum_congr_apply {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁ ⊕ β₁) : sum_congr e₁ e₂ a = a.map e₁ e₂ := rfl @[simp] lemma sum_congr_symm {α β γ δ : Type u} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ /-- Sum of types is commutative up to an equivalence. -/ def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_apply (α β) (a) : sum_comm α β a = a.swap := rfl @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl /-- Sum with `empty` is equivalent to the original type. -/ def sum_empty (α : Type*) : α ⊕ empty ≃ α := ⟨sum.elim id (empty.rec _), inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α} (a) : sum_empty α (sum.inl a) = a := rfl def empty_sum (α : Sort*) : empty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] lemma empty_sum_apply_inr {α} (a) : empty_sum α (sum.inr a) = a := rfl /-- Sum with `pempty` is equivalent to the original type. -/ def sum_pempty (α : Type*) : α ⊕ pempty ≃ α := ⟨sum.elim id (pempty.rec _), inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] lemma sum_pempty_apply_inl {α} (a) : sum_pempty α (sum.inl a) = a := rfl def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] lemma pempty_sum_apply_inr {α} (a) : pempty_sum α (sum.inr a) = a := rfl def option_equiv_sum_punit (α : Sort*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr () := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } def sum_equiv_sigma_bool (α β : Sort*) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ def sigma_preimage_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, x.2.1, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ @[simp] lemma sigma_preimage_equiv_apply {α β : Type*} (f : α → β) (x : Σ y : β, {x // f x = y}) : (sigma_preimage_equiv f) x = x.2.1 := rfl @[simp] lemma sigma_preimage_equiv_symm_apply_fst {α β : Type*} (f : α → β) (a : α) : ((sigma_preimage_equiv f).symm a).1 = f a := rfl @[simp] lemma sigma_preimage_equiv_symm_apply_snd_fst {α β : Type*} (f : α → β) (a : α) : ((sigma_preimage_equiv f).symm a).2.1 = a := rfl end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h], refl } } @[simp] lemma subtype_preimage_apply (x : {x : α → β // x ∘ coe = x₀}) : subtype_preimage p x₀ x = λ a, (x : α → β) a := rfl @[simp] lemma subtype_preimage_symm_apply_coe (x : {a // ¬ p a} → β) : ((subtype_preimage p x₀).symm x : α → β) = λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩ := rfl lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section fun_unique variables (α β) [unique α] /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ def fun_unique : (α → β) ≃ β := { to_fun := λ f, f (default α), inv_fun := λ b a, b, left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _, right_inv := λ b, rfl } variables {α β} @[simp] lemma fun_unique_apply (f : α → β) : fun_unique α β f = f (default α) := rfl @[simp] lemma fun_unique_symm_apply (b : β) (a : α) : (fun_unique α β).symm b a = b := rfl end fun_unique section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : sigma β, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := λ f x y, f ⟨x,y⟩, inv_fun := λ f x, f x.1 x.2, left_inv := λ f, funext $ λ ⟨x,y⟩, rfl, right_inv := λ f, funext $ λ x, funext $ λ y, rfl } end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ /-- Transporting a sigma type through an equivalence of the base -/ def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) : (Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) := (sigma_congr_left f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibres -/ def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : sigma β₁ ≃ sigma β₂ := (sigma_congr_right F).trans (sigma_congr_left f) /-- `sigma` type with a constant fiber is equivalent to the product. -/ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ α × β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ /-- Functions `α → β → γ` are equivalent to functions on `α × β`. -/ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨uncurry, curry, curry_uncurry, uncurry_curry⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { funext s, cases s; refl }, λ p, by { cases p, refl }⟩ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ α × (unit ⊕ unit) : prod_comm _ _ ... ≃ (α × unit) ⊕ (α × unit) : prod_sum_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [l.comp_eq_id, r.comp_eq_id] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α := e.symm.surjective.unique def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype def subtype_congr {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x.1, (h _).1 x.2⟩, λ y, ⟨e.symm y.1, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.eq' $ by simp, λ ⟨y, h⟩, subtype.eq' $ by simp⟩ def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : subtype p ≃ subtype q := subtype_congr (equiv.refl _) e @[simp] lemma subtype_congr_right_mk {p q : α → Prop} (e : ∀x, p x ↔ q x) {x : α} (h : p x) : subtype_congr_right e ⟨x, h⟩ = ⟨x, (e x).1 h⟩ := rfl def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := subtype_congr e $ by simp def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl α) (assume a, h ▸ iff.rfl) def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr_prop h def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_congr_right $ λ x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_congr_right $ assume x, ⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩ /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_preimage_equiv f def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_congr_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.eq' rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ @[simp] lemma univ_apply {α : Type u} (x : @univ α) : equiv.set.univ α x = x := rfl @[simp] lemma univ_symm_apply {α : Type u} (x : α) : (equiv.set.univ α).symm x = ⟨x, trivial⟩ := rfl protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x.1 then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x.1, or.inl x.2⟩ | (sum.inr x) := ⟨x.1, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg (show ↑a ∉ s, by finish [set.ext_iff]) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x.1, h ▸ x.2⟩, inv_fun := λ x, ⟨x.1, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } @[simp] lemma of_eq_apply {α : Type u} {s t : set α} (h : s = t) (a : s) : equiv.set.of_eq h a = ⟨a, h ▸ a.2⟩ := rfl @[simp] lemma of_eq_symm_apply {α : Type u} {s t : set α} (h : s = t) (a : t) : (equiv.set.of_eq h).symm a = ⟨a, h.symm ▸ a.2⟩ := rfl protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.ext_iff]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (-s : set α) ≃ α := calc s ⊕ (-s : set α) ≃ ↥(s ∪ -s) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : -s) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ -s : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ -s : set α)) ∈ -s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := @subtype_prod_equiv_prod α β s t protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (λ x y hx hy hxy, H hxy) @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := { to_fun := λ x, ⟨f x, mem_range_self _⟩, inv_fun := λ x, classical.some x.2, left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)), right_inv := λ x, subtype.eq $ classical.some_spec x.2 } @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := rfl protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x.1 } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) := (equiv.forall_congr f.symm (λ x, h.symm)).symm -- We next build some higher arity versions of `equiv.forall_congr`. -- Although they appear to just be repeated applications of `equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) universes ua1 ua2 ub1 ub2 ug1 ug2 variables {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) : (∀x y, p x y) ↔ (∀x y, q x y) := begin apply equiv.forall_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀x y, p x y) ↔ (∀x y, q x y) := (equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := begin apply equiv.forall₂_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := (equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) : (∀x, p x) ↔ (∀y, p (f.symm y)) := equiv.forall_congr f (λx, by simp) protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) : (∀x, p (f x)) ↔ (∀y, p y) := (equiv.forall_congr_left' f.symm).symm section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } @[simp] lemma Pi_congr_left'_apply (f : Π a, P a) (b : β) : ((Pi_congr_left' P e) f) b = f (e.symm b) := rfl @[simp] lemma Pi_congr_left'_symm_apply (g : Π b, P (e.symm b)) (a : α) : ((Pi_congr_left' P e).symm g) a = (by { convert g (e a), simp }) := rfl end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm end end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique α) ≃ unique α := { to_fun := λ h, h.default, inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient /-- If a function is a bijection between `univ` and a set `s` in the target type, it induces an equivalence between the original type and the type `↑s`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set β} (f : α → β) (h : set.bij_on f set.univ s) : α ≃ s := begin have : function.bijective (λ (x : α), (⟨f x, begin exact h.maps_to (set.mem_univ x) end⟩ : s)), { split, { assume x y hxy, apply h.inj_on (set.mem_univ x) (set.mem_univ y) (subtype.mk.inj hxy) }, { assume x, rcases h.surj_on x.2 with ⟨y, hy⟩, exact ⟨y, subtype.eq hy.2⟩ } }, exact equiv.of_bijective this end /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Type*} {γ : Type*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { simp only [h, dif_pos], have A : e.symm ⟨i, h⟩ = j ↔ i = e j, by { rw equiv.symm_apply_eq, exact subtype.ext }, by_cases h' : i = e j, { rw [A.2 h', h'], simp }, { have : ¬ e.symm ⟨i, h⟩ = j, by simpa [← A] using h', simp [h, h', this] } }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
6c546d3ed23642163bc8f61719b96a1f391f507b
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/src/Init/Lean/Elab/App.lean
c3fe459156d55e31566aca40e93a3aa0b028ccd0
[ "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
29,968
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.FindMVar import Init.Lean.Elab.Term import Init.Lean.Elab.Binders namespace Lean namespace Elab namespace Term /-- Auxiliary inductive datatype for combining unelaborated syntax and already elaborated expressions. It is used to elaborate applications. -/ inductive Arg | stx (val : Syntax) | expr (val : Expr) instance Arg.inhabited : Inhabited Arg := ⟨Arg.stx (arbitrary _)⟩ instance Arg.hasToString : HasToString Arg := ⟨fun arg => match arg with | Arg.stx val => toString val | Arg.expr val => toString val⟩ /-- Named arguments created using the notation `(x := val)` -/ structure NamedArg := (name : Name) (val : Arg) instance NamedArg.hasToString : HasToString NamedArg := ⟨fun s => "(" ++ toString s.name ++ " := " ++ toString s.val ++ ")"⟩ instance NamedArg.inhabited : Inhabited NamedArg := ⟨{ name := arbitrary _, val := arbitrary _ }⟩ /-- Add a new named argument to `namedArgs`, and throw an error if it already contains a named argument with the same name. -/ def addNamedArg (ref : Syntax) (namedArgs : Array NamedArg) (namedArg : NamedArg) : TermElabM (Array NamedArg) := do when (namedArgs.any $ fun namedArg' => namedArg.name == namedArg'.name) $ throwError ref ("argument '" ++ toString namedArg.name ++ "' was already set"); pure $ namedArgs.push namedArg def synthesizeAppInstMVars (ref : Syntax) (instMVars : Array MVarId) : TermElabM Unit := instMVars.forM $ fun mvarId => unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass private def ensureArgType (ref : Syntax) (f : Expr) (arg : Expr) (expectedType : Expr) : TermElabM Expr := do argType ← inferType ref arg; ensureHasTypeAux ref expectedType argType arg f private def elabArg (ref : Syntax) (f : Expr) (arg : Arg) (expectedType : Expr) : TermElabM Expr := match arg with | Arg.expr val => ensureArgType ref f val expectedType | Arg.stx val => do val ← elabTerm val expectedType; ensureArgType ref f val expectedType private def mkArrow (d b : Expr) : TermElabM Expr := do n ← mkFreshAnonymousName; pure $ Lean.mkForall n BinderInfo.default d b /- Relevant definitions: ``` class CoeFun (α : Sort u) (γ : α → outParam (Sort v)) abbrev coeFun {α : Sort u} {γ : α → Sort v} (a : α) [CoeFun α γ] : γ a ``` -/ private def tryCoeFun (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do v ← mkFreshLevelMVar ref; type ← mkArrow α (mkSort v); γ ← mkFreshExprMVar ref type; u ← getLevel ref α; let coeFunInstType := mkAppN (Lean.mkConst `CoeFun [u, v]) #[α, γ]; mvar ← mkFreshExprMVar ref coeFunInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; synthesized ← catch (withoutMacroStackAtErr $ synthesizeInstMVarCore ref mvarId) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("function expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "function expected"); if synthesized then pure $ mkAppN (Lean.mkConst `coeFun [u, v]) #[α, γ, a, mvar] else throwError ref "function expected" /-- Auxiliary structure used to elaborate function application arguments. -/ structure ElabAppArgsCtx := (ref : Syntax) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) -- if true, all arguments are treated as explicit (argIdx : Nat := 0) -- position of next explicit argument to be processed (namedArgs : Array NamedArg) -- remaining named arguments to be processed (instMVars : Array MVarId := #[]) -- metavariables for the instance implicit arguments that have already been processed (typeMVars : Array MVarId := #[]) -- metavariables for implicit arguments of the form `{α : Sort u}` that have already been processed (foundExplicit : Bool := false) -- true if an explicit argument has already been processed /- Auxiliary function for retrieving the resulting type of a function application. See `propagateExpectedType`. -/ private partial def getForallBody : Nat → Array NamedArg → Expr → Option Expr | i, namedArgs, type@(Expr.forallE n d b c) => match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => getForallBody i (namedArgs.eraseIdx idx) b | none => if !c.binderInfo.isExplicit then getForallBody i namedArgs b else if i > 0 then getForallBody (i-1) namedArgs b else if d.isAutoParam || d.isOptParam then getForallBody i namedArgs b else some type | i, namedArgs, type => if i == 0 && namedArgs.isEmpty then some type else none private def hasTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => ctx.typeMVars.contains mvarId)).isSome private def hasOnlyTypeMVar (ctx : ElabAppArgsCtx) (type : Expr) : Bool := (type.findMVar? (fun mvarId => !ctx.typeMVars.contains mvarId)).isNone /- Auxiliary method for propagating the expected type. We call it as soon as we find the first explict argument. The goal is to propagate the expected type in applications of functions such as ```lean HasAdd.add {α : Type u} : α → α → α List.cons {α : Type u} : α → List α → List α ``` This is particularly useful when there applicable coercions. For example, assume we have a coercion from `Nat` to `Int`, and we have `(x : Nat)` and the expected type is `List Int`. Then, if we don't use this function, the elaborator will fail to elaborate ``` List.cons x [] ``` First, the elaborator creates a new metavariable `?α` for the implicit argument `{α : Type u}`. Then, when it processes `x`, it assigns `?α := Nat`, and then obtain the resultant type `List Nat` which is **not** definitionally equal to `List Int`. We solve the problem by executing this method before we elaborate the first explicit argument (`x` in this example). This method infers that the resultant type is `List ?α` and unifies it with `List Int`. Then, when we elaborate `x`, the elaborate realizes the coercion from `Nat` to `Int` must be used, and the term ``` @List.cons Int (coe x) (@List.nil Int) ``` is produced. The method will do nothing if 1- The resultant type depends on the remaining arguments (i.e., `!eTypeBody.hasLooseBVars`) 2- The resultant type does not contain any type metavariable. 3- The resultant type contains a nontype metavariable. We added conditions 2&3 to be able to restrict this method to simple functions that are "morally" in the Hindley&Milner fragment. For example, consider the following definitions ``` def foo {n m : Nat} (a : bv n) (b : bv m) : bv (n - m) ``` Now, consider ``` def test (x1 : bv 32) (x2 : bv 31) (y1 : bv 64) (y2 : bv 63) : bv 1 := foo x1 x2 = foo y1 y2 ``` When the elaborator reaches the term `foo y1 y2`, the expected type is `bv (32-31)`. If we apply this method, we would solve the unification problem `bv (?n - ?m) =?= bv (32 - 31)`, by assigning `?n := 32` and `?m := 31`. Then, the elaborator fails elaborating `y1` since `bv 64` is **not** definitionally equal to `bv 32`. -/ private def propagateExpectedType (ctx : ElabAppArgsCtx) (eType : Expr) : TermElabM Unit := unless (ctx.explicit || ctx.foundExplicit || ctx.typeMVars.isEmpty) $ do match ctx.expectedType? with | none => pure () | some expectedType => let numRemainingArgs := ctx.args.size - ctx.argIdx; match getForallBody numRemainingArgs ctx.namedArgs eType with | none => pure () | some eTypeBody => unless eTypeBody.hasLooseBVars $ when (hasTypeMVar ctx eTypeBody && hasOnlyTypeMVar ctx eTypeBody) $ do isDefEq ctx.ref expectedType eTypeBody; pure () private def nextArgIsHole (ctx : ElabAppArgsCtx) : Bool := if h : ctx.argIdx < ctx.args.size then match ctx.args.get ⟨ctx.argIdx, h⟩ with | Arg.stx (Syntax.node `Lean.Parser.Term.hole _) => true | _ => false else false /- Elaborate function application arguments. -/ private partial def elabAppArgsAux : ElabAppArgsCtx → Expr → Expr → TermElabM Expr | ctx, e, eType => do let finalize : Unit → TermElabM Expr := fun _ => do { -- all user explicit arguments have been consumed trace `Elab.app.finalize ctx.ref $ fun _ => e; match ctx.expectedType? with | none => pure () | some expectedType => do { -- Try to propagate expected type. Ignore if types are not definitionally equal, caller must handle it. isDefEq ctx.ref expectedType eType; pure () }; synthesizeAppInstMVars ctx.ref ctx.instMVars; pure e }; eType ← whnfForall ctx.ref eType; match eType with | Expr.forallE n d b c => match ctx.namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let arg := ctx.namedArgs.get! idx; let namedArgs := ctx.namedArgs.eraseIdx idx; argElab ← elabArg ctx.ref e arg.val d; propagateExpectedType ctx eType; elabAppArgsAux { foundExplicit := true, namedArgs := namedArgs, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) | none => let processExplictArg : Unit → TermElabM Expr := fun _ => do { propagateExpectedType ctx eType; let ctx := { foundExplicit := true, .. ctx }; if h : ctx.argIdx < ctx.args.size then do argElab ← elabArg ctx.ref e (ctx.args.get ⟨ctx.argIdx, h⟩) d; elabAppArgsAux { argIdx := ctx.argIdx + 1, .. ctx } (mkApp e argElab) (b.instantiate1 argElab) else match ctx.explicit, d.getOptParamDefault?, d.getAutoParamTactic? with | false, some defVal, _ => elabAppArgsAux ctx (mkApp e defVal) (b.instantiate1 defVal) | false, _, some (Expr.const tacticDecl _ _) => do env ← getEnv; match evalSyntaxConstant env tacticDecl with | Except.error err => throwError ctx.ref err | Except.ok tacticSyntax => do tacticBlock ← `(begin $(tacticSyntax.getArgs)* end); -- tacticBlock does not have any position information -- use ctx.ref.getHeadInfo if available let tacticBlock := match ctx.ref.getHeadInfo with | some info => tacticBlock.replaceInfo info | _ => tacticBlock; let d := d.getArg! 0; -- `autoParam type := by tactic` ==> `type` argElab ← elabArg ctx.ref e (Arg.stx tacticBlock) d; elabAppArgsAux ctx (mkApp e argElab) (b.instantiate1 argElab) | false, _, some _ => throwError ctx.ref "invalid autoParam, argument must be a constant" | _, _, _ => if ctx.namedArgs.isEmpty then finalize () else throwError ctx.ref ("explicit parameter '" ++ n ++ "' is missing, unused named arguments " ++ toString (ctx.namedArgs.map $ fun narg => narg.name)) }; match c.binderInfo with | BinderInfo.implicit => if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d; typeMVars ← condM (isTypeFormer ctx.ref a) (pure $ ctx.typeMVars.push a.mvarId!) (pure ctx.typeMVars); elabAppArgsAux { typeMVars := typeMVars, .. ctx } (mkApp e a) (b.instantiate1 a) | BinderInfo.instImplicit => if ctx.explicit && nextArgIsHole ctx then do /- Recall that if '@' has been used, and the argument is '_', then we still use type class resolution -/ a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { argIdx := ctx.argIdx + 1, instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) else if ctx.explicit then processExplictArg () else do a ← mkFreshExprMVar ctx.ref d MetavarKind.synthetic; elabAppArgsAux { instMVars := ctx.instMVars.push a.mvarId!, .. ctx } (mkApp e a) (b.instantiate1 a) | _ => processExplictArg () | _ => if ctx.namedArgs.isEmpty && ctx.argIdx == ctx.args.size then finalize () else do e ← tryCoeFun ctx.ref eType e; eType ← inferType ctx.ref e; elabAppArgsAux ctx e eType private def elabAppArgs (ref : Syntax) (f : Expr) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do fType ← inferType ref f; fType ← instantiateMVars ref fType; trace `Elab.app.args ref $ fun _ => "explicit: " ++ toString explicit ++ ", " ++ f ++ " : " ++ fType; unless (namedArgs.isEmpty && args.isEmpty) $ tryPostponeIfMVar fType; elabAppArgsAux {ref := ref, args := args, expectedType? := expectedType?, explicit := explicit, namedArgs := namedArgs } f fType /-- Auxiliary inductive datatype that represents the resolution of an `LVal`. -/ inductive LValResolution | projFn (baseStructName : Name) (structName : Name) (fieldName : Name) | projIdx (structName : Name) (idx : Nat) | const (baseName : Name) (constName : Name) | localRec (baseName : Name) (fullName : Name) (fvar : Expr) | getOp (fullName : Name) (idx : Syntax) private def throwLValError {α} (ref : Syntax) (e : Expr) (eType : Expr) (msg : MessageData) : TermElabM α := throwError ref $ msg ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType private def resolveLValAux (ref : Syntax) (e : Expr) (eType : Expr) (lval : LVal) : TermElabM LValResolution := match eType.getAppFn, lval with | Expr.const structName _ _, LVal.fieldIdx idx => do when (idx == 0) $ throwError ref "invalid projection, index must be greater than 0"; env ← getEnv; unless (isStructureLike env structName) $ throwLValError ref e eType "invalid projection, structure expected"; let fieldNames := getStructureFields env structName; if h : idx - 1 < fieldNames.size then if isStructure env structName then pure $ LValResolution.projFn structName structName (fieldNames.get ⟨idx - 1, h⟩) else /- `structName` was declared using `inductive` command. So, we don't projection functions for it. Thus, we use `Expr.proj` -/ pure $ LValResolution.projIdx structName (idx - 1) else throwLValError ref e eType ("invalid projection, structure has only " ++ toString fieldNames.size ++ " field(s)") | Expr.const structName _ _, LVal.fieldName fieldName => do env ← getEnv; let searchEnv (fullName : Name) : TermElabM LValResolution := do { match env.find? fullName with | some _ => pure $ LValResolution.const structName fullName | none => throwLValError ref e eType $ "invalid field notation, '" ++ fieldName ++ "' is not a valid \"field\" because environment does not contain '" ++ fullName ++ "'" }; -- search local context first, then environment let searchCtx : Unit → TermElabM LValResolution := fun _ => do { let fullName := structName ++ fieldName; currNamespace ← getCurrNamespace; let localName := fullName.replacePrefix currNamespace Name.anonymous; lctx ← getLCtx; match lctx.findFromUserName? localName with | some localDecl => if localDecl.binderInfo == BinderInfo.auxDecl then /- LVal notation is being used to make a "local" recursive call. -/ pure $ LValResolution.localRec structName fullName localDecl.toExpr else searchEnv fullName | none => searchEnv fullName }; if isStructure env structName then match findField? env structName fieldName with | some baseStructName => pure $ LValResolution.projFn baseStructName structName fieldName | none => searchCtx () else searchCtx () | Expr.const structName _ _, LVal.getOp idx => do env ← getEnv; let fullName := mkNameStr structName "getOp"; match env.find? fullName with | some _ => pure $ LValResolution.getOp fullName idx | none => throwLValError ref e eType $ "invalid [..] notation because environment does not contain '" ++ fullName ++ "'" | _, LVal.getOp idx => throwLValError ref e eType "invalid [..] notation, type is not of the form (C ...) where C is a constant" | _, _ => throwLValError ref e eType "invalid field notation, type is not of the form (C ...) where C is a constant" private partial def resolveLValLoop (ref : Syntax) (e : Expr) (lval : LVal) : Expr → Array Message → TermElabM LValResolution | eType, previousExceptions => do eType ← whnfCore ref eType; tryPostponeIfMVar eType; catch (resolveLValAux ref e eType lval) (fun ex => match ex with | Exception.postpone => throw ex | Exception.ex Elab.Exception.unsupportedSyntax => throw ex | Exception.ex (Elab.Exception.error errMsg) => do eType? ← unfoldDefinition? ref eType; match eType? with | some eType => resolveLValLoop eType (previousExceptions.push errMsg) | none => do previousExceptions.forM $ fun ex => logMessage errMsg; throw (Exception.ex (Elab.Exception.error errMsg))) private def resolveLVal (ref : Syntax) (e : Expr) (lval : LVal) : TermElabM LValResolution := do eType ← inferType ref e; resolveLValLoop ref e lval eType #[] private partial def mkBaseProjections (ref : Syntax) (baseStructName : Name) (structName : Name) (e : Expr) : TermElabM Expr := do env ← getEnv; match getPathToBaseStructure? env baseStructName structName with | none => throwError ref "failed to access field in parent structure" | some path => path.foldlM (fun e projFunName => do projFn ← mkConst ref projFunName; elabAppArgs ref projFn #[{ name := `self, val := Arg.expr e }] #[] none false) e /- Auxiliary method for field notation. It tries to add `e` to `args` as the first explicit parameter which takes an element of type `(C ...)` where `C` is `baseName`. `fullName` is the name of the resolved "field" access function. It is used for reporting errors -/ private def addLValArg (ref : Syntax) (baseName : Name) (fullName : Name) (e : Expr) (args : Array Arg) : Nat → Array NamedArg → Expr → TermElabM (Array Arg) | i, namedArgs, Expr.forallE n d b c => if !c.binderInfo.isExplicit then addLValArg i namedArgs b else /- If there is named argument with name `n`, then we should skip. -/ match namedArgs.findIdx? (fun namedArg => namedArg.name == n) with | some idx => do let namedArgs := namedArgs.eraseIdx idx; addLValArg i namedArgs b | none => do if d.consumeMData.isAppOf baseName then pure $ args.insertAt i (Arg.expr e) else if i < args.size then addLValArg (i+1) namedArgs b else throwError ref $ "invalid field notation, insufficient number of arguments for '" ++ fullName ++ "'" | _, _, fType => throwError ref $ "invalid field notation, function '" ++ fullName ++ "' does not have explicit argument with type (" ++ baseName ++ " ...)" private def elabAppLValsAux (ref : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : Expr → List LVal → TermElabM Expr | f, [] => elabAppArgs ref f namedArgs args expectedType? explicit | f, lval::lvals => do lvalRes ← resolveLVal ref f lval; match lvalRes with | LValResolution.projIdx structName idx => let f := mkProj structName idx f; elabAppLValsAux f lvals | LValResolution.projFn baseStructName structName fieldName => do f ← mkBaseProjections ref baseStructName structName f; projFn ← mkConst ref (baseStructName ++ fieldName); if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[{ name := `self, val := Arg.expr f }] #[] none false; elabAppLValsAux f lvals | LValResolution.const baseName constName => do projFn ← mkConst ref constName; if lvals.isEmpty then do projFnType ← inferType ref projFn; args ← addLValArg ref baseName constName f args 0 namedArgs projFnType; elabAppArgs ref projFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref projFn #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.localRec baseName fullName fvar => if lvals.isEmpty then do fvarType ← inferType ref fvar; args ← addLValArg ref baseName fullName f args 0 namedArgs fvarType; elabAppArgs ref fvar namedArgs args expectedType? explicit else do f ← elabAppArgs ref fvar #[] #[Arg.expr f] none false; elabAppLValsAux f lvals | LValResolution.getOp fullName idx => do getOpFn ← mkConst ref fullName; if lvals.isEmpty then do namedArgs ← addNamedArg ref namedArgs { name := `self, val := Arg.expr f }; namedArgs ← addNamedArg ref namedArgs { name := `idx, val := Arg.stx idx }; elabAppArgs ref getOpFn namedArgs args expectedType? explicit else do f ← elabAppArgs ref getOpFn #[{ name := `self, val := Arg.expr f }, { name := `idx, val := Arg.stx idx }] #[] none false; elabAppLValsAux f lvals private def elabAppLVals (ref : Syntax) (f : Expr) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) : TermElabM Expr := do when (!lvals.isEmpty && explicit) $ throwError ref "invalid use of field notation with `@` modifier"; elabAppLValsAux ref namedArgs args expectedType? explicit f lvals def elabExplicitUniv (stx : Syntax) : TermElabM (List Level) := do let lvls := stx.getArg 1; lvls.foldSepRevArgsM (fun stx lvls => do lvl ← elabLevel stx; pure (lvl::lvls)) [] private partial def elabAppFnId (ref : Syntax) (fIdent : Syntax) (fExplicitUnivs : List Level) (lvals : List LVal) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) (explicit : Bool) (acc : Array TermElabResult) : TermElabM (Array TermElabResult) := match fIdent with | Syntax.ident _ _ n preresolved => do funLVals ← resolveName fIdent n preresolved fExplicitUnivs; funLVals.foldlM (fun acc ⟨f, fields⟩ => do let lvals' := fields.map LVal.fieldName; s ← observing $ elabAppLVals ref f (lvals' ++ lvals) namedArgs args expectedType? explicit; pure $ acc.push s) acc | _ => throwUnsupportedSyntax private partial def elabAppFn (ref : Syntax) : Syntax → List LVal → Array NamedArg → Array Arg → Option Expr → Bool → Array TermElabResult → TermElabM (Array TermElabResult) | f, lvals, namedArgs, args, expectedType?, explicit, acc => if f.isIdent then -- A raw identifier is not a valid Term. Recall that `Term.id` is defined as `parser! ident >> optional (explicitUniv <|> namedPattern)` -- We handle it here to make macro development more comfortable. elabAppFnId ref f [] lvals namedArgs args expectedType? explicit acc else if f.getKind == choiceKind then f.getArgs.foldlM (fun acc f => elabAppFn f lvals namedArgs args expectedType? explicit acc) acc else match_syntax f with | `($(e).$idx:fieldIdx) => let idx := idx.isFieldIdx?.get!; elabAppFn e (LVal.fieldIdx idx :: lvals) namedArgs args expectedType? explicit acc | `($(e).$field:ident) => let newLVals := field.getId.eraseMacroScopes.components.map (fun n => LVal.fieldName (toString n)); elabAppFn e (newLVals ++ lvals) namedArgs args expectedType? explicit acc | `($e[$idx]) => elabAppFn e (LVal.getOp idx :: lvals) namedArgs args expectedType? explicit acc | `($id:ident$us:explicitUniv*) => do -- Remark: `id.<namedPattern>` should already have been expanded us ← if us.isEmpty then pure [] else elabExplicitUniv (us.get! 0); elabAppFnId ref id us lvals namedArgs args expectedType? explicit acc | `(@$id:id) => elabAppFn id lvals namedArgs args expectedType? true acc | _ => do s ← observing $ do { f ← elabTerm f none; elabAppLVals ref f lvals namedArgs args expectedType? explicit }; pure $ acc.push s private def getSuccess (candidates : Array TermElabResult) : Array TermElabResult := candidates.filter $ fun c => match c with | EStateM.Result.ok _ _ => true | _ => false private def toMessageData (msg : Message) (stx : Syntax) : TermElabM MessageData := do strPos ← getPos stx; pos ← getPosition strPos; if pos == msg.pos then pure msg.data else pure $ toString msg.pos.line ++ ":" ++ toString msg.pos.column ++ " " ++ msg.data private def mergeFailures {α} (failures : Array TermElabResult) (stx : Syntax) : TermElabM α := do msgs ← failures.mapM $ fun failure => match failure with | EStateM.Result.ok _ _ => unreachable! | EStateM.Result.error errMsg s => toMessageData errMsg stx; throwError stx ("overloaded, errors " ++ MessageData.ofArray msgs) private def elabAppAux (ref : Syntax) (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (expectedType? : Option Expr) : TermElabM Expr := do /- TODO: if `f` contains `choice` or overloaded symbols, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we should postpone until `?m` is assigned. Another (more expensive) option is: execute, and if successes > 1, `mayPostpone == true`, and `expectedType? == some ?m` where `?m` is not assigned, then we postpone `elabAppAux`. It is more expensive because we would have to re-elaborate the whole thing after we assign `?m`. We **can't** continue from `TermElabResult` since they contain a snapshot of the state, and state has changed. -/ candidates ← elabAppFn ref f [] namedArgs args expectedType? false #[]; if candidates.size == 1 then applyResult $ candidates.get! 0 else let successes := getSuccess candidates; if successes.size == 1 then applyResult $ successes.get! 0 else if successes.size > 1 then do lctx ← getLCtx; opts ← getOptions; let msgs : Array MessageData := successes.map $ fun success => match success with | EStateM.Result.ok e s => MessageData.withContext { env := s.env, mctx := s.mctx, lctx := lctx, opts := opts } e | _ => unreachable!; throwError f ("ambiguous, possible interpretations " ++ MessageData.ofArray msgs) else mergeFailures candidates f private partial def expandApp (stx : Syntax) : TermElabM (Syntax × Array NamedArg × Array Arg) := do let f := stx.getArg 0; (namedArgs, args) ← (stx.getArg 1).getArgs.foldlM (fun (acc : Array NamedArg × Array Arg) (stx : Syntax) => do let (namedArgs, args) := acc; if stx.getKind == `Lean.Parser.Term.namedArgument then do -- tparser! try ("(" >> ident >> " := ") >> termParser >> ")" let name := (stx.getArg 1).getId.eraseMacroScopes; let val := stx.getArg 3; namedArgs ← addNamedArg stx namedArgs { name := name, val := Arg.stx val }; pure (namedArgs, args) else pure (namedArgs, args.push $ Arg.stx stx)) (#[], #[]); pure (f, namedArgs, args) @[builtinTermElab app] def elabApp : TermElab := fun stx expectedType? => do (f, namedArgs, args) ← expandApp stx; elabAppAux stx f namedArgs args expectedType? def elabAtom : TermElab := fun stx expectedType? => elabAppAux stx stx #[] #[] expectedType? @[builtinTermElab «id»] def elabId : TermElab := elabAtom @[builtinTermElab explicit] def elabExplicit : TermElab := fun stx expectedType? => match_syntax stx with | `(@$f:fun) => elabFunCore f expectedType? true -- This rule is just a convenience for macro writers, the LHS cannot be built by the parser | `(@($f:fun)) => elabFunCore f expectedType? true -- Elaborate lambda abstraction `f` pretending all binders are explicit. | `(@($f:fun : $type)) => do -- Elaborate lambda abstraction `f` using `type` as the expected type, and pretending all binders are explicit. type ← elabType type; f ← elabFunCore f type true; ensureHasType stx type f | `(@$id:id) => elabAtom stx expectedType? /- Remark: we may support other occurrences `@` in the future, but we did not find compelling applications for them yet. One instance we considered that is barely useful: applications. We found the behavior counterintuitive. Example: ```lean def g1 {α} (a₁ a₂ : α) {β} (b : β) : α × α × β := (a₁, a₂, b) #check @(g1 true) -- α → {β : Type} → β → α × α × β ``` The example above is reasonable, but we say this feautre would produce counterintuitive because of the following small variant ```lean def g2 {α} (a : α) {β} (b : β) : α × β := (a, b) #check @(g2 true) -- ?β → α × ?β ``` That is, `g2 true` "consumed" the arguments `{α} (a : α) {β}` as expected. -/ | _ => throwUnsupportedSyntax @[builtinTermElab choice] def elabChoice : TermElab := elabAtom @[builtinTermElab proj] def elabProj : TermElab := elabAtom @[builtinTermElab arrayRef] def elabArrayRef : TermElab := elabAtom /- A raw identiier is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. -/ @[builtinTermElab ident] def elabRawIdent : TermElab := elabAtom @[builtinTermElab sortApp] def elabSortApp : TermElab := fun stx _ => do u ← elabLevel (stx.getArg 1); if (stx.getArg 0).getKind == `Lean.Parser.Term.sort then do pure $ mkSort u else pure $ mkSort (mkLevelSucc u) @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.app; pure () end Term end Elab end Lean
ad17db031542c119bffcaaf4ba76869c01f64e4e
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/test/lint.lean
c37e228042f7ca25a1274388279f4b533c506013
[ "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
4,627
lean
import tactic.lint 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 incorrect_def_lemma, 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 dup_namespace, guard $ l3.length = 1, guard $ ∃(x ∈ l3), (x : declaration × _).1.to_name = `foo.foo, l4 ← fold_over_with_cond l ge_or_gt_in_statement, 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, 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 tt [`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 ← incorrect_type_class_argument 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 ← impossible_instance 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 ← dangerous_instance 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 500 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 section def foo_instance {α} (R : setoid α) : has_coe α (quotient R) := ⟨quotient.mk⟩ local attribute [instance, priority 1] foo_instance run_cmd do d ← get_decl `foo_instance, some "illegal instance" ← has_coe_variable d, d ← get_decl `has_coe_to_fun, some s ← fails_quickly 3000 d, guard $ "maximum class-instance resolution depth has been reached".is_prefix_of s end /- 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
7df938e94fa75cf0821840361dca1e21df8644da
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Meta/Tactic/Assert.lean
a8be65a5bd6def3f62d441aa696d0ca502ea70a3
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,054
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Util import Lean.Meta.Tactic.FVarSubst import Lean.Meta.Tactic.Intro import Lean.Meta.Tactic.Revert namespace Lean.Meta /-- Convert the given goal `Ctx |- target` into `Ctx |- type -> target`. It assumes `val` has type `type` -/ def assert (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkForall name BinderInfo.default type target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId (mkApp newMVar val) pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- let name : type := val; target`. It assumes `val` has type `type` -/ def define (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) : MetaM MVarId := do withMVarContext mvarId $ do checkNotAssigned mvarId `define let tag ← getMVarTag mvarId let target ← getMVarType mvarId let newType := Lean.mkLet name type val target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag assignExprMVar mvarId newMVar pure newMVar.mvarId! /-- Convert the given goal `Ctx |- target` into `Ctx |- (hName : type) -> hName = val -> target`. It assumes `val` has type `type` -/ def assertExt (mvarId : MVarId) (name : Name) (type : Expr) (val : Expr) (hName : Name := `h) : MetaM MVarId := do withMVarContext mvarId $ do checkNotAssigned mvarId `assert let tag ← getMVarTag mvarId let target ← getMVarType mvarId let u ← getLevel type let hType := mkApp3 (mkConst `Eq [u]) type (mkBVar 0) val let newType := Lean.mkForall name BinderInfo.default type $ Lean.mkForall hName BinderInfo.default hType target let newMVar ← mkFreshExprSyntheticOpaqueMVar newType tag let rflPrf ← mkEqRefl val assignExprMVar mvarId (mkApp2 newMVar val rflPrf) pure newMVar.mvarId! structure AssertAfterResult := (fvarId : FVarId) (mvarId : MVarId) (subst : FVarSubst) /-- Convert the given goal `Ctx |- target` into a goal containing `(userName : type)` after the local declaration with if `fvarId`. It assumes `val` has type `type`, and that `type` is well-formed after `fvarId`. Note that `val` does not need to be well-formed after `fvarId`. That is, it may contain variables that are defined after `fvarId`. -/ def assertAfter (mvarId : MVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (val : Expr) : MetaM AssertAfterResult := do withMVarContext mvarId $ do checkNotAssigned mvarId `assertAfter let tag ← getMVarTag mvarId let target ← getMVarType mvarId let localDecl ← getLocalDecl fvarId let lctx ← getLCtx let localInsts ← getLocalInstances let fvarIds := lctx.foldl (init := #[]) (start := localDecl.index+1) fun fvarIds decl => fvarIds.push decl.fvarId let xs := fvarIds.map mkFVar let targetNew ← mkForallFVars xs target let targetNew := Lean.mkForall userName BinderInfo.default type targetNew let lctxNew := fvarIds.foldl (init := lctx) fun lctxNew fvarId => lctxNew.erase fvarId let localInstsNew := localInsts.filter fun inst => fvarIds.contains inst.fvar.fvarId! let mvarNew ← mkFreshExprMVarAt lctxNew localInstsNew targetNew MetavarKind.syntheticOpaque tag let args := (fvarIds.filter fun fvarId => !(lctx.get! fvarId).isLet).map mkFVar let args := #[val] ++ args assignExprMVar mvarId (mkAppN mvarNew args) let (fvarIdNew, mvarIdNew) ← intro1P mvarNew.mvarId! let (fvarIdsNew, mvarIdNew) ← introNP mvarIdNew fvarIds.size let subst := fvarIds.size.fold (init := {}) fun i subst => subst.insert fvarIds[i] (mkFVar fvarIdsNew[i]) pure { fvarId := fvarIdNew, mvarId := mvarIdNew, subst := subst } end Lean.Meta
c4f941620b3b6e9fd4fcdc1ecb422fbbdaf194d8
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Elab/Syntax.lean
230895a5bcbeebd6c36c3c71aa89907ed9f1705c
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
28,978
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.Elab.Command import Lean.Parser.Syntax namespace Lean.Elab.Term /- Expand `optional «precedence»` where «precedence» := leading_parser " : " >> precedenceParser -/ def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) := if stx.isNone then return none else return some (← evalPrec stx[0][1]) private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure ds[0] else let mut r := ds[0] for d in ds[1:ds.size] do r ← `(ParserDescr.binary `andthen $r $d) return r structure ToParserDescrContext where catName : Name first : Bool leftRec : Bool -- true iff left recursion is allowed /- See comment at `Parser.ParserCategory`. -/ behavior : Parser.LeadingIdentBehavior abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM) private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec) @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with first := false }) x @[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with leftRec := false, first := false }) x def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do let ctx ← read unless ctx.first && stx.getKind == `Lean.Parser.Syntax.cat do return false let cat := stx[0].getId.eraseMacroScopes unless cat == ctx.catName do return false let prec? ← liftMacroM <| expandOptPrecedence stx[1] unless ctx.leftRec do throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion" markAsTrailingParser (prec?.getD 0) return true /-- Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/ partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do let env ← getEnv let behavior := Parser.leadingIdentBehavior env catName (process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none where process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do let kind := stx.getKind if kind == nullKind then processSeq stx else if kind == choiceKind then process stx[0] else if kind == `Lean.Parser.Syntax.paren then process stx[1] else if kind == `Lean.Parser.Syntax.cat then processNullaryOrCat stx else if kind == `Lean.Parser.Syntax.unary then processUnary stx else if kind == `Lean.Parser.Syntax.binary then processBinary stx else if kind == `Lean.Parser.Syntax.sepBy then processSepBy stx else if kind == `Lean.Parser.Syntax.sepBy1 then processSepBy1 stx else if kind == `Lean.Parser.Syntax.atom then processAtom stx else if kind == `Lean.Parser.Syntax.nonReserved then processNonReserved stx else let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _) match stxNew? with | some stxNew => process stxNew | none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}" /- Sequence (aka NullNode) -/ processSeq (stx : Syntax) := do let args := stx.getArgs if (← checkLeftRec stx[0]) then if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax" let args := args.eraseIdx 0 let args ← args.mapM fun arg => withNestedParser do process arg mkParserSeq args else let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg mkParserSeq args /- Resolve the given parser name and return a list of candidates. Each candidate is a pair `(resolvedParserName, isDescr)`. `isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/ resolveParserName (parserName : Name) : ToParserDescrM (List (Name × Bool)) := do try let candidates ← resolveGlobalConstWithInfos (← getRef) parserName /- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name, and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/ candidates.filterMap fun c => match (← getEnv).find? c with | none => none | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => (c, false) | Expr.const `Lean.Parser.Parser _ _ => (c, false) | Expr.const `Lean.ParserDescr _ _ => (c, true) | Expr.const `Lean.TrailingParserDescr _ _ => (c, true) | _ => none catch _ => return [] ensureNoPrec (stx : Syntax) := unless stx[1].isNone do throwErrorAt stx[1] "unexpected precedence" processParserCategory (stx : Syntax) := do let catName := stx[0].getId.eraseMacroScopes if (← read).first && catName == (← read).catName then throwErrorAt stx "invalid atomic left recursive syntax" let prec? ← liftMacroM <| expandOptPrecedence stx[1] let prec := prec?.getD 0 `(ParserDescr.cat $(quote catName) $(quote prec)) processNullaryOrCat (stx : Syntax) := do let id := stx[0].getId.eraseMacroScopes match (← withRef stx[0] <| resolveParserName id) with | [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c | [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c)) | cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}" | [] => if Parser.isParserCategory (← getEnv) id then processParserCategory stx else if (← Parser.isParserAlias id) then ensureNoPrec stx Parser.ensureConstantParserAlias id `(ParserDescr.const $(quote id)) else throwError "unknown parser declaration/category/alias '{id}'" processUnary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureUnaryParserAlias aliasName let d ← withNestedParser do process stx[2] `(ParserDescr.unary $(quote aliasName) $d) processBinary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureBinaryParserAlias aliasName let d₁ ← withNestedParser do process stx[2] let d₂ ← withNestedParser do process stx[4] `(ParserDescr.binary $(quote aliasName) $d₁ $d₂) processSepBy (stx : Syntax) := do let p ← withNestedParser $ process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep)) processSepBy1 (stx : Syntax) := do let p ← withNestedParser do process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep)) processAtom (stx : Syntax) := do match stx[0].isStrLit? with | some atom => /- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark the first symbol as nonReserved. -/ if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then `(ParserDescr.nonReservedSymbol $(quote atom) false) else `(ParserDescr.symbol $(quote atom)) | none => throwUnsupportedSyntax processNonReserved (stx : Syntax) := do match stx[1].isStrLit? with | some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false) | none => throwUnsupportedSyntax end Term namespace Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command private def getCatSuffix (catName : Name) : String := match catName with | Name.str _ s _ => s | _ => unreachable! private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do let quotSymbol := "`(" ++ getCatSuffix catName ++ "|" let name := catName ++ `quot -- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator let kind := ``Lean.Parser.Term.quot let cmd ← `( @[termParser] def $(mkIdent name) : Lean.ParserDescr := Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.cat $(quote catName) 0) (Lean.ParserDescr.symbol ")")))) elabCommand cmd @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let catName := stx[1].getId let attrName := catName.appendAfter "Parser" let env ← getEnv let env ← liftIO $ Parser.registerParserCategory env attrName catName setEnv env declareSyntaxCatQuotParser catName /-- Auxiliary function for creating declaration names from parser descriptions. Example: Given ``` syntax term "+" term : term syntax "[" sepBy(term, ", ") "]" : term ``` It generates the names `term_+_` and `term[_,]` -/ partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : CommandElabM Name := mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx "" where visit (stx : Syntax) (acc : String) : String := match stx.isStrLit? with | some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize | none => match stx with | Syntax.node k args => if k == `Lean.Parser.Syntax.cat then acc ++ "_" else args.foldl (init := acc) fun acc arg => visit arg acc | Syntax.ident .. => acc | Syntax.atom .. => acc | Syntax.missing => acc appendCatName (str : String) := match catName with | Name.str _ s _ => s ++ str | _ => str /- We assume a new syntax can be treated as an atom when it starts and ends with a token. Here are examples of atom-like syntax. ``` syntax "(" term ")" : term syntax "[" (sepBy term ",") "]" : term syntax "foo" : term ``` -/ private partial def isAtomLikeSyntax (stx : Syntax) : Bool := let kind := stx.getKind if kind == nullKind then isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1] else if kind == choiceKind then isAtomLikeSyntax stx[0] -- see toParserDescr else if kind == `Lean.Parser.Syntax.paren then isAtomLikeSyntax stx[1] else kind == `Lean.Parser.Syntax.atom @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do let `($attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx | throwUnsupportedSyntax let cat := catStx.getId.eraseMacroScopes unless (Parser.isParserCategory (← getEnv) cat) do throwErrorAt catStx "unknown category '{cat}'" let syntaxParser := mkNullNode ps -- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise. let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec let prec ← match prec? with | some prec => liftMacroM <| evalPrec prec | none => precDefault let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax cat syntaxParser let prio ← liftMacroM <| evalOptPrio prio? let stxNodeKind := (← getCurrNamespace) ++ name let catParserId := mkIdentFrom stx (cat.appendAfter "Parser") let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat let declName := mkIdentFrom stx name let d ← if let some lhsPrec := lhsPrec? then `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val) else `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.ParserDescr := ParserDescr.node $(quote stxNodeKind) $(quote prec) $val) trace `Elab fun _ => d withMacroExpansion stx d <| elabCommand d /- def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser -/ @[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do let declName := stx[1] -- TODO: nonatomic names let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous let stxNodeKind := (← getCurrNamespace) ++ declName.getId let stx' ← `(def $declName : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val) withMacroExpansion stx stx' $ elabCommand stx' /- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do let alts ← alts.mapM fun alt => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if k' == k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => quotAlt.getKind == k with | none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $pats,* => $rhs) else throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax `(@[macro $(Lean.mkIdent k)] def myMacro : Macro := fun $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax) def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat pure quoted.getKind | _ => throwUnsupportedSyntax def elabNoKindMacroRulesAux (alts : Array Syntax) : CommandElabM Syntax := do let k ← inferMacroRulesAltKind alts[0] if k == choiceKind then throwErrorAt alts[0] "invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)" else let altsK ← alts.filterM fun alt => do pure $ k == (← inferMacroRulesAltKind alt) let altsNotK ← alts.filterM fun alt => do pure $ k != (← inferMacroRulesAltKind alt) let defCmd ← elabMacroRulesAux k altsK if altsNotK.isEmpty then pure defCmd else `($defCmd:command macro_rules $altsNotK:matchAlt*) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match stx with | `(macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux alts | `(macro_rules [$kind] $alts:matchAlt*) => do elabMacroRulesAux ((← getCurrNamespace) ++ kind.getId) alts | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx => withAttrKindGlobal stx fun stx => do match stx with | `(infixl $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs$[:$prec]? $op:strLit rhs:$prec1 => $f lhs rhs) | `(infix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec1 => $f lhs rhs) | `(infixr $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs $[: $prec]? => $f lhs rhs) | `(prefix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op:strLit arg $[: $prec]? => $f arg) | `(postfix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? arg$[:$prec]? $op:strLit => $f arg) | _ => Macro.throwUnsupported where -- set "global" `attrKind`, apply `f`, and restore `attrKind` to result withAttrKindGlobal stx f := do let attrKind := stx[0] let stx := stx.setArg 0 mkAttrKindGlobal let stx ← f stx return stx.setArg 0 attrKind /- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id else stx | _ => match stx with | Syntax.node k args => Syntax.node k (args.map (antiquote vars)) | stx => stx /- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem (stx : Syntax) : CommandElabM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]] else if k == strLitKind then pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx] else throwUnsupportedSyntax def strLitToPattern (stx: Syntax) : MacroM Syntax := match stx.isStrLit? with | some str => pure $ mkAtomFrom stx str | none => Macro.throwUnsupported /- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : CommandElabM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then mkAntiquotNode stx[0] else if k == strLitKind then liftMacroM <| strLitToPattern stx else throwUnsupportedSyntax /-- Try to derive a `SimpleDelab` from a notation. The notation must be of the form `notation ... => c var_1 ... var_n` where `c` is a declaration in the current scope and the `var_i` are a permutation of the LHS vars. -/ def mkSimpleDelab (attrKind : Syntax) (vars : Array Syntax) (pat qrhs : Syntax) : OptionT CommandElabM Syntax := do match qrhs with | `($c:ident $args*) => let [(c, [])] ← resolveGlobalName c.getId | failure guard <| args.all (Syntax.isIdent ∘ getAntiquotTerm) guard <| args.allDiff -- replace head constant with (unused) antiquotation so we're not dependent on the exact pretty printing of the head let qrhs ← `($(mkAntiquotNode (← `(_))) $args*) `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun | `($qrhs) => `($pat) | _ => throw ()) | `($c:ident) => let [(c, [])] ← resolveGlobalName c.getId | failure `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun _ => `($pat)) | _ => failure private def expandNotationAux (ref : Syntax) (currNamespace : Name) (attrKind : Syntax) (prec? : Option Syntax) (name? : Option Syntax) (prio? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : CommandElabM Syntax := do let prio ← liftMacroM <| evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax `term (mkNullNode syntaxParts) -- build macro rules let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec let vars := vars.map fun var => var[0] let qrhs := antiquote vars rhs let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat := Syntax.node fullName patArgs let stxDecl ← `($attrKind:attrKind syntax $[: $prec?]? (name := $(mkIdent name)) (priority := $(quote prio):numLit) $[$syntaxParts]* : $cat) let macroDecl ← `(macro_rules | `($pat) => `($qrhs)) match (← mkSimpleDelab attrKind vars pat qrhs |>.run) with | some delabDecl => mkNullNode #[stxDecl, macroDecl, delabDecl] | none => mkNullNode #[stxDecl, macroDecl] @[builtinCommandElab «notation»] def expandNotation : CommandElab := adaptExpander fun stx => do let currNamespace ← getCurrNamespace match stx with | `($attrKind:attrKind notation $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx currNamespace attrKind prec? name? prio? items rhs | _ => throwUnsupportedSyntax /- Convert `macro` argument into a `syntax` command item -/ def expandMacroArgIntoSyntaxItem : Macro | `(macroArg|$id:ident:$stx) => stx -- can't match against `$s:strLit%$id` because the latter part would be interpreted as an antiquotation on the token -- `strLit`. | `(macroArg|$s:macroArgSymbol) => `(stx|$(s[0]):strLit) | _ => Macro.throwUnsupported /- Convert `macro` arg into a pattern element -/ def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := do match (← expandMacros stx) with | `(macroArg|$id:ident:optional($stx)) => mkSplicePat `optional id "?" | `(macroArg|$id:ident:many($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:many1($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:sepBy($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:sepBy1($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:$stx) => mkAntiquotNode id | `(macroArg|$s:strLit) => strLitToPattern s -- `"tk"%id` ~> `"tk"%$id` | `(macroArg|$s:macroArgSymbol) => mkNode `token_antiquot #[← strLitToPattern s[0], mkAtom "%", mkAtom "$", s[1][1]] | _ => Macro.throwUnsupported where mkSplicePat kind id suffix := mkNullNode #[mkAntiquotSuffixSpliceNode kind (mkAntiquotNode id) suffix] /- «macro» := leading_parser suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail) -/ def expandMacro (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← liftMacroM <| expandOptNamedName stx[3] let prio ← liftMacroM <| expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] -- build parser let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build macro rules let patHead ← liftMacroM <| expandMacroArgIntoPattern head let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs) if stx.getArgs.size == 11 then -- `stx` is of the form `macro $head $args* : $cat => term` let rhs := stx[10] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => $rhs) return mkNullNode #[stxCmd, macroRulesCmd] else -- `stx` is of the form `macro $head $args* : $cat => `( $body )` let rhsBody := stx[11] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => `($rhsBody)) return mkNullNode #[stxCmd, macroRulesCmd] @[builtinCommandElab «macro»] def elabMacro : CommandElab := adaptExpander fun stx => do expandMacro (← getCurrNamespace) stx builtin_initialize registerTraceClass `Elab.syntax @[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do Term.tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "expected type must be known" x expectedType /- def elabTail := try (" : " >> ident) >> darrow >> termParser def «elab» := leading_parser suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail) -/ def expandElab (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do let ref := stx let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← liftMacroM <| expandOptNamedName stx[3] let prio ← liftMacroM <| expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] let expectedTypeSpec := stx[9] let rhs := stx[11] let catName := cat.getId -- build parser let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build pattern for `martch_syntax let patHead ← liftMacroM <| expandMacroArgIntoPattern head let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs) let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let elabCmd ← if expectedTypeSpec.hasArgs then if catName == `term then let expId := expectedTypeSpec[1] `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx expectedType? => match stx with | `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs | _ => throwUnsupportedSyntax) else throwErrorAt expectedTypeSpec "syntax category '{catName}' does not support expected type specification" else if catName == `term then `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx _ => match stx with | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `command then `(@[commandElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Command.CommandElab := fun | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `tactic then `(@[tactic $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Tactic.Tactic := fun | `(tactic|$pat) => $rhs | _ => throwUnsupportedSyntax) else -- We considered making the command extensible and support new user-defined categories. We think it is unnecessary. -- If users want this feature, they add their own `elab` macro that uses this one as a fallback. throwError "unsupported syntax category '{catName}'" return mkNullNode #[stxCmd, elabCmd] @[builtinCommandElab «elab»] def elabElab : CommandElab := adaptExpander fun stx => do expandElab (← getCurrNamespace) stx end Lean.Elab.Command
b21bf06f9d5bc89d24b93f449b47834264d85dfb
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/matrix/basis.lean
8e53b4f82e122242170fb52980767e6e4ebc0118
[ "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
6,287
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 linear_algebra.matrix.to_lin /-! # Bases and matrices This file defines the map `basis.to_matrix` that sends a family of vectors to the matrix of their coordinates with respect to some basis. ## Main definitions * `basis.to_matrix e v` is the matrix whose `i, j`th entry is `e.repr (v j) i` * `basis.to_matrix_equiv` is `basis.to_matrix` bundled as a linear equiv ## Main results * `linear_map.to_matrix_id_eq_basis_to_matrix`: `linear_map.to_matrix b c id` is equal to `basis.to_matrix b c` * `basis.to_matrix_mul_to_matrix`: multiplying `basis.to_matrix` with another `basis.to_matrix` gives a `basis.to_matrix` ## Tags matrix, basis -/ noncomputable theory open linear_map matrix set submodule open_locale big_operators open_locale matrix section basis_to_matrix variables {ι ι' κ κ' : Type*} [fintype ι] [fintype ι'] [fintype κ] [fintype κ'] variables {R M : Type*} [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 basis.to_matrix (e : basis ι R M) (v : ι' → M) : matrix ι ι' R := λ i j, e.repr (v j) i variables (e : basis ι R M) (v : ι' → M) (i : ι) (j : ι') namespace basis lemma to_matrix_apply : e.to_matrix v i j = e.repr (v j) i := rfl lemma to_matrix_transpose_apply : (e.to_matrix v)ᵀ j = e.repr (v j) := funext $ (λ _, rfl) lemma to_matrix_eq_to_matrix_constr [decidable_eq ι] (v : ι → M) : e.to_matrix v = linear_map.to_matrix e e (e.constr ℕ v) := by { ext, rw [basis.to_matrix_apply, linear_map.to_matrix_apply, basis.constr_basis] } @[simp] lemma to_matrix_self [decidable_eq ι] : e.to_matrix e = 1 := begin rw basis.to_matrix, ext i j, simp [basis.equiv_fun, matrix.one_apply, finsupp.single, eq_comm] end lemma to_matrix_update [decidable_eq ι'] (x : M) : e.to_matrix (function.update v j x) = matrix.update_column (e.to_matrix v) j (e.repr x) := begin ext i' k, rw [basis.to_matrix, matrix.update_column_apply, e.to_matrix_apply], split_ifs, { rw [h, update_same j x v] }, { rw update_noteq h }, end @[simp] lemma sum_to_matrix_smul_self : ∑ (i : ι), e.to_matrix v i j • e i = v j := by simp_rw [e.to_matrix_apply, e.sum_repr] @[simp] lemma to_lin_to_matrix [decidable_eq ι'] (v : basis ι' R M) : matrix.to_lin v e (e.to_matrix v) = id := v.ext (λ i, by rw [to_lin_self, id_apply, e.sum_to_matrix_smul_self]) /-- 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 : basis ι R M) : (ι → M) ≃ₗ[R] matrix ι ι R := { to_fun := e.to_matrix, map_add' := λ v w, begin ext i j, change _ = _ + _, rw [e.to_matrix_apply, pi.add_apply, linear_equiv.map_add], refl end, map_smul' := begin intros c v, ext i j, rw [e.to_matrix_apply, pi.smul_apply, linear_equiv.map_smul], refl end, inv_fun := λ m j, ∑ i, (m i j) • e i, left_inv := begin intro v, ext j, exact e.sum_to_matrix_smul_self v j end, right_inv := begin intros m, ext k l, simp only [e.to_matrix_apply, ← e.equiv_fun_apply, ← e.equiv_fun_symm_apply, linear_equiv.apply_symm_apply], end } end basis section mul_linear_map_to_matrix variables {N : Type*} [add_comm_group N] [module R N] variables (b : basis ι R M) (b' : basis ι' R M) (c : basis κ R N) (c' : basis κ' R N) variables (f : M →ₗ[R] N) open linear_map @[simp] lemma basis_to_matrix_mul_linear_map_to_matrix [decidable_eq ι'] : c.to_matrix c' ⬝ linear_map.to_matrix b' c' f = linear_map.to_matrix b' c f := (matrix.to_lin b' c).injective (by haveI := classical.dec_eq κ'; rw [to_lin_to_matrix, to_lin_mul b' c' c, to_lin_to_matrix, c.to_lin_to_matrix, id_comp]) @[simp] lemma linear_map_to_matrix_mul_basis_to_matrix [decidable_eq ι] [decidable_eq ι'] : linear_map.to_matrix b' c' f ⬝ b'.to_matrix b = linear_map.to_matrix b c' f := (matrix.to_lin b c').injective (by rw [to_lin_to_matrix, to_lin_mul b b' c', to_lin_to_matrix, b'.to_lin_to_matrix, comp_id]) /-- A generalization of `linear_map.to_matrix_id`. -/ @[simp] lemma linear_map.to_matrix_id_eq_basis_to_matrix [decidable_eq ι] : linear_map.to_matrix b b' id = b'.to_matrix b := by { haveI := classical.dec_eq ι', rw [← basis_to_matrix_mul_linear_map_to_matrix b b', to_matrix_id, matrix.mul_one] } /-- A generalization of `basis.to_matrix_self`, in the opposite direction. -/ @[simp] lemma basis.to_matrix_mul_to_matrix {ι'' : Type*} [fintype ι''] (b'' : ι'' → M) : b.to_matrix b' ⬝ b'.to_matrix b'' = b.to_matrix b'' := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq ι', haveI := classical.dec_eq ι'', ext i j, simp only [matrix.mul_apply, basis.to_matrix_apply, basis.sum_repr_mul_repr], end @[simp] lemma basis.to_matrix_reindex (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).to_matrix v = (b.to_matrix v).minor e.symm id := by { ext, simp only [basis.to_matrix_apply, basis.reindex_repr, matrix.minor_apply, id.def] } /-- See also `basis.to_matrix_reindex` which gives the `simp` normal form of this result. -/ lemma basis.to_matrix_reindex' [decidable_eq ι] [decidable_eq ι'] (b : basis ι R M) (v : ι' → M) (e : ι ≃ ι') : (b.reindex e).to_matrix v = matrix.reindex_alg_equiv e (b.to_matrix (v ∘ e)) := by { ext, simp only [basis.to_matrix_apply, basis.reindex_repr, matrix.reindex_alg_equiv_apply, matrix.reindex_apply, matrix.minor_apply, function.comp_app, e.apply_symm_apply] } @[simp] lemma basis.to_matrix_map (b : basis ι R M) (f : M ≃ₗ[R] N) (v : ι → N) : (b.map f).to_matrix v = b.to_matrix (f.symm ∘ v) := by { ext, simp only [basis.to_matrix_apply, basis.map, linear_equiv.trans_apply] } end mul_linear_map_to_matrix end basis_to_matrix
3cc4ea620af545923fb3ac5a8882a1b727b99cb0
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/algebra/ordered_field.lean
c1941d7d84f945776d433f232ccd79ee2f7adfc1
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
18,457
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura -/ prelude import init.algebra.ordered_ring init.algebra.field set_option old_structure_cmd true universe u class linear_ordered_field (α : Type u) extends linear_ordered_ring α, field α section linear_ordered_field variables {α : Type u} [linear_ordered_field α] lemma mul_zero_lt_mul_inv_of_pos {a : α} (h : 0 < a) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne.symm (ne_of_lt h))) ... = a * (1 / a) : by rw inv_eq_one_div lemma mul_zero_lt_mul_inv_of_neg {a : α} (h : a < 0) : a * 0 < a * (1 / a) := calc a * 0 = 0 : by rw mul_zero ... < 1 : zero_lt_one ... = a * a⁻¹ : eq.symm (mul_inv_cancel (ne_of_lt h)) ... = a * (1 / a) : by rw inv_eq_one_div lemma one_div_pos_of_pos {a : α} (h : 0 < a) : 0 < 1 / a := lt_of_mul_lt_mul_left (mul_zero_lt_mul_inv_of_pos h) (le_of_lt h) lemma one_div_neg_of_neg {a : α} (h : a < 0) : 1 / a < 0 := gt_of_mul_lt_mul_neg_left (mul_zero_lt_mul_inv_of_neg h) (le_of_lt h) lemma le_mul_of_ge_one_right {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ b * a := suffices b * 1 ≤ b * a, by rwa mul_one at this, mul_le_mul_of_nonneg_left h hb lemma le_mul_of_ge_one_left {a b : α} (hb : b ≥ 0) (h : a ≥ 1) : b ≤ a * b := by rw mul_comm; exact le_mul_of_ge_one_right hb h lemma lt_mul_of_gt_one_right {a b : α} (hb : b > 0) (h : a > 1) : b < b * a := suffices b * 1 < b * a, by rwa mul_one at this, mul_lt_mul_of_pos_left h hb lemma one_le_div_of_le (a : α) {b : α} (hb : b > 0) (h : b ≤ a) : 1 ≤ a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... ≤ a * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt hbinv) ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma le_of_one_le_div (a : α) {b : α} (hb : b > 0) (h : 1 ≤ a / b) : b ≤ a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b ≤ b * (a / b) : le_mul_of_ge_one_right (le_of_lt hb) h ... = a : by rw [mul_div_cancel' _ hb'] lemma one_lt_div_of_lt (a : α) {b : α} (hb : b > 0) (h : b < a) : 1 < a / b := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), have hbinv : 1 / b > 0, from one_div_pos_of_pos hb, calc 1 = b * (1 / b) : eq.symm (mul_one_div_cancel hb') ... < a * (1 / b) : mul_lt_mul_of_pos_right h hbinv ... = a / b : eq.symm $ div_eq_mul_one_div a b lemma lt_of_one_lt_div (a : α) {b : α} (hb : b > 0) (h : 1 < a / b) : b < a := have hb' : b ≠ 0, from ne.symm (ne_of_lt hb), calc b < b * (a / b) : lt_mul_of_gt_one_right hb h ... = a : by rw [mul_div_cancel' _ hb'] -- the following lemmas amount to four iffs, for <, ≤, ≥, >. lemma mul_le_of_le_div {a b c : α} (hc : 0 < c) (h : a ≤ b / c) : a * c ≤ b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_le_mul_of_nonneg_right h (le_of_lt hc) lemma le_div_of_mul_le {a b c : α} (hc : 0 < c) (h : a * c ≤ b) : a ≤ b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... ≤ b * (1 / c) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_lt_div {a b c : α} (hc : 0 < c) (h : a < b / c) : a * c < b := div_mul_cancel b (ne.symm (ne_of_lt hc)) ▸ mul_lt_mul_of_pos_right h hc lemma lt_div_of_mul_lt {a b c : α} (hc : 0 < c) (h : a * c < b) : a < b / c := calc a = a * c * (1 / c) : mul_mul_div a (ne.symm (ne_of_lt hc)) ... < b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_le_of_div_le_of_neg {a b c : α} (hc : c < 0) (h : b / c ≤ a) : a * c ≤ b := div_mul_cancel b (ne_of_lt hc) ▸ mul_le_mul_of_nonpos_right h (le_of_lt hc) lemma div_le_of_mul_le_of_neg {a b c : α} (hc : c < 0) (h : a * c ≤ b) : b / c ≤ a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... ≥ b * (1 / c) : mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma mul_lt_of_gt_div_of_neg {a b c : α} (hc : c < 0) (h : a > b / c) : a * c < b := div_mul_cancel b (ne_of_lt hc) ▸ mul_lt_mul_of_neg_right h hc lemma div_lt_of_mul_lt_of_pos {a b c : α} (hc : c > 0) (h : b < a * c) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_gt hc) ... > b * (1 / c) : mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_lt_of_mul_gt_of_neg {a b c : α} (hc : c < 0) (h : a * c < b) : b / c < a := calc a = a * c * (1 / c) : mul_mul_div a (ne_of_lt hc) ... > b * (1 / c) : mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) ... = b / c : eq.symm $ div_eq_mul_one_div b c lemma div_le_of_le_mul {a b c : α} (hb : b > 0) (h : a ≤ b * c) : a / b ≤ c := calc a / b = a * (1 / b) : div_eq_mul_one_div a b ... ≤ (b * c) * (1 / b) : mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hb)) ... = (b * c) / b : eq.symm $ div_eq_mul_one_div (b * c) b ... = c : by rw [mul_div_cancel_left _ (ne.symm (ne_of_lt hb))] lemma le_mul_of_div_le {a b c : α} (hc : c > 0) (h : a / c ≤ b) : a ≤ b * c := calc a = a / c * c : by rw (div_mul_cancel _ (ne.symm (ne_of_lt hc))) ... ≤ b * c : mul_le_mul_of_nonneg_right h (le_of_lt hc) -- following these in the isabelle file, there are 8 biconditionals for the above with - signs -- skipping for now lemma mul_sub_mul_div_mul_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c < b / d) : (a * d - b * c) / (c * d) < 0 := have h1 : a / c - b / d < 0, from calc a / c - b / d < b / d - b / d : sub_lt_sub_right h _ ... = 0 : by rw sub_self, calc 0 > a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma mul_sub_mul_div_mul_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : a / c ≤ b / d) : (a * d - b * c) / (c * d) ≤ 0 := have h1 : a / c - b / d ≤ 0, from calc a / c - b / d ≤ b / d - b / d : sub_le_sub_right h _ ... = 0 : by rw sub_self, calc 0 ≥ a / c - b / d : h1 ... = (a * d - c * b) / (c * d) : div_sub_div _ _ hc hd ... = (a * d - b * c) / (c * d) : by rw (mul_comm b c) lemma div_lt_div_of_mul_sub_mul_div_neg {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) < 0) : a / c < b / d := have (a * d - c * b) / (c * d) < 0, by rwa [mul_comm c b], have a / c - b / d < 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d < 0 + b / d, from add_lt_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_le_div_of_mul_sub_mul_div_nonpos {a b c d : α} (hc : c ≠ 0) (hd : d ≠ 0) (h : (a * d - b * c) / (c * d) ≤ 0) : a / c ≤ b / d := have (a * d - c * b) / (c * d) ≤ 0, by rwa [mul_comm c b], have a / c - b / d ≤ 0, by rwa [div_sub_div _ _ hc hd], have a / c - b / d + b / d ≤ 0 + b / d, from add_le_add_right this _, by rwa [zero_add, sub_eq_add_neg, neg_add_cancel_right] at this lemma div_pos_of_pos_of_pos {a b : α} : 0 < a → 0 < b → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonneg_of_nonneg_of_pos {a b : α} : 0 ≤ a → 0 < b → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_neg_of_pos {a b : α} : a < 0 → 0 < b → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_neg_of_pos, assumption, apply one_div_pos_of_pos, assumption end lemma div_nonpos_of_nonpos_of_pos {a b : α} : a ≤ 0 → 0 < b → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonpos_of_nonneg, assumption, apply le_of_lt, apply one_div_pos_of_pos, assumption end lemma div_neg_of_pos_of_neg {a b : α} : 0 < a → b < 0 → a / b < 0 := begin intros, rw div_eq_mul_one_div, apply mul_neg_of_pos_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonpos_of_nonneg_of_neg {a b : α} : 0 ≤ a → b < 0 → a / b ≤ 0 := begin intros, rw div_eq_mul_one_div, apply mul_nonpos_of_nonneg_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_pos_of_neg_of_neg {a b : α} : a < 0 → b < 0 → 0 < a / b := begin intros, rw div_eq_mul_one_div, apply mul_pos_of_neg_of_neg, assumption, apply one_div_neg_of_neg, assumption end lemma div_nonneg_of_nonpos_of_neg {a b : α} : a ≤ 0 → b < 0 → 0 ≤ a / b := begin intros, rw div_eq_mul_one_div, apply mul_nonneg_of_nonpos_of_nonpos, assumption, apply le_of_lt, apply one_div_neg_of_neg, assumption end lemma div_lt_div_of_lt_of_pos {a b c : α} (h : a < b) (hc : 0 < c) : a / c < b / c := begin intros, rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_pos_right h (one_div_pos_of_pos hc) end lemma div_le_div_of_le_of_pos {a b c : α} (h : a ≤ b) (hc : 0 < c) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonneg_right h (le_of_lt (one_div_pos_of_pos hc)) end lemma div_lt_div_of_lt_of_neg {a b c : α} (h : b < a) (hc : c < 0) : a / c < b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_lt_mul_of_neg_right h (one_div_neg_of_neg hc) end lemma div_le_div_of_le_of_neg {a b c : α} (h : b ≤ a) (hc : c < 0) : a / c ≤ b / c := begin rw [div_eq_mul_one_div a c, div_eq_mul_one_div b c], exact mul_le_mul_of_nonpos_right h (le_of_lt (one_div_neg_of_neg hc)) end lemma two_pos : (2:α) > 0 := begin unfold bit0, exact add_pos zero_lt_one zero_lt_one end lemma two_ne_zero : (2:α) ≠ 0 := ne.symm (ne_of_lt two_pos) lemma add_halves (a : α) : a / 2 + a / 2 = a := calc a / 2 + a / 2 = (a + a) / 2 : by rw div_add_div_same ... = (a * 1 + a * 1) / 2 : by rw mul_one ... = (a * (1 + 1)) / 2 : by rw left_distrib ... = (a * 2) / 2 : by rw one_add_one_eq_two ... = a : by rw [@mul_div_cancel α _ _ _ two_ne_zero] lemma sub_self_div_two (a : α) : a - a / 2 = a / 2 := suffices a / 2 + a / 2 - a / 2 = a / 2, by rwa add_halves at this, by rw [add_sub_cancel] lemma add_midpoint {a b : α} (h : a < b) : a + (b - a) / 2 < b := begin rw [← div_sub_div_same, sub_eq_add_neg, add_comm (b/2), ← add_assoc, ← sub_eq_add_neg], apply add_lt_of_lt_sub_right, rw [sub_self_div_two, sub_self_div_two], apply div_lt_div_of_lt_of_pos h two_pos end lemma div_two_sub_self (a : α) : a / 2 - a = - (a / 2) := suffices a / 2 - (a / 2 + a / 2) = - (a / 2), by rwa add_halves at this, by rw [sub_add_eq_sub_sub, sub_self, zero_sub] lemma add_self_div_two (a : α) : (a + a) / 2 = a := eq.symm (iff.mpr (eq_div_iff_mul_eq _ _ (ne_of_gt (add_pos (@zero_lt_one α _) zero_lt_one))) (begin unfold bit0, rw [left_distrib, mul_one] end)) lemma two_gt_one : (2:α) > 1 := calc (2:α) = 1+1 : one_add_one_eq_two ... > 1+0 : add_lt_add_left zero_lt_one _ ... = 1 : add_zero 1 lemma two_ge_one : (2:α) ≥ 1 := le_of_lt two_gt_one lemma four_pos : (4:α) > 0 := add_pos two_pos two_pos lemma mul_le_mul_of_mul_div_le {a b c d : α} (h : a * (b / c) ≤ d) (hc : c > 0) : b * a ≤ d * c := begin rw [← mul_div_assoc] at h, rw [mul_comm b], apply le_mul_of_div_le hc h end lemma div_two_lt_of_pos {a : α} (h : a > 0) : a / 2 < a := suffices a / (1 + 1) < a, begin unfold bit0, assumption end, have ha : a / 2 > 0, from div_pos_of_pos_of_pos h (add_pos zero_lt_one zero_lt_one), calc a / 2 < a / 2 + a / 2 : lt_add_of_pos_left _ ha ... = a : add_halves a lemma div_mul_le_div_mul_of_div_le_div_pos {a b c d e : α} (hb : b ≠ 0) (hd : d ≠ 0) (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin have h₁ := field.div_mul_eq_div_mul_one_div a hb (ne_of_gt he), have h₂ := field.div_mul_eq_div_mul_one_div c hd (ne_of_gt he), rw [h₁, h₂], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end lemma exists_add_lt_and_pos_of_lt {a b : α} (h : b < a) : ∃ c : α, b + c < a ∧ c > 0 := begin apply exists.intro ((a - b) / (1 + 1)), split, {have h2 : a + a > (b + b) + (a - b), calc a + a > b + a : add_lt_add_right h _ ... = b + a + b - b : by rw add_sub_cancel ... = b + b + a - b : by simp ... = (b + b) + (a - b) : by rw add_sub, have h3 : (a + a) / 2 > ((b + b) + (a - b)) / 2, exact div_lt_div_of_lt_of_pos h2 two_pos, rw [one_add_one_eq_two, sub_eq_add_neg], rw [add_self_div_two, ← div_add_div_same, add_self_div_two, sub_eq_add_neg] at h3, exact h3}, exact div_pos_of_pos_of_pos (sub_pos_of_lt h) two_pos end lemma ge_of_forall_ge_sub {a b : α} (h : ∀ ε : α, ε > 0 → a ≥ b - ε) : a ≥ b := begin apply le_of_not_gt, intro hb, cases exists_add_lt_and_pos_of_lt hb with c hc, have hc' := h c (and.right hc), apply (not_le_of_gt (and.left hc)) (le_add_of_sub_right_le hc') end lemma one_div_lt_one_div_of_lt {a b : α} (ha : 0 < a) (h : a < b) : 1 / b < 1 / a := begin apply lt_div_of_mul_lt ha, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_lt_of_pos (lt_trans ha h), rwa [one_mul] end lemma one_div_le_one_div_of_le {a b : α} (ha : 0 < a) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt ha h) (λ h, by rw [h]) lemma one_div_lt_one_div_of_lt_of_neg {a b : α} (hb : b < 0) (h : a < b) : 1 / b < 1 / a := begin apply div_lt_of_mul_gt_of_neg hb, rw [mul_comm, ← div_eq_mul_one_div], apply div_lt_of_mul_gt_of_neg (lt_trans h hb), rwa [one_mul] end lemma one_div_le_one_div_of_le_of_neg {a b : α} (hb : b < 0) (h : a ≤ b) : 1 / b ≤ 1 / a := (lt_or_eq_of_le h).elim (λ h, le_of_lt $ one_div_lt_one_div_of_lt_of_neg hb h) (λ h, by rw [h]) lemma le_of_one_div_le_one_div {a b : α} (h : 0 < a) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt h hn lemma le_of_one_div_le_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a ≤ 1 / b) : b ≤ a := le_of_not_gt $ λ hn, not_lt_of_ge hl $ one_div_lt_one_div_of_lt_of_neg h hn lemma lt_of_one_div_lt_one_div {a b : α} (h : 0 < a) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le h hn lemma lt_of_one_div_lt_one_div_of_neg {a b : α} (h : b < 0) (hl : 1 / a < 1 / b) : b < a := lt_of_not_ge $ λ hn, not_le_of_gt hl $ one_div_le_one_div_of_le_of_neg h hn lemma one_div_le_of_one_div_le_of_pos {a b : α} (ha : a > 0) (h : 1 / a ≤ b) : 1 / b ≤ a := begin rw [← division_ring.one_div_one_div (ne_of_gt ha)], apply one_div_le_one_div_of_le _ h, apply one_div_pos_of_pos ha end lemma one_div_le_of_one_div_le_of_neg {a b : α} (hb : b < 0) (h : 1 / a ≤ b) : 1 / b ≤ a := le_of_not_gt $ λ hl, begin have : a < 0, from lt_trans hl (one_div_neg_of_neg hb), rw ← division_ring.one_div_one_div (ne_of_lt this) at hl, exact not_lt_of_ge h (lt_of_one_div_lt_one_div_of_neg hb hl) end lemma one_lt_one_div {a : α} (h1 : 0 < a) (h2 : a < 1) : 1 < 1 / a := suffices 1 / 1 < 1 / a, by rwa one_div_one at this, one_div_lt_one_div_of_lt h1 h2 lemma one_le_one_div {a : α} (h1 : 0 < a) (h2 : a ≤ 1) : 1 ≤ 1 / a := suffices 1 / 1 ≤ 1 / a, by rwa one_div_one at this, one_div_le_one_div_of_le h1 h2 lemma one_div_lt_neg_one {a : α} (h1 : a < 0) (h2 : -1 < a) : 1 / a < -1 := suffices 1 / a < 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_lt_one_div_of_lt_of_neg h1 h2 lemma one_div_le_neg_one {a : α} (h1 : a < 0) (h2 : -1 ≤ a) : 1 / a ≤ -1 := suffices 1 / a ≤ 1 / -1, by rwa one_div_neg_one_eq_neg_one at this, one_div_le_one_div_of_le_of_neg h1 h2 lemma div_lt_div_of_pos_of_lt_of_pos {a b c : α} (hb : 0 < b) (h : b < a) (hc : 0 < c) : c / a < c / b := begin apply lt_of_sub_neg, rw [div_eq_mul_one_div, div_eq_mul_one_div c b, ← mul_sub_left_distrib], apply mul_neg_of_pos_of_neg, exact hc, apply sub_neg_of_lt, apply one_div_lt_one_div_of_lt; assumption, end end linear_ordered_field class discrete_linear_ordered_field (α : Type u) extends linear_ordered_field α, decidable_linear_ordered_comm_ring α := (inv_zero : inv zero = zero) section discrete_linear_ordered_field variables {α : Type u} instance discrete_linear_ordered_field.to_discrete_field [s : discrete_linear_ordered_field α] : discrete_field α := { has_decidable_eq := @decidable_linear_ordered_comm_ring.decidable_eq α (@discrete_linear_ordered_field.to_decidable_linear_ordered_comm_ring α s), ..s } variables [discrete_linear_ordered_field α] lemma pos_of_one_div_pos {a : α} (h : 0 < 1 / a) : 0 < a := have h1 : 0 < 1 / (1 / a), from one_div_pos_of_pos h, have h2 : 1 / a ≠ 0, from (assume h3 : 1 / a = 0, have h4 : 1 / (1 / a) = 0, from eq.symm h3 ▸ div_zero 1, absurd h4 (ne.symm (ne_of_lt h1))), (division_ring.one_div_one_div (ne_zero_of_one_div_ne_zero h2)) ▸ h1 lemma neg_of_one_div_neg {a : α} (h : 1 / a < 0) : a < 0 := have h1 : 0 < - (1 / a), from neg_pos_of_neg h, have ha : a ≠ 0, from ne_zero_of_one_div_ne_zero (ne_of_lt h), have h2 : 0 < 1 / (-a), from eq.symm (division_ring.one_div_neg_eq_neg_one_div ha) ▸ h1, have h3 : 0 < -a, from pos_of_one_div_pos h2, neg_of_neg_pos h3 lemma div_mul_le_div_mul_of_div_le_div_pos' {a b c d e : α} (h : a / b ≤ c / d) (he : e > 0) : a / (b * e) ≤ c / (d * e) := begin rw [div_mul_eq_div_mul_one_div, div_mul_eq_div_mul_one_div], apply mul_le_mul_of_nonneg_right h, apply le_of_lt, apply one_div_pos_of_pos he end end discrete_linear_ordered_field
2ab7a54a6a77b6b14bfa35d8f0496f3cfefd457a
ba4794a0deca1d2aaa68914cd285d77880907b5c
/src/game/world1/level3.lean
20f20cd6167217277ab0a9ae6bd7f0137f304566
[ "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
4,098
lean
/- We just restarted Lean behind the scenes, so let's re-import the natural numbers, but this time without addition and multiplication. -/ import mynat.definition -- import Peano's definition of the natural numbers {0,1,2,3,4,...} namespace mynat -- hide /- # Tutorial world ## Level 3: Peano's axioms. The import above gives us the type `mynat` of natural numbers. But it also gives us some other things, which we'll take a look at now: * a term `0 : mynat`, interpreted as the number zero. * a function `succ : mynat → mynat`, with `succ n` interpreted as "the number after $n$". * The principle of mathematical induction. These axioms are essentially the axioms isolated by Peano which uniquely characterise the natural numbers (we also need recursion, but we can ignore it for now). The first axiom says that $0$ is a natural number. The second says that there is a `succ` function which eats a number and spits out the number after it, so $\operatorname{succ}(0)=1$, $\operatorname{succ}(1)=2$ and so on. Peano's last axiom is the principle of mathematical induction. This is a deeper fact. It says that if we have infinitely many true/false statements $P(0)$, $P(1)$, $P(2)$ and so on, and if $P(0)$ is true, and if for every natural number $d$ we know that $P(d)$ implies $P(\operatorname{succ}(d))$, then $P(n)$ must be true for every natural number $n$. It's like saying that if you have a long line of dominoes, and if you knock the first one down, and if you know that if a domino falls down then the one after it will fall down too, then you can deduce that all the dominos will fall down. One can also think of it as saying that every natural number can be built by starting at `0` and then applying `succ` a finite number of times. Peano's insights were firstly that these axioms completely characterise the natural numbers, and secondly that these axioms alone can be used to build a whole bunch of other structure on the natural numbers, for example addition, multiplication and so on. This game is all about seeing how far these axioms of Peano can take us. Let's practice our use of the `rw` tactic in the following example. Our hypothesis `h` is a proof that `succ(a) = b` and we want to prove that `succ(succ(a))=succ(b)`. In words, we're going to prove that if `b` is the number after `a` then `succ(b)` is the number after `succ(a)`. Now here's a tricky question. If our goal is `⊢ succ (succ a) = succ b`, and our hypothesis is `h : succ a = b`, then what will the goal change to when we type `rw h,` and hit enter whilst not forgetting the comma? Remember that `rw h` will look for the *left* hand side of `h` in the goal, and will replace it with the *right* hand side. Try and figure out how the goal will change, and then try it. The answer: Lean changed `succ a` into `b`, so the goal became `succ b = succ b`. That goal is of the form `X = X`, so you can prove this new goal with `refl,` on the line after `rw h,`. Don't forget the commas! **Important note** : the tactic `rw` expects a proof afterwards (e.g. `rw h1`). But `refl` is just `refl`. Note also that the system sometimes drops brackets when they're not necessary, and `succ b` just means `succ(b)`. You may be wondering whether we could have just substituted in the definition of `b` and proved the goal that way. To do that, we would want to replace the right hand side of `h` with the left hand side. You do this in Lean by writing `rw ← h`. You get the left-arrow by typing `\l` and then a space. You can just edit your proof and try it. You may also be wondering why we keep writing `succ(b)` instead of `b+1`. This is because we haven't defined addition yet! On the next level, the final level of Tutorial World, we will introduce addition, and then we'll be ready to enter Addition World. -/ /- Lemma : no-side-bar If $\operatorname{succ}(a) = b$, then $$\operatorname{succ}(\operatorname{succ}(a)) = \operatorname{succ}(b).$$ -/ lemma example4 (a b : mynat) (h : succ a = b) : succ(succ(a)) = succ(b) := begin [less_leaky] rw h, refl, end end mynat -- hide
a467e5b747473e0d328374add064b7d3389f4cbc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/algebra/order/liminf_limsup.lean
f0da709bfdc1918825f276ff2b0f0b2170c5eba5
[ "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
20,365
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import algebra.big_operators.intervals import order.liminf_limsup import order.filter.archimedean import topology.algebra.order.basic /-! # Lemmas about liminf and limsup in an order topology. -/ open filter open_locale topological_space classical universes u v variables {α : Type u} {β : Type v} section liminf_limsup section order_closed_topology variables [semilattice_sup α] [topological_space α] [order_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := (is_top_or_exists_gt a).elim (λ h, ⟨a, eventually_of_forall h⟩) (λ ⟨b, hb⟩, ⟨b, ge_mem_nhds hb⟩) lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := (is_bounded_le_nhds a).mono h lemma filter.tendsto.bdd_above_range_of_cofinite {u : β → α} {a : α} (h : tendsto u cofinite (𝓝 a)) : bdd_above (set.range u) := h.is_bounded_under_le.bdd_above_range_of_cofinite lemma filter.tendsto.bdd_above_range {u : ℕ → α} {a : α} (h : tendsto u at_top (𝓝 a)) : bdd_above (set.range u) := h.is_bounded_under_le.bdd_above_range lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := (is_bounded_le_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := h.is_bounded_under_le.is_cobounded_flip lemma is_bounded_le_at_bot (α : Type*) [hα : nonempty α] [preorder α] : (at_bot : filter α).is_bounded (≤) := is_bounded_iff.2 ⟨set.Iic hα.some, mem_at_bot _, hα.some, λ x hx, hx⟩ lemma filter.tendsto.is_bounded_under_le_at_bot {α : Type*} [nonempty α] [preorder α] {f : filter β} {u : β → α} (h : tendsto u f at_bot) : f.is_bounded_under (≤) u := (is_bounded_le_at_bot α).mono h lemma bdd_above_range_of_tendsto_at_top_at_bot {α : Type*} [nonempty α] [semilattice_sup α] {u : ℕ → α} (hx : tendsto u at_top at_bot) : bdd_above (set.range u) := (filter.tendsto.is_bounded_under_le_at_bot hx).bdd_above_range end order_closed_topology section order_closed_topology variables [semilattice_inf α] [topological_space α] [order_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := @is_bounded_le_nhds αᵒᵈ _ _ _ a lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := (is_bounded_ge_nhds a).mono h lemma filter.tendsto.bdd_below_range_of_cofinite {u : β → α} {a : α} (h : tendsto u cofinite (𝓝 a)) : bdd_below (set.range u) := h.is_bounded_under_ge.bdd_below_range_of_cofinite lemma filter.tendsto.bdd_below_range {u : ℕ → α} {a : α} (h : tendsto u at_top (𝓝 a)) : bdd_below (set.range u) := h.is_bounded_under_ge.bdd_below_range lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := (is_bounded_ge_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := h.is_bounded_under_ge.is_cobounded_flip lemma is_bounded_ge_at_top (α : Type*) [hα : nonempty α] [preorder α] : (at_top : filter α).is_bounded (≥) := is_bounded_le_at_bot αᵒᵈ lemma filter.tendsto.is_bounded_under_ge_at_top {α : Type*} [nonempty α] [preorder α] {f : filter β} {u : β → α} (h : tendsto u f at_top) : f.is_bounded_under (≥) u := (is_bounded_ge_at_top α).mono h lemma bdd_below_range_of_tendsto_at_top_at_top {α : Type*} [nonempty α] [semilattice_inf α] {u : ℕ → α} (hx : tendsto u at_top at_top) : bdd_below (set.range u) := (filter.tendsto.is_bounded_under_ge_at_top hx).bdd_below_range end order_closed_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in mem_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_Limsup_lt αᵒᵈ _ variables [topological_space α] [order_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_order.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_eq_of_forall_ge_of_forall_gt_exists_lt (is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_mem_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds αᵒᵈ _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h, have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h, le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds αᵒᵈ _ _ _ /-- If a function has a limit, then its limsup coincides with its limit. -/ theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : limsup u f = a := Limsup_eq_of_le_nhds h /-- If a function has a limit, then its liminf coincides with its limit. -/ theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : liminf u f = a := Liminf_eq_of_le_nhds h /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (hinf : liminf u f = a) (hsup : limsup u f = a) (h : f.is_bounded_under (≤) u . is_bounded_default) (h' : f.is_bounded_under (≥) u . is_bounded_default) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf h h' hsup hinf /-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/ theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α} (hinf : a ≤ liminf u f) (hsup : limsup u f ≤ a) (h : f.is_bounded_under (≤) u . is_bounded_default) (h' : f.is_bounded_under (≥) u . is_bounded_default) : tendsto u f (𝓝 a) := if hf : f = ⊥ then hf.symm ▸ tendsto_bot else by haveI : ne_bot f := ⟨hf⟩; exact tendsto_of_liminf_eq_limsup (le_antisymm (le_trans (liminf_le_limsup h h') hsup) hinf) (le_antisymm hsup (le_trans hinf (liminf_le_limsup h h'))) h h' /-- Assume that, for any `a < b`, a sequence can not be infinitely many times below `a` and above `b`. If it is also ultimately bounded above and below, then it has to converge. This even works if `a` and `b` are restricted to a dense subset. -/ lemma tendsto_of_no_upcrossings [densely_ordered α] {f : filter β} {u : β → α} {s : set α} (hs : dense s) (H : ∀ (a ∈ s) (b ∈ s), a < b → ¬((∃ᶠ n in f, u n < a) ∧ (∃ᶠ n in f, b < u n))) (h : f.is_bounded_under (≤) u . is_bounded_default) (h' : f.is_bounded_under (≥) u . is_bounded_default) : ∃ (c : α), tendsto u f (𝓝 c) := begin by_cases hbot : f = ⊥, { rw hbot, exact ⟨Inf ∅, tendsto_bot⟩ }, haveI : ne_bot f := ⟨hbot⟩, refine ⟨limsup u f, _⟩, apply tendsto_of_le_liminf_of_limsup_le _ le_rfl h h', by_contra' hlt, obtain ⟨a, ⟨⟨la, au⟩, as⟩⟩ : ∃ a, (f.liminf u < a ∧ a < f.limsup u) ∧ a ∈ s := dense_iff_inter_open.1 hs (set.Ioo (f.liminf u) (f.limsup u)) is_open_Ioo (set.nonempty_Ioo.2 hlt), obtain ⟨b, ⟨⟨ab, bu⟩, bs⟩⟩ : ∃ b, (a < b ∧ b < f.limsup u) ∧ b ∈ s := dense_iff_inter_open.1 hs (set.Ioo a (f.limsup u)) is_open_Ioo (set.nonempty_Ioo.2 au), have A : ∃ᶠ n in f, u n < a := frequently_lt_of_liminf_lt (is_bounded.is_cobounded_ge h) la, have B : ∃ᶠ n in f, b < u n := frequently_lt_of_lt_limsup (is_bounded.is_cobounded_le h') bu, exact H a as b bs ab ⟨A, B⟩, end end conditionally_complete_linear_order end liminf_limsup section monotone variables {ι R S : Type*} {F : filter ι} [ne_bot F] [complete_linear_order R] [topological_space R] [order_topology R] [complete_linear_order S] [topological_space S] [order_topology S] /-- An antitone function between complete linear ordered spaces sends a `filter.Limsup` to the `filter.liminf` of the image if it is continuous at the `Limsup`. -/ lemma antitone.map_Limsup_of_continuous_at {F : filter R} [ne_bot F] {f : R → S} (f_decr : antitone f) (f_cont : continuous_at f (F.Limsup)) : f (F.Limsup) = F.liminf f := begin apply le_antisymm, { have A : {a : R | ∀ᶠ (n : R) in F, n ≤ a}.nonempty, from ⟨⊤, by simp⟩, rw [Limsup, (f_decr.map_Inf_of_continuous_at' f_cont A)], apply le_of_forall_lt, assume c hc, simp only [liminf, Liminf, lt_Sup_iff, eventually_map, set.mem_set_of_eq, exists_prop, set.mem_image, exists_exists_and_eq_and] at hc ⊢, rcases hc with ⟨d, hd, h'd⟩, refine ⟨f d, _, h'd⟩, filter_upwards [hd] with x hx using f_decr hx }, { rcases eq_or_lt_of_le (bot_le : ⊥ ≤ F.Limsup) with h|Limsup_ne_bot, { rw ← h, apply liminf_le_of_frequently_le, apply frequently_of_forall, assume x, exact f_decr bot_le }, by_cases h' : ∃ c, c < F.Limsup ∧ set.Ioo c F.Limsup = ∅, { rcases h' with ⟨c, c_lt, hc⟩, have B : ∃ᶠ n in F, F.Limsup ≤ n, { apply (frequently_lt_of_lt_Limsup (by is_bounded_default) c_lt).mono, assume x hx, by_contra', have : (set.Ioo c F.Limsup).nonempty := ⟨x, ⟨hx, this⟩⟩, simpa [hc] }, apply liminf_le_of_frequently_le, exact B.mono (λ x hx, f_decr hx) }, by_contra' H, obtain ⟨l, l_lt, h'l⟩ : ∃ l < F.Limsup, set.Ioc l F.Limsup ⊆ {x : R | f x < F.liminf f}, from exists_Ioc_subset_of_mem_nhds ((tendsto_order.1 f_cont.tendsto).2 _ H) ⟨⊥, Limsup_ne_bot⟩, obtain ⟨m, l_m, m_lt⟩ : (set.Ioo l F.Limsup).nonempty, { contrapose! h', refine ⟨l, l_lt, by rwa set.not_nonempty_iff_eq_empty at h'⟩ }, have B : F.liminf f ≤ f m, { apply liminf_le_of_frequently_le, apply (frequently_lt_of_lt_Limsup (by is_bounded_default) m_lt).mono, assume x hx, exact f_decr hx.le }, have I : f m < F.liminf f := h'l ⟨l_m, m_lt.le⟩, exact lt_irrefl _ (B.trans_lt I) } end /-- A continuous antitone function between complete linear ordered spaces sends a `filter.limsup` to the `filter.liminf` of the images. -/ lemma antitone.map_limsup_of_continuous_at {f : R → S} (f_decr : antitone f) (a : ι → R) (f_cont : continuous_at f (F.limsup a)) : f (F.limsup a) = F.liminf (f ∘ a) := f_decr.map_Limsup_of_continuous_at f_cont /-- An antitone function between complete linear ordered spaces sends a `filter.Liminf` to the `filter.limsup` of the image if it is continuous at the `Liminf`. -/ lemma antitone.map_Liminf_of_continuous_at {F : filter R} [ne_bot F] {f : R → S} (f_decr : antitone f) (f_cont : continuous_at f (F.Liminf)) : f (F.Liminf) = F.limsup f := @antitone.map_Limsup_of_continuous_at (order_dual R) (order_dual S) _ _ _ _ _ _ _ _ f f_decr.dual f_cont /-- A continuous antitone function between complete linear ordered spaces sends a `filter.liminf` to the `filter.limsup` of the images. -/ lemma antitone.map_liminf_of_continuous_at {f : R → S} (f_decr : antitone f) (a : ι → R) (f_cont : continuous_at f (F.liminf a)) : f (F.liminf a) = F.limsup (f ∘ a) := f_decr.map_Liminf_of_continuous_at f_cont /-- A monotone function between complete linear ordered spaces sends a `filter.Limsup` to the `filter.limsup` of the image if it is continuous at the `Limsup`. -/ lemma monotone.map_Limsup_of_continuous_at {F : filter R} [ne_bot F] {f : R → S} (f_incr : monotone f) (f_cont : continuous_at f (F.Limsup)) : f (F.Limsup) = F.limsup f := @antitone.map_Limsup_of_continuous_at R (order_dual S) _ _ _ _ _ _ _ _ f f_incr f_cont /-- A continuous monotone function between complete linear ordered spaces sends a `filter.limsup` to the `filter.limsup` of the images. -/ lemma monotone.map_limsup_of_continuous_at {f : R → S} (f_incr : monotone f) (a : ι → R) (f_cont : continuous_at f (F.limsup a)) : f (F.limsup a) = F.limsup (f ∘ a) := f_incr.map_Limsup_of_continuous_at f_cont /-- A monotone function between complete linear ordered spaces sends a `filter.Liminf` to the `filter.liminf` of the image if it is continuous at the `Liminf`. -/ lemma monotone.map_Liminf_of_continuous_at {F : filter R} [ne_bot F] {f : R → S} (f_incr : monotone f) (f_cont : continuous_at f (F.Liminf)) : f (F.Liminf) = F.liminf f := @antitone.map_Liminf_of_continuous_at R (order_dual S) _ _ _ _ _ _ _ _ f f_incr f_cont /-- A continuous monotone function between complete linear ordered spaces sends a `filter.liminf` to the `filter.liminf` of the images. -/ lemma monotone.map_liminf_of_continuous_at {f : R → S} (f_incr : monotone f) (a : ι → R) (f_cont : continuous_at f (F.liminf a)) : f (F.liminf a) = F.liminf (f ∘ a) := f_incr.map_Liminf_of_continuous_at f_cont end monotone section infi_and_supr open_locale topological_space open filter set variables {ι : Type*} {R : Type*} [complete_linear_order R] [topological_space R] [order_topology R] lemma infi_eq_of_forall_le_of_tendsto {x : R} {as : ι → R} (x_le : ∀ i, x ≤ as i) {F : filter ι} [filter.ne_bot F] (as_lim : filter.tendsto as F (𝓝 x)) : (⨅ i, as i) = x := begin refine infi_eq_of_forall_ge_of_forall_gt_exists_lt (λ i, x_le i) _, apply λ w x_lt_w, ‹filter.ne_bot F›.nonempty_of_mem (eventually_lt_of_tendsto_lt x_lt_w as_lim), end lemma supr_eq_of_forall_le_of_tendsto {x : R} {as : ι → R} (le_x : ∀ i, as i ≤ x) {F : filter ι} [filter.ne_bot F] (as_lim : filter.tendsto as F (𝓝 x)) : (⨆ i, as i) = x := @infi_eq_of_forall_le_of_tendsto ι (order_dual R) _ _ _ x as le_x F _ as_lim lemma Union_Ici_eq_Ioi_of_lt_of_tendsto {ι : Type*} (x : R) {as : ι → R} (x_lt : ∀ i, x < as i) {F : filter ι} [filter.ne_bot F] (as_lim : filter.tendsto as F (𝓝 x)) : (⋃ (i : ι), Ici (as i)) = Ioi x := begin have obs : x ∉ range as, { intro maybe_x_is, rcases mem_range.mp maybe_x_is with ⟨i, hi⟩, simpa only [hi, lt_self_iff_false] using x_lt i, } , rw ← infi_eq_of_forall_le_of_tendsto (λ i, (x_lt i).le) as_lim at *, exact Union_Ici_eq_Ioi_infi obs, end lemma Union_Iic_eq_Iio_of_lt_of_tendsto {ι : Type*} (x : R) {as : ι → R} (lt_x : ∀ i, as i < x) {F : filter ι} [filter.ne_bot F] (as_lim : filter.tendsto as F (𝓝 x)) : (⋃ (i : ι), Iic (as i)) = Iio x := @Union_Ici_eq_Ioi_of_lt_of_tendsto (order_dual R) _ _ _ ι x as lt_x F _ as_lim end infi_and_supr section indicator open_locale big_operators lemma limsup_eq_tendsto_sum_indicator_nat_at_top (s : ℕ → set α) : limsup s at_top = {ω | tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : α → ℕ) ω) at_top at_top} := begin ext ω, simp only [limsup_eq_infi_supr_of_nat, ge_iff_le, set.supr_eq_Union, set.infi_eq_Inter, set.mem_Inter, set.mem_Union, exists_prop], split, { intro hω, refine tendsto_at_top_at_top_of_monotone' (λ n m hnm, finset.sum_mono_set_of_nonneg (λ i, set.indicator_nonneg (λ _ _, zero_le_one) _) (finset.range_mono hnm)) _, rintro ⟨i, h⟩, simp only [mem_upper_bounds, set.mem_range, forall_exists_index, forall_apply_eq_imp_iff'] at h, induction i with k hk, { obtain ⟨j, hj₁, hj₂⟩ := hω 1, refine not_lt.2 (h $ j + 1) (lt_of_le_of_lt (finset.sum_const_zero.symm : 0 = ∑ k in finset.range (j + 1), 0).le _), refine finset.sum_lt_sum (λ m _, set.indicator_nonneg (λ _ _, zero_le_one) _) ⟨j - 1, finset.mem_range.2 (lt_of_le_of_lt (nat.sub_le _ _) j.lt_succ_self), _⟩, rw [nat.sub_add_cancel hj₁, set.indicator_of_mem hj₂], exact zero_lt_one }, { rw imp_false at hk, push_neg at hk, obtain ⟨i, hi⟩ := hk, obtain ⟨j, hj₁, hj₂⟩ := hω (i + 1), replace hi : ∑ k in finset.range i, (s (k + 1)).indicator 1 ω = k + 1 := le_antisymm (h i) hi, refine not_lt.2 (h $ j + 1) _, rw [← finset.sum_range_add_sum_Ico _ (i.le_succ.trans (hj₁.trans j.le_succ)), hi], refine lt_add_of_pos_right _ _, rw (finset.sum_const_zero.symm : 0 = ∑ k in finset.Ico i (j + 1), 0), refine finset.sum_lt_sum (λ m _, set.indicator_nonneg (λ _ _, zero_le_one) _) ⟨j - 1, finset.mem_Ico.2 ⟨(nat.le_sub_iff_right (le_trans ((le_add_iff_nonneg_left _).2 zero_le') hj₁)).2 hj₁, lt_of_le_of_lt (nat.sub_le _ _) j.lt_succ_self⟩, _⟩, rw [nat.sub_add_cancel (le_trans ((le_add_iff_nonneg_left _).2 zero_le') hj₁), set.indicator_of_mem hj₂], exact zero_lt_one } }, { rintro hω i, rw [set.mem_set_of_eq, tendsto_at_top_at_top] at hω, by_contra hcon, push_neg at hcon, obtain ⟨j, h⟩ := hω (i + 1), have : ∑ k in finset.range j, (s (k + 1)).indicator 1 ω ≤ i, { have hle : ∀ j ≤ i, ∑ k in finset.range j, (s (k + 1)).indicator 1 ω ≤ i, { refine λ j hij, (finset.sum_le_card_nsmul _ _ _ _ : _ ≤ (finset.range j).card • 1).trans _, { exact λ m hm, set.indicator_apply_le' (λ _, le_rfl) (λ _, zero_le_one) }, { simpa only [finset.card_range, smul_eq_mul, mul_one] } }, by_cases hij : j < i, { exact hle _ hij.le }, { rw ← finset.sum_range_add_sum_Ico _ (not_lt.1 hij), suffices : ∑ k in finset.Ico i j, (s (k + 1)).indicator 1 ω = 0, { rw [this, add_zero], exact hle _ le_rfl }, rw finset.sum_eq_zero (λ m hm, _), exact set.indicator_of_not_mem (hcon _ $ (finset.mem_Ico.1 hm).1.trans m.le_succ) _ } }, exact not_le.2 (lt_of_lt_of_le i.lt_succ_self $ h _ le_rfl) this } end lemma limsup_eq_tendsto_sum_indicator_at_top (R : Type*) [strict_ordered_semiring R] [archimedean R] (s : ℕ → set α) : limsup s at_top = {ω | tendsto (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : α → R) ω) at_top at_top} := begin rw limsup_eq_tendsto_sum_indicator_nat_at_top s, ext ω, simp only [set.mem_set_of_eq], rw (_ : (λ n, ∑ k in finset.range n, (s (k + 1)).indicator (1 : α → R) ω) = (λ n, ↑(∑ k in finset.range n, (s (k + 1)).indicator (1 : α → ℕ) ω))), { exact tendsto_coe_nat_at_top_iff.symm }, { ext n, simp only [set.indicator, pi.one_apply, finset.sum_boole, nat.cast_id] } end end indicator
f5f6c8ee0fc3a33cfc14fdf1e0f0c2e635768875
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/measure/hausdorff.lean
adfd81ecef870928fe29217def4368a9419f53cc
[ "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
43,591
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 topology.metric_space.metric_separated import measure_theory.constructions.borel_space import measure_theory.measure.lebesgue import analysis.special_functions.pow import topology.metric_space.holder import data.equiv.list /-! # Hausdorff measure and metric (outer) measures In this file we define the `d`-dimensional Hausdorff measure on an (extended) metric space `X` and the Hausdorff dimension of a set in an (extended) metric space. Let `μ d δ` be the maximal outer measure such that `μ d δ s ≤ (emetric.diam s) ^ d` for every set of diameter less than `δ`. Then the Hausdorff measure `μH[d] s` of `s` is defined as `⨆ δ > 0, μ d δ s`. By Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, this is a Borel measure on `X`. The value of `μH[d]`, `d > 0`, on a set `s` (measurable or not) is given by ``` μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, emetric.diam (t n) ^ d ``` For every set `s` for any `d < d'` we have either `μH[d] s = ∞` or `μH[d'] s = 0`, see `measure_theory.measure.hausdorff_measure_zero_or_top`. In `topology.metric_space.hausdorff_dimension` we use this fact to define the Hausdorff dimension `dimH` of a set in an (extended) metric space. We also define two generalizations of the Hausdorff measure. In one generalization (see `measure_theory.measure.mk_metric`) we take any function `m (diam s)` instead of `(diam s) ^ d`. In an even more general definition (see `measure_theory.measure.mk_metric'`) we use any function of `m : set X → ℝ≥0∞`. Some authors start with a partial function `m` defined only on some sets `s : set X` (e.g., only on balls or only on measurable sets). This is equivalent to our definition applied to `measure_theory.extend m`. We also define a predicate `measure_theory.outer_measure.is_metric` which says that an outer measure is additive on metric separated pairs of sets: `μ (s ∪ t) = μ s + μ t` provided that `⨅ (x ∈ s) (y ∈ t), edist x y ≠ 0`. This is the property required for the Caratheodory theorem `measure_theory.outer_measure.is_metric.borel_le_caratheodory`, so we prove this theorem for any metric outer measure, then prove that outer measures constructed using `mk_metric'` are metric outer measures. ## Main definitions * `measure_theory.outer_measure.is_metric`: an outer measure `μ` is called *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s` and `t`. A metric outer measure in a Borel extended metric space is guaranteed to satisfy the Caratheodory condition, see `measure_theory.outer_measure.is_metric.borel_le_caratheodory`. * `measure_theory.outer_measure.mk_metric'` and its particular case `measure_theory.outer_measure.mk_metric`: a construction of an outer measure that is guaranteed to be metric. Both constructions are generalizations of the Hausdorff measure. The same measures interpreted as Borel measures are called `measure_theory.measure.mk_metric'` and `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure` a.k.a. `μH[d]`: the `d`-dimensional Hausdorff measure. There are many definitions of the Hausdorff measure that differ from each other by a multiplicative constant. We put `μH[d] s = ⨆ r > 0, ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, emetric.diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬set.subsingleton (t n)), (emetric.diam (t n)) ^ d`, see `measure_theory.measure.hausdorff_measure_apply'`. In the most interesting case `0 < d` one can omit the `⨆ (ht : ¬set.subsingleton (t n))` part. ## Main statements ### Basic properties * `measure_theory.outer_measure.is_metric.borel_le_caratheodory`: if `μ` is a metric outer measure on an extended metric space `X` (that is, it is additive on pairs of metric separated sets), then every Borel set is Caratheodory measurable (hence, `μ` defines an actual `measure_theory.measure`). See also `measure_theory.measure.mk_metric`. * `measure_theory.measure.hausdorff_measure_mono`: `μH[d] s` is an antitone function of `d`. * `measure_theory.measure.hausdorff_measure_zero_or_top`: if `d₁ < d₂`, then for any `s`, either `μH[d₂] s = 0` or `μH[d₁] s = ∞`. Together with the previous lemma, this means that `μH[d] s` is equal to infinity on some ray `(-∞, D)` and is equal to zero on `(D, +∞)`, where `D` is a possibly infinite number called the *Hausdorff dimension* of `s`; `μH[D] s` can be zero, infinity, or anything in between. * `measure_theory.measure.no_atoms_hausdorff`: Hausdorff measure has no atoms. ### Hausdorff measure in `ℝⁿ` * `measure_theory.hausdorff_measure_pi_real`: for a nonempty `ι`, `μH[card ι]` on `ι → ℝ` equals Lebesgue measure. ## Notations We use the following notation localized in `measure_theory`. - `μH[d]` : `measure_theory.measure.hausdorff_measure d` ## Implementation notes There are a few similar constructions called the `d`-dimensional Hausdorff measure. E.g., some sources only allow coverings by balls and use `r ^ d` instead of `(diam s) ^ d`. While these construction lead to different Hausdorff measures, they lead to the same notion of the Hausdorff dimension. Some sources define the `0`-dimensional Hausdorff measure to be the counting measure. We define it to be zero on subsingletons because this way we can have a `measure.has_no_atoms (measure.hausdorff_measure d)` instance. ## TODO * prove that `1`-dimensional Hausdorff measure on `ℝ` equals `volume`; * prove a similar statement for `ℝ × ℝ`. ## References * [Herbert Federer, Geometric Measure Theory, Chapter 2.10][Federer1996] ## Tags Hausdorff measure, measure, metric measure -/ open_locale nnreal ennreal topological_space big_operators open emetric set function filter encodable finite_dimensional topological_space noncomputable theory variables {ι X Y : Type*} [emetric_space X] [emetric_space Y] namespace measure_theory namespace outer_measure /-! ### Metric outer measures In this section we define metric outer measures and prove Caratheodory theorem: a metric outer measure has the Caratheodory property. -/ /-- We say that an outer measure `μ` in an (e)metric space is *metric* if `μ (s ∪ t) = μ s + μ t` for any two metric separated sets `s`, `t`. -/ def is_metric (μ : outer_measure X) : Prop := ∀ (s t : set X), is_metric_separated s t → μ (s ∪ t) = μ s + μ t namespace is_metric variables {μ : outer_measure X} /-- A metric outer measure is additive on a finite set of pairwise metric separated sets. -/ lemma finset_Union_of_pairwise_separated (hm : is_metric μ) {I : finset ι} {s : ι → set X} (hI : ∀ (i ∈ I) (j ∈ I), i ≠ j → is_metric_separated (s i) (s j)) : μ (⋃ i ∈ I, s i) = ∑ i in I, μ (s i) := begin classical, induction I using finset.induction_on with i I hiI ihI hI, { simp }, simp only [finset.mem_insert] at hI, rw [finset.set_bUnion_insert, hm, ihI, finset.sum_insert hiI], exacts [λ i hi j hj hij, (hI i (or.inr hi) j (or.inr hj) hij), is_metric_separated.finset_Union_right (λ j hj, hI i (or.inl rfl) j (or.inr hj) (ne_of_mem_of_not_mem hj hiI).symm)] end /-- Caratheodory theorem. If `m` is a metric outer measure, then every Borel measurable set `t` is Caratheodory measurable: for any (not necessarily measurable) set `s` we have `μ (s ∩ t) + μ (s \ t) = μ s`. -/ lemma borel_le_caratheodory (hm : is_metric μ) : borel X ≤ μ.caratheodory := begin rw [borel_eq_generate_from_is_closed], refine measurable_space.generate_from_le (λ t ht, μ.is_caratheodory_iff_le.2 $ λ s, _), set S : ℕ → set X := λ n, {x ∈ s | (↑n)⁻¹ ≤ inf_edist x t}, have n0 : ∀ {n : ℕ}, (n⁻¹ : ℝ≥0∞) ≠ 0, from λ n, ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top, have Ssep : ∀ n, is_metric_separated (S n) t, from λ n, ⟨n⁻¹, n0, λ x hx y hy, hx.2.trans $ inf_edist_le_edist_of_mem hy⟩, have Ssep' : ∀ n, is_metric_separated (S n) (s ∩ t), from λ n, (Ssep n).mono subset.rfl (inter_subset_right _ _), have S_sub : ∀ n, S n ⊆ s \ t, from λ n, subset_inter (inter_subset_left _ _) (Ssep n).subset_compl_right, have hSs : ∀ n, μ (s ∩ t) + μ (S n) ≤ μ s, from λ n, calc μ (s ∩ t) + μ (S n) = μ (s ∩ t ∪ S n) : eq.symm $ hm _ _ $ (Ssep' n).symm ... ≤ μ (s ∩ t ∪ s \ t) : by { mono*, exact le_rfl } ... = μ s : by rw [inter_union_diff], have Union_S : (⋃ n, S n) = s \ t, { refine subset.antisymm (Union_subset S_sub) _, rintro x ⟨hxs, hxt⟩, rw mem_iff_inf_edist_zero_of_closed ht at hxt, rcases ennreal.exists_inv_nat_lt hxt with ⟨n, hn⟩, exact mem_Union.2 ⟨n, hxs, hn.le⟩ }, /- Now we have `∀ n, μ (s ∩ t) + μ (S n) ≤ μ s` and we need to prove `μ (s ∩ t) + μ (⋃ n, S n) ≤ μ s`. We can't pass to the limit because `μ` is only an outer measure. -/ by_cases htop : μ (s \ t) = ∞, { rw [htop, ennreal.add_top, ← htop], exact μ.mono (diff_subset _ _) }, suffices : μ (⋃ n, S n) ≤ ⨆ n, μ (S n), calc μ (s ∩ t) + μ (s \ t) = μ (s ∩ t) + μ (⋃ n, S n) : by rw Union_S ... ≤ μ (s ∩ t) + ⨆ n, μ (S n) : add_le_add le_rfl this ... = ⨆ n, μ (s ∩ t) + μ (S n) : ennreal.add_supr ... ≤ μ s : supr_le hSs, /- It suffices to show that `∑' k, μ (S (k + 1) \ S k) ≠ ∞`. Indeed, if we have this, then for all `N` we have `μ (⋃ n, S n) ≤ μ (S N) + ∑' k, m (S (N + k + 1) \ S (N + k))` and the second term tends to zero, see `outer_measure.Union_nat_of_monotone_of_tsum_ne_top` for details. -/ have : ∀ n, S n ⊆ S (n + 1), from λ n x hx, ⟨hx.1, le_trans (ennreal.inv_le_inv.2 $ ennreal.coe_nat_le_coe_nat.2 n.le_succ) hx.2⟩, refine (μ.Union_nat_of_monotone_of_tsum_ne_top this _).le, clear this, /- While the sets `S (k + 1) \ S k` are not pairwise metric separated, the sets in each subsequence `S (2 * k + 1) \ S (2 * k)` and `S (2 * k + 2) \ S (2 * k)` are metric separated, so `m` is additive on each of those sequences. -/ rw [← tsum_even_add_odd ennreal.summable ennreal.summable, ennreal.add_ne_top], suffices : ∀ a, (∑' (k : ℕ), μ (S (2 * k + 1 + a) \ S (2 * k + a))) ≠ ∞, from ⟨by simpa using this 0, by simpa using this 1⟩, refine λ r, ne_top_of_le_ne_top htop _, rw [← Union_S, ennreal.tsum_eq_supr_nat, supr_le_iff], intro n, rw [← hm.finset_Union_of_pairwise_separated], { exact μ.mono (Union_subset $ λ i, Union_subset $ λ hi x hx, mem_Union.2 ⟨_, hx.1⟩) }, suffices : ∀ i j, i < j → is_metric_separated (S (2 * i + 1 + r)) (s \ S (2 * j + r)), from λ i _ j _ hij, hij.lt_or_lt.elim (λ h, (this i j h).mono (inter_subset_left _ _) (λ x hx, ⟨hx.1.1, hx.2⟩)) (λ h, (this j i h).symm.mono (λ x hx, ⟨hx.1.1, hx.2⟩) (inter_subset_left _ _)), intros i j hj, have A : ((↑(2 * j + r))⁻¹ : ℝ≥0∞) < (↑(2 * i + 1 + r))⁻¹, by { rw [ennreal.inv_lt_inv, ennreal.coe_nat_lt_coe_nat], linarith }, refine ⟨(↑(2 * i + 1 + r))⁻¹ - (↑(2 * j + r))⁻¹, by simpa using A, λ x hx y hy, _⟩, have : inf_edist y t < (↑(2 * j + r))⁻¹, from not_le.1 (λ hle, hy.2 ⟨hy.1, hle⟩), rcases exists_edist_lt_of_inf_edist_lt this with ⟨z, hzt, hyz⟩, have hxz : (↑(2 * i + 1 + r))⁻¹ ≤ edist x z, from le_inf_edist.1 hx.2 _ hzt, apply ennreal.le_of_add_le_add_right hyz.ne_top, refine le_trans _ (edist_triangle _ _ _), refine (add_le_add le_rfl hyz.le).trans (eq.trans_le _ hxz), rw [tsub_add_cancel_of_le A.le] end lemma le_caratheodory [measurable_space X] [borel_space X] (hm : is_metric μ) : ‹measurable_space X› ≤ μ.caratheodory := by { rw @borel_space.measurable_eq X _ _, exact hm.borel_le_caratheodory } end is_metric /-! ### Constructors of metric outer measures In this section we provide constructors `measure_theory.outer_measure.mk_metric'` and `measure_theory.outer_measure.mk_metric` and prove that these outer measures are metric outer measures. We also prove basic lemmas about `map`/`comap` of these measures. -/ /-- Auxiliary definition for `outer_measure.mk_metric'`: given a function on sets `m : set X → ℝ≥0∞`, returns the maximal outer measure `μ` such that `μ s ≤ m s` for any set `s` of diameter at most `r`.-/ def mk_metric'.pre (m : set X → ℝ≥0∞) (r : ℝ≥0∞) : outer_measure X := bounded_by $ extend (λ s (hs : diam s ≤ r), m s) /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `mk_metric'.pre m r` over `r > 0`. Equivalently, it is the limit of `mk_metric'.pre m r` as `r` tends to zero from the right. -/ def mk_metric' (m : set X → ℝ≥0∞) : outer_measure X := ⨆ r > 0, mk_metric'.pre m r /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞` and `r > 0`, let `μ r` be the maximal outer measure such that `μ s = 0` on subsingletons and `μ s ≤ m (emetric.diam s)` whenever `emetric.diam s < r`. Then `mk_metric m = ⨆ r > 0, μ r`. We add `⨆ (hs : ¬s.subsingleton)` to ensure that in the case `m x = x ^ d` the definition gives the expected result for `d = 0`. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : outer_measure X := mk_metric' (λ s, ⨆ (hs : ¬s.subsingleton), m (diam s)) namespace mk_metric' variables {m : set X → ℝ≥0∞} {r : ℝ≥0∞} {μ : outer_measure X} {s : set X} lemma le_pre : μ ≤ pre m r ↔ ∀ s : set X, diam s ≤ r → μ s ≤ m s := by simp only [pre, le_bounded_by, extend, le_infi_iff] lemma pre_le (hs : diam s ≤ r) : pre m r s ≤ m s := (bounded_by_le _).trans $ infi_le _ hs lemma mono_pre (m : set X → ℝ≥0∞) {r r' : ℝ≥0∞} (h : r ≤ r') : pre m r' ≤ pre m r := le_pre.2 $ λ s hs, pre_le (hs.trans h) lemma mono_pre_nat (m : set X → ℝ≥0∞) : monotone (λ k : ℕ, pre m k⁻¹) := λ k l h, le_pre.2 $ λ s hs, pre_le (hs.trans $ by simpa) lemma tendsto_pre (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ r, pre m r s) (𝓝[Ioi 0] 0) (𝓝 $ mk_metric' m s) := begin rw [← map_coe_Ioi_at_bot, tendsto_map'_iff], simp only [mk_metric', outer_measure.supr_apply, supr_subtype'], exact tendsto_at_bot_supr (λ r r' hr, mono_pre _ hr _) end lemma tendsto_pre_nat (m : set X → ℝ≥0∞) (s : set X) : tendsto (λ n : ℕ, pre m n⁻¹ s) at_top (𝓝 $ mk_metric' m s) := begin refine (tendsto_pre m s).comp (tendsto_inf.2 ⟨ennreal.tendsto_inv_nat_nhds_zero, _⟩), refine tendsto_principal.2 (eventually_of_forall $ λ n, _), simp end lemma eq_supr_nat (m : set X → ℝ≥0∞) : mk_metric' m = ⨆ n : ℕ, mk_metric'.pre m n⁻¹ := begin ext1 s, rw supr_apply, refine tendsto_nhds_unique (mk_metric'.tendsto_pre_nat m s) (tendsto_at_top_supr $ λ k l hkl, mk_metric'.mono_pre_nat m hkl s) end /-- `measure_theory.outer_measure.mk_metric'.pre m r` is a trimmed measure provided that `m (closure s) = m s` for any set `s`. -/ lemma trim_pre [measurable_space X] [opens_measurable_space X] (m : set X → ℝ≥0∞) (hcl : ∀ s, m (closure s) = m s) (r : ℝ≥0∞) : (pre m r).trim = pre m r := begin refine le_antisymm (le_pre.2 $ λ s hs, _) (le_trim _), rw trim_eq_infi, refine (infi_le_of_le (closure s) $ infi_le_of_le subset_closure $ infi_le_of_le measurable_set_closure ((pre_le _).trans_eq (hcl _))), rwa diam_closure end end mk_metric' /-- An outer measure constructed using `outer_measure.mk_metric'` is a metric outer measure. -/ lemma mk_metric'_is_metric (m : set X → ℝ≥0∞) : (mk_metric' m).is_metric := begin rintros s t ⟨r, r0, hr⟩, refine tendsto_nhds_unique_of_eventually_eq (mk_metric'.tendsto_pre _ _) ((mk_metric'.tendsto_pre _ _).add (mk_metric'.tendsto_pre _ _)) _, rw [← pos_iff_ne_zero] at r0, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, r0⟩], rintro ε ⟨ε0, εr⟩, refine bounded_by_union_of_top_of_nonempty_inter _, rintro u ⟨x, hxs, hxu⟩ ⟨y, hyt, hyu⟩, have : ε < diam u, from εr.trans_le ((hr x hxs y hyt).trans $ edist_le_diam_of_mem hxu hyu), exact infi_eq_top.2 (λ h, (this.not_le h).elim) end /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : outer_measure X) ≤ c • mk_metric m₂ := begin classical, rcases (mem_nhds_within_Ioi_iff_exists_Ioo_subset' ennreal.zero_lt_one).1 hle with ⟨r, hr0, hr⟩, refine λ s, le_of_tendsto_of_tendsto (mk_metric'.tendsto_pre _ s) (ennreal.tendsto.const_mul (mk_metric'.tendsto_pre _ s) (or.inr hc)) (mem_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_rfl, hr0⟩) (λ r' hr', _)), simp only [mem_set_of_eq, mk_metric'.pre], rw [← smul_apply, smul_bounded_by hc], refine le_bounded_by.2 (λ t, (bounded_by_le _).trans _) _, simp only [smul_eq_mul, pi.smul_apply, extend, infi_eq_if], split_ifs with ht ht, { refine supr_le (λ ht₁, _), rw [supr_eq_if, if_pos ht₁], refine hr ⟨_, ht.trans_lt hr'.2⟩, exact pos_iff_ne_zero.2 (mt diam_eq_zero_iff.1 ht₁) }, { simp [h0] } end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : outer_measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } lemma isometry_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : comap f (mk_metric m) = mk_metric m := begin simp only [mk_metric, mk_metric', mk_metric'.pre, induced_outer_measure, comap_supr], refine supr_congr id surjective_id (λ ε, supr_congr id surjective_id $ λ hε, _), rw comap_bounded_by _ (H.imp (λ h_mono, _) id), { congr' with s : 1, apply extend_congr, { simp [hf.ediam_image] }, { intros, simp [hf.injective.subsingleton_image_iff, hf.ediam_image] } }, { refine λ s t hst, infi_le_infi2 (λ ht, ⟨(diam_mono hst).trans ht, supr_le $ λ hs, _⟩), have ht : ¬(t : set Y).subsingleton, from λ ht, hs (ht.mono hst), refine (@h_mono ⟨_, mt diam_eq_zero_iff.1 hs⟩ ⟨_, mt diam_eq_zero_iff.1 ht⟩ (diam_mono hst)).trans _, exact le_supr (λ h : ¬(t : set Y).subsingleton, m (diam (t : set Y))) ht } end lemma isometry_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) {f : X → Y} (hf : isometry f) (H : monotone (λ d : {d : ℝ≥0∞ | d ≠ 0}, m d) ∨ surjective f) : map f (mk_metric m) = restrict (range f) (mk_metric m) := by rw [← isometry_comap_mk_metric _ hf H, map_comap] lemma isometric_comap_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : comap f (mk_metric m) = mk_metric m := isometry_comap_mk_metric _ f.isometry (or.inr f.surjective) lemma isometric_map_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (f : X ≃ᵢ Y) : map f (mk_metric m) = mk_metric m := by rw [← isometric_comap_mk_metric _ f, map_comap_of_surjective f.surjective] lemma trim_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : outer_measure X).trim = mk_metric m := begin simp only [mk_metric, mk_metric'.eq_supr_nat, trim_supr], congr' 1 with n : 1, refine mk_metric'.trim_pre _ (λ s, _) _, simp end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : outer_measure X) (hμ : ∀ x, μ {x} = 0) (r : ℝ≥0∞) (h0 : 0 < r) (hr : ∀ s, diam s ≤ r → ¬s.subsingleton → μ s ≤ m (diam s)) : μ ≤ mk_metric m := le_bsupr_of_le r h0 $ mk_metric'.le_pre.2 $ λ s hs, begin by_cases h : s.subsingleton, exacts [h.induction_on (μ.empty'.trans_le (zero_le _)) (λ x, ((hμ x).trans_le (zero_le _))), le_supr_of_le h (hr _ hs h)] end end outer_measure /-! ### Metric measures In this section we use `measure_theory.outer_measure.to_measure` and theorems about `measure_theory.outer_measure.mk_metric'`/`measure_theory.outer_measure.mk_metric` to define `measure_theory.measure.mk_metric'`/`measure_theory.measure.mk_metric`. We also restate some lemmas about metric outer measures for metric measures. -/ namespace measure variables [measurable_space X] [borel_space X] /-- Given a function `m : set X → ℝ≥0∞`, `mk_metric' m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all `s`. While each `μ r` is an *outer* measure, the supremum is a measure. -/ def mk_metric' (m : set X → ℝ≥0∞) : measure X := (outer_measure.mk_metric' m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory /-- Given a function `m : ℝ≥0∞ → ℝ≥0∞`, `mk_metric m` is the supremum of `μ r` over `r > 0`, where `μ r` is the maximal outer measure `μ` such that `μ s ≤ m s` for all sets `s` that contain at least two points. While each `mk_metric'.pre` is an *outer* measure, the supremum is a measure. -/ def mk_metric (m : ℝ≥0∞ → ℝ≥0∞) : measure X := (outer_measure.mk_metric m).to_measure (outer_measure.mk_metric'_is_metric _).le_caratheodory @[simp] lemma mk_metric'_to_outer_measure (m : set X → ℝ≥0∞) : (mk_metric' m).to_outer_measure = (outer_measure.mk_metric' m).trim := rfl @[simp] lemma mk_metric_to_outer_measure (m : ℝ≥0∞ → ℝ≥0∞) : (mk_metric m : measure X).to_outer_measure = outer_measure.mk_metric m := outer_measure.trim_mk_metric m end measure lemma outer_measure.coe_mk_metric [measurable_space X] [borel_space X] (m : ℝ≥0∞ → ℝ≥0∞) : ⇑(outer_measure.mk_metric m : outer_measure X) = measure.mk_metric m := by rw [← measure.mk_metric_to_outer_measure, coe_to_outer_measure] namespace measure variables [measurable_space X] [borel_space X] /-- If `c ∉ {0, ∞}` and `m₁ d ≤ c * m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ c • mk_metric m₂ hm₂`. -/ lemma mk_metric_mono_smul {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} {c : ℝ≥0∞} (hc : c ≠ ∞) (h0 : c ≠ 0) (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] c • m₂) : (mk_metric m₁ : measure X) ≤ c • mk_metric m₂ := begin intros s hs, rw [← outer_measure.coe_mk_metric, coe_smul, ← outer_measure.coe_mk_metric], exact outer_measure.mk_metric_mono_smul hc h0 hle s end /-- If `m₁ d ≤ m₂ d` for `0 < d < ε` for some `ε > 0` (we use `≤ᶠ[𝓝[Ioi 0]]` to state this), then `mk_metric m₁ hm₁ ≤ mk_metric m₂ hm₂`-/ lemma mk_metric_mono {m₁ m₂ : ℝ≥0∞ → ℝ≥0∞} (hle : m₁ ≤ᶠ[𝓝[Ioi 0] 0] m₂) : (mk_metric m₁ : measure X) ≤ mk_metric m₂ := by { convert mk_metric_mono_smul ennreal.one_ne_top ennreal.zero_lt_one.ne' _; simp * } /-- A formula for `measure_theory.measure.mk_metric`. -/ lemma mk_metric_apply (m : ℝ≥0∞ → ℝ≥0∞) (s : set X) : mk_metric m s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), m (diam (t n)) := begin -- We mostly unfold the definitions but we need to switch the order of `∑'` and `⨅` -- and merge `(t n).nonempty` with `¬subsingleton (t n)` classical, simp only [← outer_measure.coe_mk_metric, outer_measure.mk_metric, outer_measure.mk_metric', outer_measure.supr_apply, outer_measure.mk_metric'.pre, outer_measure.bounded_by_apply, extend], refine supr_congr (λ r, r) surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr _ surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ ht, _), by_cases htr : ∀ n, diam (t n) ≤ r, { rw [infi_eq_if, if_pos htr], congr' 1 with n : 1, simp only [infi_eq_if, htr n, id, if_true, supr_and'], refine supr_congr_Prop (and_iff_right_of_imp $ λ h, _) (λ _, rfl), contrapose! h, rw [not_nonempty_iff_eq_empty.1 h], exact subsingleton_empty }, { rw [infi_eq_if, if_neg htr], push_neg at htr, rcases htr with ⟨n, hn⟩, refine ennreal.tsum_eq_top_of_eq_top ⟨n, _⟩, rw [supr_eq_if, if_pos, infi_eq_if, if_neg], exact hn.not_le, rcases diam_pos_iff.1 ((zero_le r).trans_lt hn) with ⟨x, hx, -⟩, exact ⟨x, hx⟩ } end lemma le_mk_metric (m : ℝ≥0∞ → ℝ≥0∞) (μ : measure X) [has_no_atoms μ] (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → ¬s.subsingleton → μ s ≤ m (diam s)) : μ ≤ mk_metric m := begin rw [← to_outer_measure_le, mk_metric_to_outer_measure], exact outer_measure.le_mk_metric m μ.to_outer_measure measure_singleton ε h₀ h end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma mk_metric_le_liminf_tsum {β : Type*} {ι : β → Type*} [∀ n, encodable (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑' i, m (diam (t n i))) := begin simp only [mk_metric_apply], refine bsupr_le (λ ε hε, _), refine le_of_forall_le_of_dense (λ c hc, _), rcases ((frequently_lt_of_liminf_lt (by apply_auto_param) hc).and_eventually ((hr.eventually (gt_mem_nhds hε)).and (ht.and hst))).exists with ⟨n, hn, hrn, htn, hstn⟩, set u : ℕ → set X := λ j, ⋃ b ∈ decode₂ (ι n) j, t n b, refine binfi_le_of_le u (by rwa Union_decode₂) _, refine infi_le_of_le (λ j, _) _, { rw emetric.diam_Union_mem_option, exact bsupr_le (λ _ _, (htn _).trans hrn.le) }, { calc (∑' (j : ℕ), ⨆ (ht : ¬(u j).subsingleton), m (diam (u j))) = _ : tsum_Union_decode₂ (λ t : set X, ⨆ (h : ¬t.subsingleton), m (diam t)) (by simp) _ ... ≤ _ : ennreal.tsum_le_tsum (λ b, supr_le $ λ htb, le_rfl) ... ≤ c : hn.le } end /-- To bound the Hausdorff measure (or, more generally, for a measure defined using `measure_theory.measure.mk_metric`) of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma mk_metric_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) (m : ℝ≥0∞ → ℝ≥0∞) : mk_metric m s ≤ liminf l (λ n, ∑ i, m (diam (t n i))) := begin haveI : ∀ n, encodable (ι n), from λ n, fintype.encodable _, simpa only [tsum_fintype] using mk_metric_le_liminf_tsum s r hr t ht hst m, end /-! ### Hausdorff measure and Hausdorff dimension -/ /-- Hausdorff measure on an (e)metric space. -/ def hausdorff_measure (d : ℝ) : measure X := mk_metric (λ r, r ^ d) localized "notation `μH[` d `]` := measure_theory.measure.hausdorff_measure d" in measure_theory lemma le_hausdorff_measure (d : ℝ) (μ : measure X) [has_no_atoms μ] (ε : ℝ≥0∞) (h₀ : 0 < ε) (h : ∀ s : set X, diam s ≤ ε → ¬s.subsingleton → μ s ≤ diam s ^ d) : μ ≤ μH[d] := le_mk_metric _ μ ε h₀ h /-- A formula for `μH[d] s` that works for all `d`. In case of a positive `d` a simpler formula is available as `measure_theory.measure.hausdorff_measure_apply`. -/ lemma hausdorff_measure_apply' (d : ℝ) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, ⨆ (ht : ¬(t n).subsingleton), (diam (t n)) ^ d := mk_metric_apply _ _ /-- A formula for `μH[d] s` that works for all positive `d`. -/ lemma hausdorff_measure_apply {d : ℝ} (hd : 0 < d) (s : set X) : μH[d] s = ⨆ (r : ℝ≥0∞) (hr : 0 < r), ⨅ (t : ℕ → set X) (hts : s ⊆ ⋃ n, t n) (ht : ∀ n, diam (t n) ≤ r), ∑' n, diam (t n) ^ d := begin classical, rw hausdorff_measure_apply', -- I wish `congr'` was able to generate this refine supr_congr id surjective_id (λ r, supr_congr_Prop iff.rfl $ λ hr, infi_congr id surjective_id $ λ t, infi_congr_Prop iff.rfl $ λ hts, infi_congr_Prop iff.rfl $ λ ht, tsum_congr $ λ n, _), rw [supr_eq_if], split_ifs with ht', { erw [diam_eq_zero_iff.2 ht', ennreal.zero_rpow_of_pos hd, ennreal.bot_eq_zero] }, { refl } end /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of encodable types. -/ lemma hausdorff_measure_le_liminf_tsum {β : Type*} {ι : β → Type*} [hι : ∀ n, encodable (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑' i, diam (t n i) ^ d) := mk_metric_le_liminf_tsum s r hr t ht hst _ /-- To bound the Hausdorff measure of a set, one may use coverings with maximum diameter tending to `0`, indexed by any sequence of finite types. -/ lemma hausdorff_measure_le_liminf_sum {β : Type*} {ι : β → Type*} [hι : ∀ n, fintype (ι n)] (d : ℝ) (s : set X) {l : filter β} (r : β → ℝ≥0∞) (hr : tendsto r l (𝓝 0)) (t : Π (n : β), ι n → set X) (ht : ∀ᶠ n in l, ∀ i, diam (t n i) ≤ r n) (hst : ∀ᶠ n in l, s ⊆ ⋃ i, t n i) : μH[d] s ≤ liminf l (λ n, ∑ i, diam (t n i) ^ d) := mk_metric_le_liminf_sum s r hr t ht hst _ /-- If `d₁ < d₂`, then for any set `s` we have either `μH[d₂] s = 0`, or `μH[d₁] s = ∞`. -/ lemma hausdorff_measure_zero_or_top {d₁ d₂ : ℝ} (h : d₁ < d₂) (s : set X) : μH[d₂] s = 0 ∨ μH[d₁] s = ∞ := begin by_contra H, push_neg at H, suffices : ∀ (c : ℝ≥0), c ≠ 0 → μH[d₂] s ≤ c * μH[d₁] s, { rcases ennreal.exists_nnreal_pos_mul_lt H.2 H.1 with ⟨c, hc0, hc⟩, exact hc.not_le (this c (pos_iff_ne_zero.1 hc0)) }, intros c hc, refine le_iff'.1 (mk_metric_mono_smul ennreal.coe_ne_top (by exact_mod_cast hc) _) s, have : 0 < (c ^ (d₂ - d₁)⁻¹ : ℝ≥0∞), { rw [ennreal.coe_rpow_of_ne_zero hc, pos_iff_ne_zero, ne.def, ennreal.coe_eq_zero, nnreal.rpow_eq_zero_iff], exact mt and.left hc }, filter_upwards [Ioo_mem_nhds_within_Ioi ⟨le_rfl, this⟩], rintro r ⟨hr₀, hrc⟩, lift r to ℝ≥0 using ne_top_of_lt hrc, rw [pi.smul_apply, smul_eq_mul, ← ennreal.div_le_iff_le_mul (or.inr ennreal.coe_ne_top) (or.inr $ mt ennreal.coe_eq_zero.1 hc), ← ennreal.rpow_sub _ _ hr₀.ne' ennreal.coe_ne_top], refine (ennreal.rpow_lt_rpow hrc (sub_pos.2 h)).le.trans _, rw [← ennreal.rpow_mul, inv_mul_cancel (sub_pos.2 h).ne', ennreal.rpow_one], exact le_rfl end /-- Hausdorff measure `μH[d] s` is monotone in `d`. -/ lemma hausdorff_measure_mono {d₁ d₂ : ℝ} (h : d₁ ≤ d₂) (s : set X) : μH[d₂] s ≤ μH[d₁] s := begin rcases h.eq_or_lt with rfl|h, { exact le_rfl }, cases hausdorff_measure_zero_or_top h s with hs hs, { rw hs, exact zero_le _ }, { rw hs, exact le_top } end instance no_atoms_hausdorff (d : ℝ) : has_no_atoms (hausdorff_measure d : measure X) := begin refine ⟨λ x, _⟩, rw [← nonpos_iff_eq_zero, hausdorff_measure_apply'], refine bsupr_le (λ ε ε0, binfi_le_of_le (λ n, {x}) _ (infi_le_of_le (λ n, _) _)), { exact subset_Union (λ n, {x} : ℕ → set X) 0 }, { simp only [emetric.diam_singleton, zero_le] }, { simp } end end measure open_locale measure_theory open measure /-! ### Hausdorff measure and Lebesgue measure -/ /-- In the space `ι → ℝ`, Hausdorff measure coincides exactly with Lebesgue measure. -/ @[simp] theorem hausdorff_measure_pi_real {ι : Type*} [fintype ι] [nonempty ι] : (μH[fintype.card ι] : measure (ι → ℝ)) = volume := begin classical, -- it suffices to check that the two measures coincide on products of rational intervals refine (pi_eq_generate_from (λ i, real.borel_eq_generate_from_Ioo_rat.symm) (λ i, real.is_pi_system_Ioo_rat) (λ i, real.finite_spanning_sets_in_Ioo_rat _) _).symm, simp only [mem_Union, mem_singleton_iff], -- fix such a product `s` of rational intervals, of the form `Π (a i, b i)`. intros s hs, choose a b H using hs, obtain rfl : s = λ i, Ioo (a i) (b i), from funext (λ i, (H i).2), replace H := λ i, (H i).1, apply le_antisymm _, -- first check that `volume s ≤ μH s` { have Hle : volume ≤ (μH[fintype.card ι] : measure (ι → ℝ)), { refine le_hausdorff_measure _ _ ∞ ennreal.coe_lt_top (λ s h₁ h₂, _), rw [ennreal.rpow_nat_cast], exact real.volume_pi_le_diam_pow s }, rw [← volume_pi_pi (λ i, Ioo (a i : ℝ) (b i))], exact measure.le_iff'.1 Hle _ }, /- For the other inequality `μH s ≤ volume s`, we use a covering of `s` by sets of small diameter `1/n`, namely cubes with left-most point of the form `a i + f i / n` with `f i` ranging between `0` and `⌈(b i - a i) * n⌉`. Their number is asymptotic to `n^d * Π (b i - a i)`. -/ have I : ∀ i, 0 ≤ (b i : ℝ) - a i := λ i, by simpa only [sub_nonneg, rat.cast_le] using (H i).le, let γ := λ (n : ℕ), (Π (i : ι), fin ⌈((b i : ℝ) - a i) * n⌉₊), let t : Π (n : ℕ), γ n → set (ι → ℝ) := λ n f, set.pi univ (λ i, Icc (a i + f i / n) (a i + (f i + 1) / n)), have A : tendsto (λ (n : ℕ), 1/(n : ℝ≥0∞)) at_top (𝓝 0), by simp only [one_div, ennreal.tendsto_inv_nat_nhds_zero], have B : ∀ᶠ n in at_top, ∀ (i : γ n), diam (t n i) ≤ 1 / n, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, assume f, apply diam_pi_le_of_le (λ b, _), simp only [real.ediam_Icc, add_div, ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), le_refl, add_sub_add_left_eq_sub, add_sub_cancel', ennreal.of_real_one, ennreal.of_real_coe_nat] }, have C : ∀ᶠ n in at_top, set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i)) ⊆ ⋃ (i : γ n), t n i, { apply eventually_at_top.2 ⟨1, λ n hn, _⟩, have npos : (0 : ℝ) < n := nat.cast_pos.2 hn, assume x hx, simp only [mem_Ioo, mem_univ_pi] at hx, simp only [mem_Union, mem_Ioo, mem_univ_pi, coe_coe], let f : γ n := λ i, ⟨⌊(x i - a i) * n⌋₊, begin apply nat.floor_lt_ceil_of_lt_of_pos, { refine (mul_lt_mul_right npos).2 _, simp only [(hx i).right, sub_lt_sub_iff_right] }, { refine mul_pos _ npos, simpa only [rat.cast_lt, sub_pos] using H i } end⟩, refine ⟨f, λ i, ⟨_, _⟩⟩, { calc (a i : ℝ) + ⌊(x i - a i) * n⌋₊ / n ≤ (a i : ℝ) + ((x i - a i) * n) / n : begin refine add_le_add le_rfl ((div_le_div_right npos).2 _), exact nat.floor_le (mul_nonneg (sub_nonneg.2 (hx i).1.le) npos.le), end ... = x i : by field_simp [npos.ne'] }, { calc x i = (a i : ℝ) + ((x i - a i) * n) / n : by field_simp [npos.ne'] ... ≤ (a i : ℝ) + (⌊(x i - a i) * n⌋₊ + 1) / n : add_le_add le_rfl ((div_le_div_right npos).2 (nat.lt_floor_add_one _).le) } }, calc μH[fintype.card ι] (set.pi univ (λ (i : ι), Ioo (a i : ℝ) (b i))) ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), diam (t n i) ^ ↑(fintype.card ι)) : hausdorff_measure_le_liminf_sum _ (set.pi univ (λ i, Ioo (a i : ℝ) (b i))) (λ (n : ℕ), 1/(n : ℝ≥0∞)) A t B C ... ≤ liminf at_top (λ (n : ℕ), ∑ (i : γ n), (1/n) ^ (fintype.card ι)) : begin refine liminf_le_liminf _ (by is_bounded_default), filter_upwards [B], assume n hn, apply finset.sum_le_sum (λ i _, _), rw ennreal.rpow_nat_cast, exact pow_le_pow_of_le_left' (hn i) _, end ... = liminf at_top (λ (n : ℕ), ∏ (i : ι), (⌈((b i : ℝ) - a i) * n⌉₊ : ℝ≥0∞) / n) : begin simp only [finset.card_univ, nat.cast_prod, one_mul, fintype.card_fin, finset.sum_const, nsmul_eq_mul, fintype.card_pi, div_eq_mul_inv, finset.prod_mul_distrib, finset.prod_const] end ... = ∏ (i : ι), volume (Ioo (a i : ℝ) (b i)) : begin simp only [real.volume_Ioo], apply tendsto.liminf_eq, refine ennreal.tendsto_finset_prod_of_ne_top _ (λ i hi, _) (λ i hi, _), { apply tendsto.congr' _ ((ennreal.continuous_of_real.tendsto _).comp ((tendsto_nat_ceil_mul_div_at_top (I i)).comp tendsto_coe_nat_at_top_at_top)), apply eventually_at_top.2 ⟨1, λ n hn, _⟩, simp only [ennreal.of_real_div_of_pos (nat.cast_pos.mpr hn), comp_app, ennreal.of_real_coe_nat] }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end end end measure_theory /-! ### Hausdorff measure, Hausdorff dimension, and Hölder or Lipschitz continuous maps -/ open_locale measure_theory open measure_theory measure_theory.measure variables [measurable_space X] [borel_space X] [measurable_space Y] [borel_space Y] namespace holder_on_with variables {C r : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is Hölder continuous on `s` with a positive exponent `r`, then `μH[d] (f '' s) ≤ C ^ d * μH[r * d] s`. -/ lemma hausdorff_measure_image_le (h : holder_on_with C r f s) (hr : 0 < r) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ C ^ d * μH[r * d] s := begin -- We start with the trivial case `C = 0` rcases (zero_le C).eq_or_lt with rfl|hC0, { have : (f '' s).subsingleton, by simpa [diam_eq_zero_iff] using h.ediam_image_le, rw this.measure_zero, exact zero_le _ }, { have hCd0 : (C : ℝ≥0∞) ^ d ≠ 0, by simp [hC0.ne'], have hCd : (C : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply', ennreal.mul_supr, ennreal.mul_infi_of_ne hCd0 hCd, ← ennreal.tsum_mul_left], refine supr_le (λ R, supr_le $ λ hR, _), have : tendsto (λ d : ℝ≥0∞, (C : ℝ≥0∞) * d ^ (r : ℝ)) (𝓝 0) (𝓝 0), from ennreal.tendsto_const_mul_rpow_nhds_zero_of_pos ennreal.coe_ne_top hr, rcases ennreal.nhds_zero_basis_Iic.eventually_iff.1 (this.eventually (gt_mem_nhds hR)) with ⟨δ, δ0, H⟩, refine le_supr_of_le δ (le_supr_of_le δ0 $ le_binfi $ λ t hst, le_infi $ λ htδ, _), refine binfi_le_of_le (λ n, f '' (t n ∩ s)) _ (infi_le_of_le (λ n, _) _), { rw [← image_Union, ← Union_inter], exact image_subset _ (subset_inter hst subset.rfl) }, { exact (h.ediam_image_inter_le (t n)).trans (H (htδ n)).le }, { refine ennreal.tsum_le_tsum (λ n, supr_le $ λ hft, le_supr_of_le (λ ht, hft $ (ht.mono (inter_subset_left _ _)).image f) _), rw [ennreal.rpow_mul, ← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (h.ediam_image_inter_le _) hd } } end end holder_on_with namespace lipschitz_on_with variables {K : ℝ≥0} {f : X → Y} {s t : set X} /-- If `f : X → Y` is `K`-Lipschitz on `s`, then `μH[d] (f '' s) ≤ K ^ d * μH[d] s`. -/ lemma hausdorff_measure_image_le (h : lipschitz_on_with K f s) {d : ℝ} (hd : 0 ≤ d) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := by simpa only [nnreal.coe_one, one_mul] using h.holder_on_with.hausdorff_measure_image_le zero_lt_one hd end lipschitz_on_with namespace lipschitz_with variables {K : ℝ≥0} {f : X → Y} /-- If `f` is a `K`-Lipschitz map, then it increases the Hausdorff `d`-measures of sets at most by the factor of `K ^ d`.-/ lemma hausdorff_measure_image_le (h : lipschitz_with K f) {d : ℝ} (hd : 0 ≤ d) (s : set X) : μH[d] (f '' s) ≤ K ^ d * μH[d] s := (h.lipschitz_on_with s).hausdorff_measure_image_le hd end lipschitz_with /-! ### Antilipschitz maps do not decrease Hausdorff measures and dimension -/ namespace antilipschitz_with variables {f : X → Y} {K : ℝ≥0} {d : ℝ} lemma hausdorff_measure_preimage_le (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set Y) : μH[d] (f ⁻¹' s) ≤ K ^ d * μH[d] s := begin rcases eq_or_ne K 0 with rfl|h0, { haveI : subsingleton X := hf.subsingleton, have : (f ⁻¹' s).subsingleton, from subsingleton_univ.mono (subset_univ _), rw this.measure_zero, exact zero_le _ }, have hKd0 : (K : ℝ≥0∞) ^ d ≠ 0, by simp [h0], have hKd : (K : ℝ≥0∞) ^ d ≠ ∞, by simp [hd], simp only [hausdorff_measure_apply', ennreal.mul_supr, ennreal.mul_infi_of_ne hKd0 hKd, ← ennreal.tsum_mul_left], refine bsupr_le (λ ε ε0, _), refine le_bsupr_of_le (ε / K) (by simp [ε0.ne']) _, refine le_binfi (λ t hst, le_infi $ λ htε, _), replace hst : f ⁻¹' s ⊆ _ := preimage_mono hst, rw preimage_Union at hst, refine binfi_le_of_le _ hst (infi_le_of_le (λ n, _) _), { exact (hf.ediam_preimage_le _).trans (ennreal.mul_le_of_le_div' $ htε n) }, { refine ennreal.tsum_le_tsum (λ n, supr_le $ λ H, le_supr_of_le (λ h, H $ h.preimage hf.injective) _), rw [← ennreal.mul_rpow_of_nonneg _ _ hd], exact ennreal.rpow_le_rpow (hf.ediam_preimage_le _) hd } end lemma le_hausdorff_measure_image (hf : antilipschitz_with K f) (hd : 0 ≤ d) (s : set X) : μH[d] s ≤ K ^ d * μH[d] (f '' s) := calc μH[d] s ≤ μH[d] (f ⁻¹' (f '' s)) : measure_mono (subset_preimage_image _ _) ... ≤ K ^ d * μH[d] (f '' s) : hf.hausdorff_measure_preimage_le hd (f '' s) end antilipschitz_with /-! ### Isometries preserve the Hausdorff measure and Hausdorff dimension -/ namespace isometry variables {f : X → Y} {d : ℝ} lemma hausdorff_measure_image (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set X) : μH[d] (f '' s) = μH[d] s := begin simp only [hausdorff_measure, ← outer_measure.coe_mk_metric, ← outer_measure.comap_apply], rw [outer_measure.isometry_comap_mk_metric _ hf (hd.imp_left _)], exact λ hd x y hxy, ennreal.rpow_le_rpow hxy hd end lemma hausdorff_measure_preimage (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) (s : set Y) : μH[d] (f ⁻¹' s) = μH[d] (s ∩ range f) := by rw [← hf.hausdorff_measure_image hd, image_preimage_eq_inter_range] lemma map_hausdorff_measure (hf : isometry f) (hd : 0 ≤ d ∨ surjective f) : measure.map f μH[d] = (μH[d]).restrict (range f) := begin ext1 s hs, rw [map_apply hf.continuous.measurable hs, restrict_apply hs, hf.hausdorff_measure_preimage hd] end end isometry namespace isometric @[simp] lemma hausdorff_measure_image (e : X ≃ᵢ Y) (d : ℝ) (s : set X) : μH[d] (e '' s) = μH[d] s := e.isometry.hausdorff_measure_image (or.inr e.surjective) s @[simp] lemma hausdorff_measure_preimage (e : X ≃ᵢ Y) (d : ℝ) (s : set Y) : μH[d] (e ⁻¹' s) = μH[d] s := by rw [← e.image_symm, e.symm.hausdorff_measure_image] end isometric
d6a9391465f9b87e9b0d7aeadb60b4447974fbd6
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/products/associator_auto.lean
e0a3711394a45ab29ca519d129b1abf5d2955508
[]
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
2,416
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.products.basic import Mathlib.PostPort universes u₁ u₂ u₃ v₁ v₂ v₃ namespace Mathlib /-# The associator functor `((C × D) × E) ⥤ (C × (D × E))` and its inverse form an equivalence. -/ namespace category_theory.prod /-- The associator functor `(C × D) × E ⥤ C × (D × E)`. -/ @[simp] theorem associator_map (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] (_x : (C × D) × E) : ∀ (_x_1 : (C × D) × E) (f : _x ⟶ _x_1), functor.map (associator C D E) f = (prod.fst (prod.fst f), prod.snd (prod.fst f), prod.snd f) := fun (_x_1 : (C × D) × E) (f : _x ⟶ _x_1) => Eq.refl (functor.map (associator C D E) f) /-- The inverse associator functor `C × (D × E) ⥤ (C × D) × E `. -/ @[simp] theorem inverse_associator_map (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] (_x : C × D × E) : ∀ (_x_1 : C × D × E) (f : _x ⟶ _x_1), functor.map (inverse_associator C D E) f = ((prod.fst f, prod.fst (prod.snd f)), prod.snd (prod.snd f)) := fun (_x_1 : C × D × E) (f : _x ⟶ _x_1) => Eq.refl (functor.map (inverse_associator C D E) f) /-- The equivalence of categories expressing associativity of products of categories. -/ def associativity (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : (C × D) × E ≌ C × D × E := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (fun (X : (C × D) × E) => eq_to_iso sorry) sorry) (nat_iso.of_components (fun (X : C × D × E) => eq_to_iso sorry) sorry) protected instance associator_is_equivalence (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : is_equivalence (associator C D E) := is_equivalence.of_equivalence (associativity C D E) protected instance inverse_associator_is_equivalence (C : Type u₁) [category C] (D : Type u₂) [category D] (E : Type u₃) [category E] : is_equivalence (inverse_associator C D E) := is_equivalence.of_equivalence_inverse (associativity C D E) end Mathlib
1cac48b337b65ce235d8a49fec256e33049861cf
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/subtype.lean
da0b273a97f55c00b9b629cddbe1c5a05966d31b
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
4,266
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl -/ -- Lean complains if this section is turned into a namespace open function section subtype variables {α : Sort*} {p : α → Prop} @[simp] theorem subtype.forall {q : {a // p a} → Prop} : (∀ x, q x) ↔ (∀ a b, q ⟨a, b⟩) := ⟨assume h a b, h ⟨a, b⟩, assume h ⟨a, b⟩, h a b⟩ @[simp] theorem subtype.exists {q : {a // p a} → Prop} : (∃ x, q x) ↔ (∃ a b, q ⟨a, b⟩) := ⟨assume ⟨⟨a, b⟩, h⟩, ⟨a, b, h⟩, assume ⟨a, b, h⟩, ⟨⟨a, b⟩, h⟩⟩ end subtype namespace subtype variables {α : Sort*} {β : Sort*} {γ : Sort*} {p : α → Prop} protected lemma eq' : ∀ {a1 a2 : {x // p x}}, a1.val = a2.val → a1 = a2 | ⟨x, h1⟩ ⟨.(x), h2⟩ rfl := rfl lemma ext {a1 a2 : {x // p x}} : a1 = a2 ↔ a1.val = a2.val := ⟨congr_arg _, subtype.eq'⟩ lemma coe_ext {a1 a2 : {x // p x}} : a1 = a2 ↔ (a1 : α) = a2 := ext theorem val_injective : injective (@val _ p) := λ a b, subtype.eq' /- Restrict a (dependent) function to a subtype -/ def restrict {α} {β : α → Type*} (f : ∀x, β x) (p : α → Prop) (x : subtype p) : β x.1 := f x.1 lemma restrict_apply {α} {β : α → Type*} (f : ∀x, β x) (p : α → Prop) (x : subtype p) : restrict f p x = f x.1 := by refl lemma restrict_def {α β} (f : α → β) (p : α → Prop) : restrict f p = f ∘ subtype.val := by refl lemma restrict_injective {α β} {f : α → β} (p : α → Prop) (h : injective f) : injective (restrict f p) := injective_comp h subtype.val_injective /-- Defining a map into a subtype, this can be seen as an "coinduction principle" of `subtype`-/ def coind {α β} (f : α → β) {p : β → Prop} (h : ∀a, p (f a)) : α → subtype p := λ a, ⟨f a, h a⟩ theorem coind_injective {α β} {f : α → β} {p : β → Prop} (h : ∀a, p (f a)) (hf : injective f) : injective (coind f h) := λ x y hxy, hf $ by apply congr_arg subtype.val hxy /-- Restriction of a function to a function on subtypes. -/ def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) : subtype p → subtype q := λ x, ⟨f x.1, h x.1 x.2⟩ theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p} (f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) : map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x := rfl theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id := funext $ assume ⟨v, h⟩, rfl lemma map_injective {p : α → Prop} {q : β → Prop} {f : α → β} (h : ∀a, p a → q (f a)) (hf : injective f) : injective (map f h) := coind_injective _ $ injective_comp hf val_injective instance [has_equiv α] (p : α → Prop) : has_equiv (subtype p) := ⟨λ s t, s.val ≈ t.val⟩ theorem equiv_iff [has_equiv α] {p : α → Prop} {s t : subtype p} : s ≈ t ↔ s.val ≈ t.val := iff.rfl variables [setoid α] protected theorem refl (s : subtype p) : s ≈ s := setoid.refl s.val protected theorem symm {s t : subtype p} (h : s ≈ t) : t ≈ s := setoid.symm h protected theorem trans {s t u : subtype p} (h₁ : s ≈ t) (h₂ : t ≈ u) : s ≈ u := setoid.trans h₁ h₂ theorem equivalence (p : α → Prop) : equivalence (@has_equiv.equiv (subtype p) _) := mk_equivalence _ subtype.refl (@subtype.symm _ p _) (@subtype.trans _ p _) instance (p : α → Prop) : setoid (subtype p) := setoid.mk (≈) (equivalence p) end subtype namespace subtype variables {α : Type*} {β : Type*} {γ : Type*} {p : α → Prop} @[simp] theorem coe_eta {α : Type*} {p : α → Prop} (a : {a // p a}) (h : p a) : mk ↑a h = a := eta _ _ @[simp] theorem coe_mk {α : Type*} {p : α → Prop} (a h) : (@mk α p a h : α) = a := rfl @[simp] theorem mk_eq_mk {α : Type*} {p : α → Prop} {a h a' h'} : @mk α p a h = @mk α p a' h' ↔ a = a' := ⟨λ H, by injection H, λ H, by congr; assumption⟩ @[simp] lemma val_prop {S : set α} (a : {a // a ∈ S}) : a.val ∈ S := a.property @[simp] lemma val_prop' {S : set α} (a : {a // a ∈ S}) : ↑a ∈ S := a.property end subtype
f9d8176bae0497e0c89a384cccbea5127ae9fac4
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/doc/examples/Certora2022/ex18.lean
e74262d2af50c976369cc045ca1297009e056ff5
[ "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
530
lean
/- Structuring proofs (cont.) -/ example : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) := by intro h have hp : p := h.left have hqr : q ∨ r := h.right show (p ∧ q) ∨ (p ∧ r) cases hqr with | inl hq => exact Or.inl ⟨hp, hq⟩ | inr hr => exact Or.inr ⟨hp, hr⟩ example : p ∧ (q ∨ r) → (p ∧ q) ∨ (p ∧ r) := by intro ⟨hp, hqr⟩ cases hqr with | inl hq => have := And.intro hp hq apply Or.inl; exact this | inr hr => have := And.intro hp hr apply Or.inr; exact this
a7970ed9244ed87cb28c09332aab771c2fef0f7e
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/lean/run/fun.lean
17b0179197b226fc4609060bf8b33ca1b85dee89
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
366
lean
open Function Bool constant f : Nat → Bool := default _ constant g : Nat → Nat := default _ #check f ∘ g ∘ g #check (id : Nat → Nat) constant h : Nat → Bool → Nat := default _ #check swap h #check swap h false Nat.zero #check (swap h false Nat.zero : Nat) constant f1 : Nat → Nat → Bool := default _ constant f2 : Bool → Nat := default _
54f8e4e861046fd41e5e44b6da5b2f962120b86b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/ring/basic.lean
6cc9980f88a841f5c7538bf0e7d4edfd070ccf9e
[ "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
46,074
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ /-- A not-necessarily-unital, not-necessarily-associative semiring. -/ @[protect_proj, ancestor add_comm_monoid distrib mul_zero_class] class non_unital_non_assoc_semiring (α : Type u) extends add_comm_monoid α, distrib α, mul_zero_class α /-- An associative but not-necessarily unital semiring. -/ @[protect_proj, ancestor non_unital_non_assoc_semiring semigroup_with_zero] class non_unital_semiring (α : Type u) extends non_unital_non_assoc_semiring α, semigroup_with_zero α /-- A unital but not-necessarily-associative semiring. -/ @[protect_proj, ancestor non_unital_non_assoc_semiring mul_zero_one_class] class non_assoc_semiring (α : Type u) extends non_unital_non_assoc_semiring α, mul_zero_one_class α /-- A semiring is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero` instead of `monoid` and `mul_zero_class`. -/ @[protect_proj, ancestor non_unital_semiring non_assoc_semiring monoid_with_zero] class semiring (α : Type u) extends non_unital_semiring α, non_assoc_semiring α, monoid_with_zero α section injective_surjective_maps variables [has_zero β] [has_add β] [has_mul β] /-- Pullback a `non_unital_non_assoc_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_non_assoc_semiring {α : Type u} [non_unital_non_assoc_semiring α] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_unital_non_assoc_semiring β := { .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pullback a `non_unital_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_unital_semiring {α : Type u} [non_unital_semiring α] (f : β → α) (hf : injective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_unital_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul, .. hf.semigroup_with_zero f zero mul } /-- Pullback a `non_assoc_semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.non_assoc_semiring {α : Type u} [non_assoc_semiring α] [has_one β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_assoc_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul, .. hf.mul_one_class f one mul } /-- Pullback a `semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.semiring {α : Type u} [semiring α] [has_one β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pushforward a `non_unital_non_assoc_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_non_assoc_semiring {α : Type u} [non_unital_non_assoc_semiring α] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_unital_non_assoc_semiring β := { .. hf.mul_zero_class f zero mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pushforward a `non_unital_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_unital_semiring {α : Type u} [non_unital_semiring α] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_unital_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul, .. hf.semigroup_with_zero f zero mul } /-- Pushforward a `non_assoc_semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.non_assoc_semiring {α : Type u} [non_assoc_semiring α] [has_one β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : non_assoc_semiring β := { .. hf.non_unital_non_assoc_semiring f zero add mul, .. hf.mul_one_class f one mul } /-- Pushforward a `semiring` instance along a surjective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.semiring {α : Type u} [semiring α] [has_one β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } end injective_surjective_maps section semiring variables [semiring α] lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [non_assoc_semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [non_assoc_semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } /-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/ def even (a : α) : Prop := ∃ k, a = 2*k lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl @[simp] lemma range_two_mul (α : Type*) [semiring α] : set.range (λ x : α, 2 * x) = {a | even a} := by { ext x, simp [even, eq_comm] } @[simp] lemma even_bit0 (a : α) : even (bit0 a) := ⟨a, by rw [bit0, two_mul]⟩ /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 @[simp] lemma odd_bit1 (a : α) : odd (bit1 a) := ⟨a, by rw [bit1, bit0, two_mul]⟩ @[simp] lemma range_two_mul_add_one (α : Type*) [semiring α] : set.range (λ x : α, 2 * x + 1) = {a | odd a} := by { ext x, simp [odd, eq_comm] } theorem dvd_add {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma coe_mul_right {R : Type*} [non_unital_non_assoc_semiring R] (r : R) : ⇑(mul_right r) = (* r) := rfl lemma mul_right_apply {R : Type*} [non_unital_non_assoc_semiring R] (a r : R) : mul_right r a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/ structure ring_hom (α : Type*) (β : Type*) [non_assoc_semiring α] [non_assoc_semiring β] extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β infixr ` →+* `:25 := ring_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`. The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/ add_decl_doc ring_hom.to_monoid_with_zero_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`. The `simp`-normal form is `(f : R →* S)`. -/ add_decl_doc ring_hom.to_monoid_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`. The `simp`-normal form is `(f : R →+ S)`. -/ add_decl_doc ring_hom.to_add_monoid_hom namespace ring_hom section coe /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ variables {rα : non_assoc_semiring α} {rβ : non_assoc_semiring β} include rα rβ instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ initialize_simps_projections ring_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl @[simp] lemma to_monoid_with_zero_hom_eq_coe (f : α →+* β) : (f.to_monoid_with_zero_hom : α → β) = f := rfl @[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ := rfl instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl @[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ := rfl end coe variables [rα : non_assoc_semiring α] [rβ : non_assoc_semiring β] section include rα rβ variables (f : α →+* β) {x y : α} {rα rβ} theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →+* β, h x) h theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma mk_coe (f : α →+* β) (h₁ h₂ h₃ h₄) : ring_hom.mk f h₁ h₂ h₃ h₄ = f := ext $ λ _, rfl theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, ext (λ x, add_monoid_hom.congr_fun h x) theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, ext (λ x, monoid_hom.congr_fun h x) /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- Ring homomorphisms preserve `bit0`. -/ @[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _ /-- Ring homomorphisms preserve `bit1`. -/ @[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) := by simp [bit1] /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ end lemma is_unit_map [semiring α] [semiring β] (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map f.to_monoid_hom /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [non_assoc_semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα instance : inhabited (α →+* α) := ⟨id α⟩ @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : non_assoc_semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: non_assoc_semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom /-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). -/ @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} /-- Pullback a `semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b] @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ /-- A ring is a type with the following structures: additive commutative group (`add_comm_group`), multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a `semiring` with a negation operation making it an additive group. -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ @[priority 200] instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /-- Pullback a `ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c) alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units lemma is_unit.neg [ring α] {a : α} : is_unit a → is_unit (-a) | ⟨x, hx⟩ := hx ▸ (-x).is_unit namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [non_assoc_semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [non_assoc_semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom /-- A commutative ring is a `ring` with commutative multiplication. -/ @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring f zero one add mul neg sub, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring f zero one add mul neg sub, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) } theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self, mul_one] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] @[priority 100] -- see Note [lower instance priority] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : domain β := { .. hf.ring f zero one add mul neg sub, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ /-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative multiplication. -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} @[priority 100] -- see Note [lower instance priority] instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. See note [reducible non-instances]. -/ @[reducible] protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : integral_domain β := { .. hf.comm_ring f zero one add mul neg sub, .. hf.domain f zero one add mul neg sub } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } /-- Makes a ring homomorphism from an additive group homomorphism from a commutative ring to an integral domain that commutes with self multiplication, assumes that two is nonzero and one is sent to one. -/ def add_monoid_hom.mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h : ∀ x, f (x * x) = f x * f x) (h_two : (2 : α) ≠ 0) (h_one : f 1 = 1) : β →+* α := { map_one' := h_one, map_mul' := begin intros x y, have hxy := h (x + y), rw [mul_add, add_mul, add_mul, f.map_add, f.map_add, f.map_add, f.map_add, h x, h y, add_mul, mul_add, mul_add, ← sub_eq_zero, add_comm, ← sub_sub, ← sub_sub, ← sub_sub, mul_comm y x, mul_comm (f y) (f x)] at hxy, simp only [add_assoc, add_sub_assoc, add_sub_cancel'_right] at hxy, rw [sub_sub, ← two_mul, ← add_sub_assoc, ← two_mul, ← mul_sub, mul_eq_zero, sub_eq_zero, or_iff_not_imp_left] at hxy, exact hxy h_two, end, ..f } @[simp] lemma add_monoid_hom.coe_fn_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β → α) = f := rfl @[simp] lemma add_monoid_hom.coe_add_monoid_hom_mk_ring_hom_of_mul_self_of_two_ne_zero [comm_ring β] (f : β →+ α) (h h_two h_one) : (f.mk_ring_hom_of_mul_self_of_two_ne_zero h h_two h_one : β →+ α) = f := by {ext, simp} end integral_domain namespace ring variables {M₀ : Type*} [monoid_with_zero M₀] open_locale classical /-- Introduce a function `inverse` on a monoid with zero `M₀`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. Note that while this is in the `ring` namespace for brevity, it requires the weaker assumption `monoid_with_zero M₀` instead of `ring M₀`. -/ noncomputable def inverse : M₀ → M₀ := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units M₀) : M₀) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ @[simp] lemma inverse_unit (u : units M₀) : inverse (u : M₀) = (u⁻¹ : units M₀) := begin simp only [units.is_unit, inverse, dif_pos], exact units.inv_unique (classical.some_spec u.is_unit) end /-- By definition, if `x` is not invertible then `inverse x = 0`. -/ @[simp] lemma inverse_non_unit (x : M₀) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left lemma bit0_right [distrib R] {x y : R} (h : commute x y) : commute x (bit0 y) := h.add_right h lemma bit0_left [distrib R] {x y : R} (h : commute x y) : commute (bit0 x) y := h.add_left h lemma bit1_right [semiring R] {x y : R} (h : commute x y) : commute x (bit1 y) := h.bit0_right.add_right (commute.one_right x) lemma bit1_left [semiring R] {x y : R} (h : commute x y) : commute (bit1 x) y := h.bit0_left.add_left (commute.one_left y) variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
97ee599a09e4534cf8366c7b9b49a4e9823148c2
46125763b4dbf50619e8846a1371029346f4c3db
/src/analysis/complex/exponential.lean
802dcfa5e2aeaeb284ba260607bc4802f98edbc0
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
82,900
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne -/ import tactic.linarith data.complex.exponential analysis.specific_limits group_theory.quotient_group analysis.complex.basic /-! # Exponential ## Main definitions This file contains the following definitions: * π, arcsin, arccos, arctan * argument of a complex number * logarithm on real and complex numbers * complex and real power function ## Main statements The following functions are shown to be continuous: * complex and real exponential function * sin, cos, tan, sinh, cosh * logarithm on real numbers * real power function * square root function The following functions are shown to be differentiable, and their derivatives are computed: * complex and real exponential function * sin, cos, sinh, cosh ## Tags exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root, -/ noncomputable theory open finset filter metric asymptotics open_locale classical open_locale topological_space namespace complex /-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/ lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x := begin rw has_deriv_at_iff_is_o_nhds_zero, have : (1 : ℕ) < 2 := by norm_num, refine is_O.trans_is_o ⟨∥exp x∥, _⟩ (is_o_pow_id this), have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) := metric.ball_mem_nhds 0 zero_lt_one, apply filter.mem_sets_of_superset this (λz hz, _), simp only [metric.mem_ball, dist_zero_right] at hz, simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow, zero_add, set.mem_set_of_eq], calc ∥exp (x + z) - exp x - z * exp x∥ = ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring } ... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _ ... ≤ ∥exp x∥ * ∥z∥^2 : mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _) end lemma differentiable_exp : differentiable ℂ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous end complex lemma has_deriv_at.cexp {f : ℂ → ℂ} {f' x : ℂ} (hf : has_deriv_at f f' x) : has_deriv_at (complex.exp ∘ f) (f' * complex.exp (f x)) x := (complex.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.cexp {f : ℂ → ℂ} {f' x : ℂ} {s : set ℂ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (complex.exp ∘ f) (f' * complex.exp (f x)) s x := (complex.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf namespace complex /-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/ lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x := begin simp only [cos, div_eq_mul_inv], convert ((((has_deriv_at_id x).neg.mul_const I).cexp.sub ((has_deriv_at_id x).mul_const I).cexp).mul_const I).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [add_comm, one_mul, mul_comm (_ - _), mul_sub, mul_left_comm, ← mul_assoc, ← mul_assoc, I_mul_I, mul_assoc (-1:ℂ), I_mul_I, neg_one_mul, neg_neg, one_mul, neg_one_mul, sub_neg_eq_add] end lemma differentiable_sin : differentiable ℂ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous /-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/ lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x := begin simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul], convert (((has_deriv_at_id x).mul_const I).cexp.add ((has_deriv_at_id x).neg.mul_const I).cexp).mul_const (2:ℂ)⁻¹, simp only [function.comp, id], rw [one_mul, neg_one_mul, neg_sub, mul_comm, mul_sub, sub_eq_add_neg, neg_mul_eq_neg_mul] end lemma differentiable_cos : differentiable ℂ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos {x : ℂ} : deriv cos x = -sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) := funext $ λ x, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) /-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/ lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x := begin simp only [cosh, div_eq_mul_inv], convert ((has_deriv_at_exp x).sub (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, neg_one_mul, neg_neg] end lemma differentiable_sinh : differentiable ℂ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous /-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/ lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x := begin simp only [sinh, div_eq_mul_inv], convert ((has_deriv_at_exp x).add (has_deriv_at_id x).neg.cexp).mul_const (2:ℂ)⁻¹, rw [id, neg_one_mul, sub_eq_add_neg] end lemma differentiable_cosh : differentiable ℂ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous end complex namespace real variables {x y z : ℝ} lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_exp x) lemma differentiable_exp : differentiable ℝ exp := λx, (has_deriv_at_exp x).differentiable_at @[simp] lemma deriv_exp : deriv exp = exp := funext $ λ x, (has_deriv_at_exp x).deriv @[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp | 0 := rfl | (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n] lemma continuous_exp : continuous exp := differentiable_exp.continuous lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sin x) lemma differentiable_sin : differentiable ℝ sin := λx, (has_deriv_at_sin x).differentiable_at @[simp] lemma deriv_sin : deriv sin = cos := funext $ λ x, (has_deriv_at_sin x).deriv lemma continuous_sin : continuous sin := differentiable_sin.continuous lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x := (has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _) lemma differentiable_cos : differentiable ℝ cos := λx, (has_deriv_at_cos x).differentiable_at lemma deriv_cos : deriv cos x = - sin x := (has_deriv_at_cos x).deriv @[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) := funext $ λ _, deriv_cos lemma continuous_cos : continuous cos := differentiable_cos.continuous lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) := by simp only [tan_eq_sin_div_cos]; exact (continuous_sin.comp continuous_subtype_val).mul (continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val)) lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x) lemma differentiable_sinh : differentiable ℝ sinh := λx, (has_deriv_at_sinh x).differentiable_at @[simp] lemma deriv_sinh : deriv sinh = cosh := funext $ λ x, (has_deriv_at_sinh x).deriv lemma continuous_sinh : continuous sinh := differentiable_sinh.continuous lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x := has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x) lemma differentiable_cosh : differentiable ℝ cosh := λx, (has_deriv_at_cosh x).differentiable_at @[simp] lemma deriv_cosh : deriv cosh = sinh := funext $ λ x, (has_deriv_at_cosh x).deriv lemma continuous_cosh : continuous cosh := differentiable_cosh.continuous lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x := have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp, from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp ⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩, match le_total x 1 with | (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in ⟨-y, by rw [exp_neg, hy, inv_inv']⟩ | (or.inr hx1) := this hx1 end /-- The real logarithm function, equal to `0` for `x ≤ 0` and to the inverse of the exponential for `x > 0`. -/ noncomputable def log (x : ℝ) : ℝ := if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0 lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x := by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx) @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) @[simp] lemma log_zero : log 0 = 0 := by simp [log, lt_irrefl] @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy] lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := ⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂, (real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩ lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x := begin by_cases h : 0 < x, { rw ← log_one, exact log_lt_log_iff (by norm_num) h }, { rw [log, dif_neg], split, repeat {intro, linarith} } end lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2 lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h (by norm_num) } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg : 1 ≤ x → 0 ≤ log x := by { intro, rwa [← log_one, log_le_log], norm_num, linarith } lemma log_nonpos : x ≤ 1 → log x ≤ 0 := begin intro, by_cases hx : 0 < x, { rwa [← log_one, log_le_log], exact hx, norm_num }, { simp [log, dif_neg hx] } end section prove_log_is_continuous lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) := begin rw tendsto_nhds_nhds, assume ε ε0, let δ := min (exp ε - 1) (1 - exp (-ε)), have : 0 < δ, refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _), by { rw exp_lt_one_iff, linarith }, use [δ, this], assume x h, cases le_total 1 x with hx hx, { have h : x < exp ε, rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h, linarith [(min_le_left _ _ : δ ≤ exp ε - 1)], calc abs (log x - 0) = abs (log x) : by simp ... = log x : abs_of_nonneg $ log_nonneg hx ... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }}, { have h : exp (-ε) < x, rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h, linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))], have : 0 < x := lt_trans (exp_pos _) h, calc abs (log x - 0) = abs (log x) : by simp ... = -log x : abs_of_nonpos $ log_nonpos hx ... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } } end lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) := continuous_iff_continuous_at.2 $ λ x, begin rw continuous_at, let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1), let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos x.2) y.2), have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))), have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1, ext h, rw ← log_mul x.2 h.2, simp only [this, log_mul x.2 zero_lt_one, log_one], exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val), have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos x.2) x.2⟩), rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val, suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)), begin convert h, ext y, have : x.val * (x.val⁻¹ * y.val) = y.val, rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul], show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this end, exact tendsto.comp (by rwa mul_one at H1) (by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption }) end lemma continuous_at_log (hx : 0 < x) : continuous_at log x := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx) (mem_nhds_sets (is_open_lt' _) hx) /-- Three forms of the continuity of `real.log` is provided. For the other two forms, see `real.continuous_log'` and `real.continuous_at_log` -/ lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a) (hf : continuous f) : continuous (λa, log (f a)) := show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩), from continuous_log'.comp (continuous_subtype_mk _ hf) end prove_log_is_continuous lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 := intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on ⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩ /-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/ noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero localized "notation `π` := real.pi" in real @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).2 lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.1 lemma pi_div_two_le_two : π / 2 ≤ 2 := by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)]; exact (classical.some_spec exists_cos_eq_zero).1.2 lemma two_le_pi : (2 : ℝ) ≤ π := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two) lemma pi_le_four : π ≤ 4 := (div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1 (calc π / 2 ≤ 2 : pi_div_two_le_two ... = 4 / 2 : by norm_num) lemma pi_pos : 0 < π := lt_of_lt_of_le (by norm_num) two_le_pi lemma pi_div_two_pos : 0 < π / 2 := half_pos pi_pos lemma two_pi_pos : 0 < 2 * π := by linarith [pi_pos] @[simp] lemma sin_pi : sin π = 0 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div, sin_add, cos_pi_div_two]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc, cos_two_mul, cos_pi_div_two]; simp [bit0, pow_add] @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x := if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2 else have (2 : ℝ) + 2 = 4, from rfl, have π - x ≤ 2, from sub_le_iff_le_add.2 (le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)), sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x := match lt_or_eq_of_le h0x with | or.inl h0x := (lt_or_eq_of_le hxp).elim (le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x) (λ hpx, by simp [hpx]) | or.inr h0x := by simp [h0x.symm] end lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 := neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx) lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 := neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx) @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := have sin (π / 2) = 1 ∨ sin (π / 2) = -1 := by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2), this.resolve_right (λ h, (show ¬(0 : ℝ) < -1, by norm_num) $ h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos)) lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x := sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith) lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x := match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with | or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂) | or.inl hx₁, or.inr hx₂ := by simp [hx₂] | or.inr hx₁, _ := by simp [hx₁.symm] end lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 := neg_pos.1 $ cos_pi_sub x ▸ cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith) lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 := neg_nonneg.1 $ cos_pi_sub x ▸ cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith) lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) : sin x = 0 ↔ x = 0 := ⟨λ h, le_antisymm (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂ ... = 0 : h)) (le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $ calc 0 = sin x : h.symm ... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)), λ h, by simp [h]⟩ lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x := ⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos)) (sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos)) (by simp [sub_eq_add_neg, sin_add, h, sin_int_mul_pi]))⟩, λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩ lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 := by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x, pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self]; exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩ theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) := begin have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2), have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2, rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm] end lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x := ⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in ⟨n / 2, (int.mod_two_eq_zero_or_one n).elim (λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel ((int.dvd_iff_mod_eq_zero _ _).2 hn0)]) (λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul, one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn; rw [← hn, cos_int_mul_two_pi_add_pi] at h; exact absurd h (by norm_num))⟩, λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩ theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 := begin rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff], split, { rintro ⟨n, hn⟩, existsi -n, rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] }, { rintro ⟨n, hn⟩, existsi -n, rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero, sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] } end lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 := ⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in begin clear _let_match, subst hn, rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂, rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt, ← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁, exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))), end, λ h, by simp [h]⟩ theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) := by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left, add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub, ← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm] lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x := calc cos y = cos x * cos (y - x) - sin x * sin (y - x) : by rw [← cos_add, add_sub_cancel'_right] ... < (cos x * 1) - sin x * sin (y - x) : sub_lt_sub_right ((mul_lt_mul_left (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁) (lt_of_lt_of_le hxy hy₂))).2 (lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt (show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1 (sub_ne_zero.2 (ne_of_lt hxy).symm)))) _ ... ≤ _ : by rw mul_one; exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith)) (sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith))) lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x := match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with | or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy | or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim (λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos]) ... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx) (λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos]) ... = cos x : by rw [hx, cos_pi_div_two]) | or.inr hx, or.inl hy := by linarith | or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub]; apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith) end lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y := by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)]; apply cos_lt_cos_of_nonneg_of_le_pi; linarith lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y := (lt_or_eq_of_le hxy).elim (le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂) (λ h, h ▸ le_refl _) lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y) (hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : cos x = cos y) : x = y := begin rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy, refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy); linarith end lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) := by convert intermediate_value_Icc (le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos)) continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two] lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x := begin cases le_or_gt x 1 with h' h', { have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.2, rw [sub_le_iff_le_add', hx] at this, apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)), apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h }, exact lt_of_le_of_lt (sin_le_one x) h' end /- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6. note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/ lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x := begin have hx : abs x = x := abs_of_nonneg (le_of_lt h), have : abs x ≤ 1, rwa [hx], have := sin_bound this, rw [abs_le] at this, have := this.1, rw [le_sub_iff_add_le, hx] at this, refine lt_of_lt_of_le _ this, rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left, apply add_lt_of_lt_sub_left, rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12, by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num), apply mul_lt_mul', { rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)), rw mul_le_mul_right, exact h', apply pow_pos h }, norm_num, norm_num, apply pow_pos h end /-- The type of angles -/ def angle : Type := quotient_add_group.quotient (gmultiples (2 * π)) namespace angle instance angle.add_comm_group : add_comm_group angle := quotient_add_group.add_comm_group _ instance : inhabited angle := ⟨0⟩ instance angle.has_coe : has_coe ℝ angle := ⟨quotient.mk'⟩ instance angle.is_add_group_hom : @is_add_group_hom ℝ angle _ _ (coe : ℝ → angle) := @quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _) @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl @[simp] lemma coe_smul (x : ℝ) (n : ℕ) : ↑(add_monoid.smul n x : ℝ) = add_monoid.smul n (↑x : angle) := add_monoid_hom.map_smul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := add_monoid_hom.map_gsmul ⟨coe, coe_zero, coe_add⟩ _ _ @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩ lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero, false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] }, { left, rw [eq_div_iff_mul_eq _ _ (@two_ne_zero ℝ _), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, ← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero], rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h, { left, rw coe_sub at h, exact sub_left_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero, cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, cases quotient.exact' hc with n hn, dsimp only at hn, rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end end angle /-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`. If the argument is not between `-1` and `1` it defaults to `0` -/ noncomputable def arcsin (x : ℝ) : ℝ := if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0 lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2 else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x := if hx : -1 ≤ x ∧ x ≤ 1 then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1 else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos) lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x := by rw [arcsin, dif_pos (and.intro hx₁ hx₂)]; exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2 lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂ (by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _)) lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arcsin x = arcsin y) : x = y := by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy] @[simp] lemma arcsin_zero : arcsin 0 = 0 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) (by rw [sin_arcsin, sin_zero]; norm_num) @[simp] lemma arcsin_one : arcsin 1 = π / 2 := sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (by linarith [pi_pos]) (le_refl _) (by rw [sin_arcsin, sin_pi_div_two]; norm_num) @[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x := if h : -1 ≤ x ∧ x ≤ 1 then have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm], sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_le_neg (arcsin_le_pi_div_two _)) (neg_le.1 (neg_pi_div_two_le_arcsin _)) (by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2]) else have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm], by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero] @[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x := if hx₁ : x ≤ 1 then not_lt.1 (λ h, not_lt.2 hx begin have := sin_lt_sin_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h, rw [real.sin_arcsin, sin_zero] at this; linarith end) else by rw [arcsin, dif_neg]; simp [hx₁] lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 := ⟨λ h, have sin (arcsin x) = 0, by simp [h], by rwa [sin_arcsin hx₁ hx₂] at this, λ h, by simp [h]⟩ lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x := lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁)) (ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm)) lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 := neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx)) /-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`. If the argument is not between `-1` and `1` it defaults to `π / 2` -/ noncomputable def arccos (x : ℝ) : ℝ := π / 2 - arcsin x lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [sub_eq_add_neg, arccos] lemma arccos_le_pi (x : ℝ) : arccos x ≤ π := by unfold arccos; linarith [neg_pi_div_two_le_arcsin x] lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x := by unfold arccos; linarith [arcsin_le_pi_div_two x] lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x := by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂] lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x := by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1) (hxy : arccos x = arccos y) : x = y := arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at * @[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos] @[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos] @[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves] lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x := by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) := cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) := have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x), begin rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))), pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this, rw [this, sin_arcsin hx₁ hx₂], end lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) := by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂] lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 := have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁, by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul, mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _), ← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)), abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm]; exact lt_add_one _ lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).2 lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) := (abs_lt.1 (abs_div_sqrt_one_add_lt _)).1 lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x := by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp) lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x := match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with | or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp) | or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos] | or.inr hx0, _ := by simp [hx0.symm] end lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 := neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 := neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos])) lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := begin rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos], exact div_lt_div (sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂) (by linarith) (le_of_lt hy₂) hxy) (cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy)) (sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith)) (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂) end lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y := match le_total x 0, le_total y 0 with | or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁) (neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy) | or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim (λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁) ... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂) (λ hy0, by rw [← hy0, tan_zero]; exact tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁) | or.inr hx0, or.inl hy0 := by linarith | or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy end lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) (hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y := match lt_trichotomy x y with | or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _) | or.inr (or.inl h) := h | or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _) end /-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/ noncomputable def arctan (x : ℝ) : ℝ := arcsin (x / sqrt (1 + x ^ 2)) lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) := sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)) lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) := have h₁ : (0 : ℝ) < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _), have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1, by rw [pow_two, ← abs_mul_self, _root_.abs_mul]; exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _) (abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)), by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)), div_pow, pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁), ← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub, mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))]; simp lemma tan_arctan (x : ℝ) : tan (arctan x) = x := by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one, mul_div_assoc, div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))), mul_one] lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 := lt_of_le_of_ne (arcsin_le_pi_div_two _) (λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two]) lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x := lt_of_le_of_ne (neg_pi_div_two_le_arcsin _) (λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $ by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two]) lemma tan_surjective : function.surjective tan := function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩ lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x := tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _) (arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan) @[simp] lemma arctan_zero : arctan 0 = 0 := by simp [arctan] @[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x := by simp [arctan, neg_div] end real namespace complex open_locale real /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma arg_le_pi (x : ℂ) : arg x ≤ π := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos)) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact le_sub_iff_add_le.1 (by rw sub_self; exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx))) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _) (by linarith [real.pi_pos])) lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := if hx₁ : 0 ≤ x.re then by rw [arg, if_pos hx₁]; exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _) else have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁, if hx₂ : 0 ≤ x.im then by rw [arg, if_neg hx₁, if_pos hx₂]; exact sub_lt_iff_lt_add.1 (lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _)) else by rw [arg, if_neg hx₁, if_neg hx₂]; exact lt_sub_iff_add_lt.2 (by rw neg_add_self; exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂)) (abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2)) lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) : arg x = arg (-x) + π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg] lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) : arg x = arg (-x) - π := have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos], by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs := have 0 ≤ 1 - (x.im / abs x) ^ 2, from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two]; exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _), by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x), arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this, sub_mul, div_pow, ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)), one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr else have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, if hxi : 0 ≤ x.im then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr, by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]; simp [neg_div] else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)]; simp [sub_eq_add_neg, real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this] lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re := if hx : x = 0 then by simp [hx] else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx, field.div_div_div_cancel_right _ (mt abs_eq_zero.1 hx)] lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) : arg (cos x + sin x * I) = x := if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2 then have hx₄ : 0 ≤ (cos x + sin x * I).re, by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2, by rw [arg, if_pos hx₄]; simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2] else if hx₄ : x < -(π / 2) then have hx₅ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬ 0 ≤ real.cos x, by simpa, not_le.2 $ by rw ← real.cos_neg; apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im := suffices real.sin x < 0, by simpa, by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith, suffices -π + -real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₅, if_neg hx₆]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; try {simp [add_left_comm]}; linarith else have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith, have hx₆ : ¬0 ≤ (cos x + sin x * I).re := suffices ¬0 ≤ real.cos x, by simpa, not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith, have hx₇ : 0 ≤ (cos x + sin x * I).im := suffices 0 ≤ real.sin x, by simpa, by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith, suffices π - real.arcsin (real.sin x) = x, by rw [arg, if_neg hx₆, if_pos hx₇]; simpa [sub_eq_add_neg, add_comm, abs_cos_add_sin_mul_I, sin_of_real_re], by rw [← real.sin_pi_sub, real.arcsin_sin]; simp [sub_eq_add_neg]; linarith lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx), have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy), ⟨λ h, begin have hcos := congr_arg real.cos h, rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos, have hsin := congr_arg real.sin h, rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin, apply complex.ext, { rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm, ← mul_div_assoc, hcos, mul_div_cancel _ hax] }, { rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero, mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] } end, λ h, have hre : abs (y / x) * x.re = y.re, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg re h, have hre' : abs (x / y) * y.re = x.re, by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have him : abs (y / x) * x.im = y.im, by rw ← of_real_div at h; simpa [-of_real_div] using congr_arg im h, have him' : abs (x / y) * y.im = x.im, by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div, mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul], have hxya : x.im / abs x = y.im / abs y, by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay], have hnxya : (-x).im / abs x = (-y).im / abs y, by rw [neg_im, neg_im, neg_div, neg_div, hxya], if hxr : 0 ≤ x.re then have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr, by simp [arg, *] at * else have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr, if hxi : 0 ≤ x.im then have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi, by simp [arg, *] at * else have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi, by simp [arg, *] at *⟩ lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := if hx : x = 0 then by simp [hx] else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $ by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc, of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul, div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm), div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := if hy : y = 0 then by simp * at * else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *, by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂ lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg]; simp [*, le_iff_eq_or_lt, lt_neg] /-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`. `log 0 = 0`-/ noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log] lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log] lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x := by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx, ← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc, mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im] lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π) (hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y := by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy; exact complex.ext (real.exp_injective $ by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy) (by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _), arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy) lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x := exp_inj_of_neg_pi_lt_of_le_pi (by rw log_im; exact neg_pi_lt_arg _) (by rw log_im; exact arg_le_pi _) hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)]) lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x := complex.ext (by rw [log_re, of_real_re, abs_of_nonneg hx]) (by rw [of_real_im, log_im, arg_of_real_of_nonneg hx]) @[simp] lemma log_zero : log 0 = 0 := by simp [log] @[simp] lemma log_one : log 1 = 0 := by simp [log] lemma log_neg_one : log (-1) = π * I := by simp [log] lemma log_I : log I = π / 2 * I := by simp [log] lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log] lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) := have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1, from λ h₁ h₂, begin rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁, have := real.exp_pos x.re, rw ← h₁ at this, exact absurd this (by norm_num) end, calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff] ... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 : begin rw exp_eq_exp_re_mul_sin_add_cos, simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re, real.exp_ne_zero], split; finish [real.sin_eq_zero_iff_cos_eq] end ... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 : by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff] ... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) : ⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩, λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩, by simp [hn]⟩⟩ lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 := by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)] lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) := by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add'] @[simp] lemma cos_pi_div_two : cos (π / 2) = 0 := calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp ... = 0 : by simp @[simp] lemma sin_pi_div_two : sin (π / 2) = 1 := calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp ... = 1 : by simp @[simp] lemma sin_pi : sin π = 0 := by rw [← of_real_sin, real.sin_pi]; simp @[simp] lemma cos_pi : cos π = -1 := by rw [← of_real_cos, real.cos_pi]; simp @[simp] lemma sin_two_pi : sin (2 * π) = 0 := by simp [two_mul, sin_add] @[simp] lemma cos_two_pi : cos (2 * π) = 1 := by simp [two_mul, cos_add] lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x := by simp [sin_add] lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x := by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi] lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x := by simp [cos_add, cos_two_pi, sin_two_pi] lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x := by simp [cos_add] lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x := by simp [sub_eq_add_neg, cos_add] lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x := by simp [sin_add] lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x := by simp [sub_eq_add_neg, sin_add] lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x := by simp [sub_eq_add_neg, sin_add] lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x := by simp [cos_add] lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x := by simp [sub_eq_add_neg, cos_add] lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x := by rw [← cos_neg, neg_sub, cos_sub_pi_div_two] lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 := by induction n; simp [add_mul, sin_add, *] lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 := by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi] lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 := by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi] lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 := by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe, int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg, (neg_mul_eq_neg_mul _ _).symm, cos_neg] lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 := by simp [cos_add, sin_add, cos_int_mul_two_pi] section pow /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_def, hx, mul_comm, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw fpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := have (log x * (↑n)⁻¹).im = (log x).im / n, by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im, of_real_re, of_real_im]; simp, have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π, from (le_total (log x).im 0).elim (λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg] ... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn) (mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h) ... = (log x * (↑n)⁻¹).im : by simp [this], this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn)) (le_of_lt real.pi_pos)⟩) (λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos) (div_nonneg h (nat.cast_pos.2 hn)), calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this] ... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn) (mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)) ... ≤ _ : by simp [log, arg_le_pi]⟩), by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2, inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)), cpow_one] end pow end complex namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log (-x)) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log (-x) * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y := abs_le_of_le_of_neg_le begin cases lt_trichotomy 0 x, { rw abs_of_pos h }, cases h, { simp [h.symm] }, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _) ... = _ : mul_one _ end begin cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith }, cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}}, rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h], calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring ... ≤ exp (log (-x) * y) * 1 : mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _) ... = exp (log (-x) * y) : mul_one _ end end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real open_locale real variables {x y z : ℝ} @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * @[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast, complex.of_real_nat_cast, complex.of_real_re] @[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂, have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂, rw [log_mul hx hy, add_mul, exp_add]}, { exact h₁}, { exact h}, { exact mul_nonneg h h₁}, end lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := begin rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃, { refl}, { simp [*, not_le_of_gt zero_lt_one] at *}, { have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h, rw [←log_le_log zero_lt_one hx, log_one] at h, have pos : 0 ≤ log x * z, exact mul_nonneg h h₁, rwa [←exp_le_exp, exp_zero] at pos}, { exact le_trans zero_le_one h}, end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rw le_iff_eq_or_lt at h h₂, cases h₂, { rw [←h₂, rpow_zero, rpow_zero]}, { cases h, { rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs, { exact zero_le_one}, { refl}, { exact le_of_lt (exp_pos (log y * z))}, { rwa ←h at h₁}, { exact ne.symm (ne_of_lt h₂)}}, { have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁, have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂), rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc], rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm], exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } } end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1), end lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 := by rw ←one_rpow e; apply rpow_le_rpow; assumption lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz } lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] section prove_rpow_is_continuous lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) := suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)), by { convert h, ext p, rw rpow_def_of_pos p.2 }, continuous_exp.comp $ (show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id) lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) := suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)), by { convert h, ext p, rw [rpow_def_of_neg p.2] }, (continuous_exp.comp $ (show continuous $ (λp:{p:ℝ//0<p}, log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩), from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $ continuous_fst.comp continuous_subtype_val).mul (continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul (continuous_cos.comp $ (continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const) lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := begin cases lt_trichotomy 0 x, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h), cases h, { exact absurd h.symm hx }, exact continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h) (mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h) end lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) := continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩, begin by_cases hx₀ : x₀ = 0, { simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0, rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩, let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos, let δ := min (min q (ε ^ (1 / q))) (1/2), have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num), have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _), have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _), have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num), use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩, simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero], assume h, rw max_lt_iff at h, cases h with xδ yy₀, have qy : q < y, calc q < y₀ / 2 : q_lt ... = y₀ - y₀ / 2 : (sub_half _).symm ... ≤ y₀ - δ : by linarith ... < y : sub_lt_of_abs_sub_lt_left yy₀, calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _ ... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy ... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} } ... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} } ... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }}, { exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1 (continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at } end lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) : continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) := continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy) (mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy) variables {α : Type*} [topological_space α] {f g : α → ℝ} /-- `real.rpow` is continuous at all points except for the lower half of the y-axis. In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`. Multiple forms of the claim is provided in the current section. -/ lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_iff_continuous_at.2 $ λ a, begin show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a, refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _), { replace h := h a, cases h, { exact continuous_at_rpow_of_ne_zero h _ }, { exact continuous_at_rpow_of_pos h _ }}, end lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g): continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg end prove_rpow_is_continuous section sqrt lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) := begin funext, by_cases h : 0 ≤ x, { rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h], norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ }, { replace h : x < 0 := lt_of_not_ge h, have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end lemma continuous_sqrt : continuous sqrt := by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const end sqrt section exp /-- The real exponential function tends to +infinity at +infinity -/ lemma tendsto_exp_at_top : tendsto exp at_top at_top := begin have A : tendsto (λx:ℝ, x + 1) at_top at_top := tendsto_at_top_add_const_right at_top 1 tendsto_id, have B : ∀ᶠ x in at_top, x + 1 ≤ exp x, { have : ∀ᶠ (x : ℝ) in at_top, 0 ≤ x := mem_at_top 0, filter_upwards [this], exact λx hx, add_one_le_exp_of_nonneg hx }, exact tendsto_at_top_mono' at_top B A end /-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0` at +infinity -/ lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm) /-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/ lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top := begin have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n, have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos, have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n, { assume x hx, let y := x / (n+1), have y_pos : 0 < y := div_pos hx n_pos, have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc exp y = exp y * 1 : by simp ... ≤ exp y * (exp y / y)^n : begin apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)), apply one_le_div_of_le _ y_pos, apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)), exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one) end ... = exp y * exp (n * y) / y^n : by rw [div_pow, exp_nat_mul, mul_div_assoc] ... = exp ((n + 1) * y) / y^n : by rw [← exp_add, add_mul, one_mul, add_comm] ... = exp x / (x / (n+1))^n : by { dsimp [y], rw mul_div_cancel' _ n_ne_zero } ... = (n+1)^n * (exp x / x^n) : by rw [← mul_div_assoc, div_pow, div_div_eq_mul_div, mul_comm], rwa div_le_iff' (pow_pos n_pos n) }, have B : ∀ᶠ x in at_top, exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n := mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩, have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top := tendsto_at_top_div (pow_pos n_pos n) (tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)), exact tendsto_at_top_mono' at_top B C end /-- The function `x^n * exp(-x)` tends to `0` at +infinity, for any natural number `n`. -/ lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) := (tendsto_inv_at_top_zero.comp (tendsto_exp_div_pow_at_top n)).congr $ λx, by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg] end exp end real lemma has_deriv_at.rexp {f : ℝ → ℝ} {f' x : ℝ} (hf : has_deriv_at f f' x) : has_deriv_at (real.exp ∘ f) (f' * real.exp (f x)) x := (real.has_deriv_at_exp (f x)).comp x hf lemma has_deriv_within_at.rexp {f : ℝ → ℝ} {f' x : ℝ} {s : set ℝ} (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (real.exp ∘ f) (f' * real.exp (f x)) s x := (real.has_deriv_at_exp (f x)).comp_has_deriv_within_at x hf
9e27add34262b3b69ed17f775d813f6ac97bf084
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/solutions/thursday/afternoon/category_theory/exercise8.lean
f744799047a4aace432fc5d03f4083b1effd70a1
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
1,556
lean
import algebra.category.Module.basic import linear_algebra.finite_dimensional /-! Every monomorphism in fdVec splits. This is not-so-secretly an exercise in using the linear algebra library -/ variables (𝕜 : Type) [field 𝕜] open category_theory abbreviation Vec := Module 𝕜 @[derive category] def fdVec := { V : Vec 𝕜 // finite_dimensional 𝕜 V } /-- We set up a `has_coe_to_sort` for `fdVec 𝕜`, sending an object directly to the underlying type. -/ instance : has_coe_to_sort (fdVec 𝕜) := { S := Type*, coe := λ V, V.val, } /-- Lean can already work out that this underlying type has the `module 𝕜` typeclass. -/ example (V : fdVec 𝕜) : module 𝕜 V := by apply_instance /-- But we need to tell it about the availability of the `finite_dimensional 𝕜` typeclass. -/ instance fdVec_finite_dimensional (V : fdVec 𝕜) : finite_dimensional 𝕜 V := V.property def exercise {X Y : fdVec 𝕜} (f : X ⟶ Y) [mono f] : split_mono f := -- We want to -- * pick a basis of `X`, using `exists_is_basis` -- * see that its image under `f` is linearly independent in `Y`, using `linear_independent.image_subtype` -- * extend that set to a basis of `Y` using `exists_subset_is_basis` -- * define a map back using `is_basis.constr` -- * check it has the right property, using `is_basis.ext` sorry /-! In practice, one should just prove this theorem directly in the linear algebra library, without reference to `fdVec`. The statement will be more verbose! The proof of the "categorical" statement should just be one line. -/
d7f2c0ab57052bcc806b8ee40b1a1d3ea7c5b06e
fe208a542cea7b2d6d7ff79f94d535f6d11d814a
/src/Logic/buzzard_effort.lean
e5a84c40d788cf1279ebfc6f2ede92cd8dfb7c05
[]
no_license
ImperialCollegeLondon/M1F_room_342_questions
c4b98b14113fe900a7f388762269305faff73e63
63de9a6ab9c27a433039dd5530bc9b10b1d227f7
refs/heads/master
1,585,807,312,561
1,545,232,972,000
1,545,232,972,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
977
lean
inductive fml | atom (i : ℕ) | imp (a b : fml) | not (a : fml) open fml infixr ` →' `:50 := imp -- right associative notation `¬' ` := fml.not inductive prf : fml → Type | axk {p q} : prf (p →' q →' p) | axs {p q r} : prf $ (p →' q →' r) →' (p →' q) →' (p →' r) | axX {p q} : prf $ ((¬' q) →' (¬' p)) →' p →' q | mp {p q} : prf p → prf (p →' q) → prf q open prf lemma p_of_p_of_p_of_q (p q : fml) : prf $ (p →' q) →' (p →' p) := begin apply mp (p →' q →' p) ((p →' q) →' p →' p) (axk p q), exact axs p q p end lemma p_of_p_of_p_of_q' (p q : fml) : prf $ (p →' q) →' (p →' p) := mp (p →' q →' p) ((p →' q) →' p →' p) (axk p q) (axs p q p) lemma p_of_p_of_p_of_q'' (p q : fml) : prf $ (p →' q) →' (p →' p) := mp axk axs -- question 6a on Britnell sheet theorem p_of_p (p : fml) : prf $ p →' p := begin exact mp (p →' p →' p) (p →' p) (axk p p) (p_of_p_of_p_of_q p (p →' p)), end
5750ff6d4955a739927e3dd44805401d12267df0
53f7fd7840fe4979de24f9611c89f2ee1b4fc5dc
/src/two_tree.lean
a70cc32c10708621d1f86621c972cd245ee2cf22
[]
no_license
cipher1024/search-trees
6d1925283c6ce47d84bdf41ca40d8317ff2e64d7
0e0ea0ee59f0b0499ebad1ef6f34f09ec9666cde
refs/heads/master
1,673,300,158,759
1,603,984,112,000
1,603,984,112,000
308,132,998
1
0
null
null
null
null
UTF-8
Lean
false
false
23,052
lean
import tactic.default .tactic .basic universes u v w namespace two_three variables (α : Type u) (β : Type v) {γ : Type w} open tree nat variables {α β} inductive liftp (p : α → Prop) : tree α β → Prop | leaf {k v} : p k → liftp (tree.leaf k v) | node2 {x} {t₀ t₁} : p x → liftp t₀ → liftp t₁ → liftp (tree.node2 t₀ x t₁) | node3 {x y} {t₀ t₁ t₂} : p x → p y → liftp t₀ → liftp t₁ → liftp t₂ → liftp (tree.node3 t₀ x t₁ y t₂) -- | node4 {x y z} {t₀ t₁ t₂ t₃} : -- p x → p y → p z → -- liftp t₀ → liftp t₁ → -- liftp t₂ → liftp t₃ → -- liftp (tree.node4 t₀ x t₁ y t₂ z t₃) lemma liftp_true {t : tree α β} : liftp (λ _, true) t := begin induction t; repeat { trivial <|> assumption <|> constructor }, end lemma liftp_map {p q : α → Prop} {t : tree α β} (f : ∀ x, p x → q x) (h : liftp p t) : liftp q t := begin induction h; constructor; solve_by_elim end lemma liftp_and {p q : α → Prop} {t : tree α β} (h : liftp p t) (h' : liftp q t) : liftp (λ x, p x ∧ q x) t := begin induction h; cases h'; constructor; solve_by_elim [and.intro] end lemma exists_of_liftp {p : α → Prop} {t : tree α β} (h : liftp p t) : ∃ x, p x := begin cases h; split; assumption end section defs variables [has_le α] [has_lt α] open tree nat variables [@decidable_rel α (<)] def insert' (x : α) (v' : β) : tree α β → (tree α β → γ) → (tree α β → α → tree α β → γ) → γ | (tree.leaf y v) ret_one inc_two := match cmp x y with | ordering.lt := inc_two (tree.leaf x v') y (tree.leaf y v) | ordering.eq := ret_one (tree.leaf y v') | ordering.gt := inc_two (tree.leaf y v) x (tree.leaf x v') end | (tree.node2 t₀ y t₁) ret_one inc_two := if x < y then insert' t₀ (λ t', ret_one $ tree.node2 t' y t₁) (λ ta k tb, ret_one $ tree.node3 ta k tb y t₁) else insert' t₁ (λ t', ret_one $ tree.node2 t₀ y t') (λ ta k tb, ret_one $ tree.node3 t₀ y ta k tb) | (tree.node3 t₀ y t₁ z t₂) ret_one inc_two := if x < y then insert' t₀ (λ t', ret_one $ tree.node3 t' y t₁ z t₂) (λ ta k tb, inc_two (tree.node2 ta k tb) y (tree.node2 t₁ z t₂)) else if x < z then insert' t₁ (λ t', ret_one $ tree.node3 t₀ y t' z t₂) (λ ta k tb, inc_two (tree.node2 t₀ y ta) k (tree.node2 tb z t₂)) else insert' t₂ (λ t', ret_one $ tree.node3 t₀ y t₁ z t') (λ ta k tb, inc_two (tree.node2 t₀ y t₁) z (tree.node2 ta k tb)) def insert (x : α) (v' : β) (t : tree α β) : tree α β := insert' x v' t id tree.node2 -- inductive shrunk (α : Type u) : ℕ section add_ variables (ret shr : tree α β → γ) def add_left : tree α β → α → tree α β → γ | t₀ x t@(tree.leaf _ _) := ret t₀ | t₀ x (tree.node2 t₁ y t₂) := shr (tree.node3 t₀ x t₁ y t₂) | t₀ x (tree.node3 t₁ y t₂ z t₃) := ret (tree.node2 (tree.node2 t₀ x t₁) y (tree.node2 t₂ z t₃)) def add_right : tree α β → α → tree α β → γ | t@(tree.leaf _ _) x t₀ := ret t | (tree.node2 t₀ x t₁) y t₂ := shr (tree.node3 t₀ x t₁ y t₂) | (tree.node3 t₀ x t₁ y t₂) z t₃ := ret (tree.node2 (tree.node2 t₀ x t₁) y (tree.node2 t₂ z t₃)) variables (t₀ : tree α β) (x : α) (t₁ : tree α β) (y : α) (t₂ : tree α β) def add_left_left : Π (t₀ : tree α β) (x : α) (t₁ : tree α β) (y : α) (t₂ : tree α β), γ | t₀ x (tree.leaf k v) z t₂ := ret t₀ | t₀ x (tree.node2 t₁ y t₂) z t₃ := ret (tree.node2 (tree.node3 t₀ x t₁ y t₂) z t₃) | t₀ w (tree.node3 t₁ x t₂ y t₃) z t₄ := ret (tree.node3 (tree.node2 t₀ w t₁) x (tree.node2 t₂ y t₃) z t₄) def add_middle : Π (t₀ : tree α β) (x : α) (t₁ : tree α β) (y : α) (t₂ : tree α β), γ | t@(tree.leaf k v) y t₁ z t₂ := ret t | (tree.node2 t₀ x t₁) y t₂ z t₃ := ret (tree.node2 (tree.node3 t₀ x t₁ y t₂) z t₃) | (tree.node3 t₀ w t₁ x t₂) y t₃ z t₄ := ret (tree.node3 (tree.node2 t₀ w t₁) x (tree.node2 t₂ y t₃) z t₄) def add_right_right : Π (t₀ : tree α β) (x : α) (t₁ : tree α β) (y : α) (t₂ : tree α β), γ | t₀ x (tree.leaf k v) z t₂ := ret t₀ | t₀ x (tree.node2 t₁ y t₂) z t₃ := ret (tree.node2 t₀ x (tree.node3 t₁ y t₂ z t₃)) | t₀ w (tree.node3 t₁ x t₂ y t₃) z t₄ := ret (tree.node3 t₀ w (tree.node2 t₁ x t₂) y (tree.node2 t₃ z t₄)) end add_ def delete' [decidable_eq α] (x : α) : tree α β → (option α → tree α β → γ) → (option α → tree α β → γ) → (unit → γ) → γ | (tree.leaf y v) ret shr del := if x = y then del () else ret (some y) (tree.leaf y v) | (tree.node2 t₀ y t₁) ret shr del := if x < y then delete' t₀ (λ a t', ret a $ tree.node2 t' y t₁) (λ a t', add_left (ret a) (shr a) t' y t₁) (λ _, shr (some y) t₁) else delete' t₁ (λ y' t', ret none $ tree.node2 t₀ (y'.get_or_else y) t') (λ y' t', add_right (ret none) (shr none) t₀ (y'.get_or_else y) t') (λ _, shr none t₀) | (tree.node3 t₀ y t₁ z t₂) ret shr del := if x < y then delete' t₀ (λ a t', ret a $ tree.node3 t' y t₁ z t₂) (λ a t', add_left_left (ret a) t' y t₁ z t₂) (λ _, ret (some y) $ tree.node2 t₁ z t₂) else if x < z then delete' t₁ (λ a t', ret none $ tree.node3 t₀ (a.get_or_else y) t' z t₂) (λ a t', add_middle (ret none) t₀ y t' z t₂) (λ _, ret none $ tree.node2 t₀ z t₂) else delete' t₂ (λ a t', ret none $ tree.node3 t₀ y t₁ (a.get_or_else z) t') (λ a t', add_right_right (ret none) t₀ y t₁ z t') (λ _, ret none $ tree.node2 t₀ y t₁) def delete [decidable_eq α] (x : α) (t : tree α β) : option (tree α β) := delete' x t (λ _, some) (λ _, some) (λ _, none) end defs local attribute [simp] add_left add_right add_left_left add_middle add_right_right first last variables [linear_order α] -- #check @above_of_above_of_forall_le_of_le lemma first_le_last_of_sorted {t : tree α β} (h : sorted' t) : first t ≤ last t := begin induction h; subst_vars; dsimp [first, last], { refl }, repeat { solve_by_elim [le_of_lt] <|> transitivity }, end lemma eq_of_below {x : option α} {y : α} (h : below x y) : x.get_or_else y = y := by cases h; refl lemma above_of_above_of_le {x y : α} {k} (h : x ≤ y) (h' : above y k) : above x k := by cases h'; constructor; solve_by_elim [lt_of_le_of_lt] @[interactive] meta def interactive.saturate : tactic unit := do tactic.interactive.casesm (some ()) [``(above _ (some _)), ``(below (some _) _), ``(below' (some _) _)], tactic.find_all_hyps ``(sorted' _) $ λ h, do { n ← tactic.get_unused_name `h, tactic.mk_app ``first_le_last_of_sorted [h] >>= tactic.note n none, tactic.skip }, tactic.find_all_hyps ``(below _ _) $ λ h, do { n ← tactic.get_unused_name `h, tactic.mk_app ``eq_of_below [h] >>= tactic.note n none, tactic.skip }, tactic.find_all_hyps ``(¬ _ < _) $ λ h, do { -- n ← tactic.get_unused_name `h, tactic.mk_app ``le_of_not_gt [h] >>= tactic.note h.local_pp_name none, tactic.clear h, tactic.skip } @[interactive] meta def interactive.above : tactic unit := do -- tactic.interactive.saturate, tactic.find_hyp ``(above _ _) $ λ h, do tactic.refine ``(above_of_above_of_le _ %%h), tactic.interactive.chain_trans section sorted_insert variables (lb ub : option α) (P : γ → Prop) (ret : tree α β → γ) -- (ret' : tree α β → tree α β) (mk : tree α β → α → tree α β → γ) (h₀ : ∀ t, below lb (first t) → above (last t) ub → sorted' t → P (ret t)) (h₂ : ∀ t₀ x t₁, below lb (first t₀) → above (last t₀) (some x) → below (some x) (first t₁) → above (last t₁) ub → sorted' t₀ → sorted' t₁ → P (mk t₀ x t₁)) include h₀ h₂ lemma sorted_insert_aux' {k : α} {v : β} {t} (h : sorted' t) (h' : below lb (min k (first t))) (h'' : above k ub) (h''' : above (last t) ub) : P (insert' k v t ret mk) := begin -- generalize_hyp hlb : none = k₀ at h, induction h generalizing lb ub ret mk, case two_three.sorted'.leaf : k' v' lb ub ret mk h₀ h₂ h' h'' { dsimp [insert'], trichotomy k =? k'; dsimp [insert']; apply h₀ <|> apply h₂, all_goals { try { have h := le_of_lt h }, simp [first, h, min_eq_left, min_eq_right, min_self] at h', }, repeat { assumption <|> constructor <|> refl } }, case two_three.sorted'.node2 : x t₀ t₁ h h' h_a h_a_1 h_ih₀ h_ih₁ lb ub ret mk h₀ h₂ { dsimp [insert'], split_ifs; [apply @h_ih₀ lb (some x), apply @h_ih₁ (some x) ub]; clear h_ih₀ h_ih₁, all_goals { try { intros, apply h₀ <|> apply h₂ }, clear h₀ h₂, }, all_goals { casesm* [above _ (some _), below (some _) _], dsimp [first, last] at * { fail_if_unchanged := ff }, repeat { assumption <|> constructor } }, all_goals { find_all_hyps foo := ¬ (_ < _) then { replace foo := le_of_not_gt foo }, find_all_hyps ht := sorted' _ then { have hh := first_le_last_of_sorted ht } }, { rw min_eq_right at h'_1, assumption, chain_trans, }, { have h : first t₀ ≤ k, chain_trans, have hh' := min_eq_right h, cc, }, { subst x, rw min_eq_right h_1, constructor } }, case two_three.sorted'.node3 : x y t₀ t₁ t₂ h_a h_a_1 h_a_2 h_a_3 h_a_4 h_a_5 h_a_6 h_ih₀ h_ih₁ h_ih₂ lb ub ret mk h₀ h₂ h' h'' h''' { dsimp [insert'], split_ifs; [apply @h_ih₀ lb (some x), apply @h_ih₁ (some x) (some y), apply @h_ih₂ (some y) ub]; clear h_ih₀ h_ih₁ h_ih₂, all_goals { try { intros, apply h₀ <|> apply h₂ }, clear h₀ h₂, }, all_goals { casesm* [above _ (some _), below (some _) _], subst_vars, dsimp [first, last] at * { fail_if_unchanged := ff }, repeat { assumption <|> constructor } }, all_goals { find_all_hyps foo := ¬ (_ < _) then { replace foo := le_of_not_gt foo }, find_all_hyps ht := sorted' _ then { have hh := first_le_last_of_sorted ht }, have h₀ : first t₀ ≤ k; [chain_trans, skip], try { have h₁ : first t₁ ≤ k; [chain_trans, skip] }, try { have h₂ : first t₂ ≤ k; [chain_trans, skip] } }, { have hh' := min_eq_right h₀, cc, }, { have hh' := min_eq_right h₀, cc, }, { rw min_eq_right h₁, constructor, }, { have hh' := min_eq_right h₀, cc, }, { have hh' := min_eq_right h₀, cc, }, { rw min_eq_right h₂, constructor, } }, end end sorted_insert lemma sorted_insert {k : α} {v : β} {t : tree α β} (h : sorted' t) : sorted' (insert k v t) := sorted_insert_aux' none none _ _ _ (λ t _ _ h, h) (λ t₀ x t₁ h₀ h₁ h₂ h₃ ht₀ ht₁, sorted'.node2 (by cases h₁; assumption) (by cases h₂; refl) ht₀ ht₁) h (by constructor) (by constructor) (by constructor) section with_height_insert variables (n : ℕ) (P : γ → Prop) (ret : tree α β → γ) (mk : tree α β → α → tree α β → γ) (h₀ : ∀ t, with_height n t → P (ret t)) (h₂ : ∀ t₀ x t₁, with_height n t₀ → with_height n t₁ → P (mk t₀ x t₁)) include h₀ h₂ lemma with_height_insert_aux {k : α} {v : β} {t} (h : with_height n t) : P (insert' k v t ret mk) := begin induction h generalizing ret mk, case two_three.with_height.leaf : k' v' { dsimp [insert'], trichotomy k =? k', all_goals { dsimp [insert'], subst_vars, apply h₂ <|> apply h₀, repeat { constructor }, }, }, case two_three.with_height.node2 : h_n h_x h_t₀ h_t₁ h_a h_a_1 h_ih₀ h_ih₁ { dsimp [insert'], split_ifs, repeat { intro <|> apply h_ih₀ <|> apply h_ih₁ <|> apply h₀ <|> apply h₂ <|> assumption <|> constructor }, }, case two_three.with_height.node3 : h_n h_x h_y h_t₀ h_t₁ h_t₂ h_a h_a_1 h_a_2 h_ih₀ h_ih₁ h_ih₂ { dsimp [insert'], split_ifs, repeat { intro <|> apply h_ih₀ <|> apply h_ih₁ <|> apply h_ih₂ <|> apply h₀ <|> apply h₂ <|> assumption <|> constructor }, }, end end with_height_insert lemma with_height_insert {k : α} {v : β} {n t} (h : with_height n t) : with_height n (insert k v t) ∨ with_height (succ n) (insert k v t) := begin apply with_height_insert_aux _ (λ t' : tree α β, with_height n t' ∨ with_height (succ n) t') _ _ _ _ h, { introv h', left, apply h' }, { introv h₀ h₁, right, constructor; assumption } end section with_height_add_left variables (n : ℕ) (P : γ → Prop) (ret shr : tree α β → γ) variables (h₀ : ∀ t, with_height (succ (succ n)) t → P (ret t)) (h₁ : ∀ t, with_height (succ n) t → P (shr t)) include h₀ h₁ lemma with_height_add_left {k : α} {t₀ t₁} (h : with_height n t₀) (h' : with_height (succ n) t₁) : P (add_left ret shr t₀ k t₁) := begin cases h'; dsimp [add_left], { apply h₁, repeat { assumption <|> constructor}, }, { apply h₀, repeat { assumption <|> constructor}, }, end lemma with_height_add_right {k : α} {t₀ t₁} (h : with_height (succ n) t₀) (h' : with_height n t₁) : P (add_right ret shr t₀ k t₁) := begin cases h; dsimp [add_right], { apply h₁, repeat { assumption <|> constructor}, }, { apply h₀, repeat { assumption <|> constructor}, }, end omit h₁ lemma with_height_add_left_left {k k' : α} {t₀ t₁ t₂} (hh₀ : with_height n t₀) (hh₁ : with_height (succ n) t₁) (hh₂ : with_height (succ n) t₂) : P (add_left_left ret t₀ k t₁ k' t₂) := begin cases hh₁; clear hh₁; dsimp; apply h₀, repeat { assumption <|> constructor }, end lemma with_height_add_middle {k k' : α} {t₀ t₁ t₂} (hh₀ : with_height (succ n) t₀) (hh₁ : with_height n t₁) (hh₂ : with_height (succ n) t₂) : P (add_middle ret t₀ k t₁ k' t₂) := begin cases hh₀; clear hh₀; dsimp; apply h₀, repeat { assumption <|> constructor }, end lemma with_height_add_right_right {k k' : α} {t₀ t₁ t₂} (hh₀ : with_height (succ n) t₀) (hh₁ : with_height (succ n) t₁) (hh₂ : with_height n t₂) : P (add_right_right ret t₀ k t₁ k' t₂) := begin cases hh₁; clear hh₁; dsimp; apply h₀, repeat { assumption <|> constructor }, end end with_height_add_left section with_height_delete variables (n : ℕ) (P : γ → Prop) (ret shr : option α → tree α β → γ) (del : unit → γ) (h₀ : ∀ a t, with_height n t → P (ret a t)) (h₁ : ∀ a t n', succ n' = n → with_height n' t → P (shr a t)) (h₂ : ∀ u, n = 0 → P (del u)) include h₀ h₁ h₂ lemma with_height_delete_aux {k : α} {t} (h : with_height n t) : P (delete' k t ret shr del) := begin induction h generalizing ret shr del, case two_three.with_height.leaf : k' v' { dsimp [delete'], split_ifs, all_goals { subst_vars, apply h₂ <|> apply h₀ <|> apply h₁, repeat { constructor }, }, }, case two_three.with_height.node2 : n h_x h_t₀ h_t₁ h_a h_a_1 h_ih₀ h_ih₁ { dsimp [delete'], split_ifs, repeat { intro <|> apply h_ih₀ <|> apply h_ih₁ <|> apply h₀ <|> apply h₁ <|> apply with_height_add_left <|> apply with_height_add_right <|> assumption <|> constructor, try { subst_vars } } }, case two_three.with_height.node3 : h_n h_x h_y h_t₀ h_t₁ h_t₂ h_a h_a_1 h_a_2 h_ih₀ h_ih₁ h_ih₂ { dsimp [delete'], split_ifs, repeat { intro <|> apply h_ih₀ <|> apply h_ih₁ <|> apply h_ih₂ }, all_goals { repeat { intro <|> apply h₀ <|> apply h₁ <|> apply h₂ <|> apply with_height_add_left <|> apply with_height_add_right <|> apply with_height_add_left_left <|> apply with_height_add_middle <|> apply with_height_add_right_right, }, repeat { subst_vars, assumption <|> constructor } }, }, end end with_height_delete lemma with_height_delete {n} {k : α} {t : tree α β} (h : with_height n t) : option.elim (delete k t) false (with_height n) ∨ option.elim (delete k t) (n = 0) (with_height n.pred) := with_height_delete_aux n (λ x : option (tree α β), option.elim x false (with_height n) ∨ option.elim x (n = 0) (with_height n.pred)) (λ _, some) (λ _, some) _ (by { dsimp, tauto }) (by { dsimp, intros, subst n, tauto }) (by { dsimp, tauto }) h section sorted_add_left variables (P : γ → Prop) (lb ub : option α) (ret shr : tree α β → γ) variables (h₀ : ∀ t, below lb (first t) → above (last t) ub → sorted' t → P (ret t)) (h₁ : ∀ t, below lb (first t) → above (last t) ub → sorted' t → P (shr t)) include h₀ h₁ lemma sorted_add_left {k : α} {t₀ t₁} (hhₐ : below lb (first t₀)) (hh₀ : sorted' t₀) (hh₁ : last t₀ < k) (hh₂ : k = first t₁) (hh₃ : sorted' t₁) (hh₄ : above (last t₁) ub) : P (add_left ret shr t₀ k t₁) := begin cases hh₃; clear hh₃; dsimp [add_left], all_goals { apply h₁ <|> apply h₀, clear h₀ h₁, repeat { assumption <|> constructor } }, dsimp at *, subst_vars, cases hh₄; constructor, chain_trans end lemma sorted_add_right {k : α} {t₀ t₁} (hhₐ : below lb (first t₀)) (hh₀ : sorted' t₀) (hh₁ : last t₀ < k) (hh₂ : k = first t₁) (hh₃ : sorted' t₁) (hh₄ : above (last t₁) ub) : P (add_right ret shr t₀ k t₁) := begin cases hh₀; clear hh₀; dsimp [add_left], all_goals { apply h₁ <|> apply h₀, clear h₀ h₁, repeat { assumption <|> constructor } }, dsimp at *, subst_vars, cases hh₄; constructor, have := first_le_last_of_sorted hh₃, chain_trans end omit h₁ lemma sorted_add_left_left {k k' : α} {t₀ t₁ t₂} (hhₐ : below lb (first t₀)) (hh₀ : sorted' t₀) (hh₁ : last t₀ < k) (hh₂ : k = first t₁) (hh₃ : sorted' t₁) (hh₄ : last t₁ < k') (hh₅ : k' = first t₂) (hh₆ : sorted' t₂) (hh₇ : above (last t₂) ub) : P (add_left_left ret t₀ k t₁ k' t₂) := begin cases hh₃; clear hh₃; dsimp at *, all_goals { saturate, subst_vars, apply h₀, repeat { assumption <|> constructor <|> above }, }, end lemma sorted_add_middle {k k' : α} {t₀ t₁ t₂} (hhₐ : below lb (first t₀)) (hh₀ : sorted' t₀) (hh₁ : last t₀ < k) (hh₂ : k = first t₁) (hh₃ : sorted' t₁) (hh₄ : last t₁ < k') (hh₅ : k' = first t₂) (hh₆ : sorted' t₂) (hh₇ : above (last t₂) ub) : P (add_middle ret t₀ k t₁ k' t₂) := begin cases hh₀; clear hh₀; dsimp; apply h₀; clear h₀, repeat { assumption <|> constructor <|> above }, end lemma sorted_add_right_right {k k' : α} {t₀ t₁ t₂} (hhₐ : below lb (first t₀)) (hh₀ : sorted' t₀) (hh₁ : last t₀ < k) (hh₂ : k = first t₁) (hh₃ : sorted' t₁) (hh₄ : last t₁ < k') (hh₅ : k' = first t₂) (hh₆ : sorted' t₂) (hh₇ : above (last t₂) ub) : P (add_right_right ret t₀ k t₁ k' t₂) := begin cases hh₃; clear hh₃; dsimp at *; apply h₀; clear h₀, repeat { assumption <|> constructor <|> above }, end end sorted_add_left section sorted_delete variables (lb ub : option α) (P : γ → Prop) (ret shr : option α → tree α β → γ) (del : unit → γ) -- (h₀ : ∀ a t, sorted' t → P (ret a t)) -- (h₁ : ∀ a t, sorted' t → P (shr a t)) -- (h₀ : ∀ a t, below lb (first t) → below a (first t) → above (last t) ub → sorted' t → P (ret a t)) -- (h₁ : ∀ a t, below lb (first t) → below a (first t) → above (last t) ub → sorted' t → P (shr a t)) (h₀ : ∀ a t, below lb (first t) → above (last t) ub → sorted' t → P (ret a t)) (h₁ : ∀ a t, below lb (first t) → above (last t) ub → sorted' t → P (shr a t)) (h₂ : ∀ u, P (del u)) include h₀ h₁ h₂ lemma sorted_delete_aux {k : α} {t} (hh₀ : below lb (first t)) (hh₁ : sorted' t) (hh₂ : above (last t) ub) : P (delete' k t ret shr del) := begin induction hh₁ generalizing lb ub ret shr del, case two_three.sorted'.leaf : k' v' { dsimp [delete'], split_ifs, all_goals { subst_vars, apply h₂ <|> apply h₀ <|> apply h₁, repeat { assumption <|> constructor <|> dsimp at * }, }, }, case two_three.sorted'.node2 : n h_x h_t₀ h_t₁ hh₀ hh₁ hh₂ h_ih₀ h_ih₁ { dsimp [delete'], find_all_hyps hh := sorted' _ then { have h := first_le_last_of_sorted hh }, split_ifs, all_goals { try { repeat { repeat { intro h, try { have := first_le_last_of_sorted h } }, apply h_ih₀ lb (some n) <|> apply h_ih₁ (some n) ub <|> casesm [above _ (some _)] <|> apply h₀ <|> apply h₁ <|> apply h₂ <|> apply sorted_add_left <|> apply sorted_add_right <|> apply sorted_add_left_left <|> apply sorted_add_middle <|> apply sorted_add_right_right <|> assumption <|> constructor, try { subst_vars } }, done } }, { apply h_ih₀ lb (some n); clear h_ih₀ h_ih₁, { intros, casesm* [above _ (some _)], apply h₀, repeat { assumption <|> constructor } }, { intros, apply sorted_add_left, intros, apply h₀, repeat { assumption <|> constructor }, all_goals { casesm* [above _ (some _)], repeat { intro <|> apply h₀ <|> apply h₁ <|> apply h₂ <|> apply with_height_add_left <|> apply with_height_add_right <|> apply with_height_add_left_left <|> apply with_height_add_middle <|> apply with_height_add_right_right, } }, repeat { subst_vars, intro <|> assumption <|> constructor } }, admit, admit, admit, }, admit }, admit, -- case two_three.sorted'.node3 : h_n h_x h_y h_t₀ h_t₁ h_t₂ h_a h_a_1 h_a_2 h_ih₀ h_ih₁ h_ih₂ -- { dsimp [delete'], split_ifs, -- repeat { intro <|> apply h_ih₀ <|> apply h_ih₁ <|> apply h_ih₂ }, -- all_goals -- { repeat { intro <|> apply h₀ <|> apply h₁ <|> apply h₂ <|> -- apply with_height_add_left <|> -- apply with_height_add_right <|> -- apply with_height_add_left_left <|> -- apply with_height_add_middle <|> -- apply with_height_add_right_right, }, -- repeat -- { subst_vars, -- assumption <|> constructor } }, }, end end sorted_delete end two_three
3f23ea4c1e6ef4a8a82d0c947c060f66ba3c606d
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/equiv/fin.lean
c9fe7c64b86f388e133a9d303225f14fa8713f93
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,761
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Kenny Lau -/ import data.fin import data.equiv.basic /-! # Equivalences for `fin n` -/ universe variables u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := ⟨fin_zero_elim, empty.elim, assume a, fin_zero_elim a, assume a, empty.elim a⟩ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty fin.elim0 /-- Equivalence between `fin 1` and `punit`. -/ def fin_one_equiv : fin 1 ≃ punit := ⟨λ_, (), λ_, 0, fin.cases rfl (λa, fin_zero_elim a), assume ⟨⟩, rfl⟩ /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, refl, refine fin.cases _ _, refl, exact λi, fin_zero_elim i end, assume b, match b with tt := rfl | ff := rfl end⟩ /-- Equivalence between `fin n.succ` and `option (fin n)` -/ def fin_succ_equiv (n : ℕ) : fin n.succ ≃ option (fin n) := ⟨λ x, fin.cases none some x, λ x, option.rec_on x 0 fin.succ, λ x, fin.cases rfl (λ i, show (option.rec_on (fin.cases none some (fin.succ i) : option (fin n)) 0 fin.succ : fin n.succ) = _, by rw fin.cases_succ) x, by rintro ⟨none | x⟩; [refl, exact fin.cases_succ _]⟩ /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def sum_fin_sum_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := λ x, sum.rec_on x (λ y, ⟨y.1, nat.lt_of_lt_of_le y.2 $ nat.le_add_right m n⟩) (λ y, ⟨m + y.1, nat.add_lt_add_left y.2 m⟩), inv_fun := λ x, if H : x.1 < m then sum.inl ⟨x.1, H⟩ else sum.inr ⟨x.1 - m, nat.lt_of_add_lt_add_left $ show m + (x.1 - m) < m + n, from (nat.add_sub_of_le $ le_of_not_gt H).symm ▸ x.2⟩, left_inv := λ x, begin cases x with y y, { simp [fin.ext_iff, y.is_lt], }, { have H : ¬m + y.val < m := not_lt_of_ge (nat.le_add_right _ _), simp [H, nat.add_sub_cancel_left, fin.ext_iff] } end, right_inv := λ x, begin by_cases H : (x:ℕ) < m, { dsimp, rw [dif_pos H], simp }, { dsimp, rw [dif_neg H], simp [fin.ext_iff, nat.add_sub_of_le (le_of_not_gt H)] } end } /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
7e8846311f70866b10fe68564b759eb01e16dfba
f618aea02cb4104ad34ecf3b9713065cc0d06103
/src/topology/metric_space/gromov_hausdorff.lean
ccee8057f6e26d8a9393fe8a0c8de1db0335ab74
[ "Apache-2.0" ]
permissive
joehendrix/mathlib
84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5
c15eab34ad754f9ecd738525cb8b5a870e834ddc
refs/heads/master
1,589,606,591,630
1,555,946,393,000
1,555,946,393,000
182,813,854
0
0
null
1,555,946,309,000
1,555,946,308,000
null
UTF-8
Lean
false
false
56,144
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 The Gromov-Hausdorff distance on the space of nonempty compact metric spaces up to isometry. We introduces the space of all nonempty compact metric spaces, up to isometry, called `GH_space`, and endow it with a metric space structure. The distance, known as the Gromov-Hausdorff distance, is defined as follows: given two nonempty compact spaces X and Y, their distance is the minimum Hausdorff distance between all possible isometric embeddings of X and Y in all metric spaces. To define properly the Gromov-Hausdorff space, we consider the non-empty compact subsets of ℓ^∞(ℝ) up to isometry, which is a well-defined type, and define the distance as the infimum of the Hausdorff distance over all embeddings in ℓ^∞(ℝ). We prove that this coincides with the previous description, as all separable metric spaces embed isometrically into ℓ^∞(ℝ), through an embedding called the Kuratowski embedding. To prove that we have a distance, we should show that if spaces can be coupled to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff distance is realized, i.e., there is a coupling for which the Hausdorff distance is exactly the Gromov-Hausdorff distance. This follows from a compactness argument, essentially following from Arzela-Ascoli. We prove the most important properties of the Gromov-Hausdorff space: it is a polish space, i.e., it is complete and second countable. We also prove the Gromov compactness criterion. -/ import topology.metric_space.closeds set_theory.cardinal topology.metric_space.gromov_hausdorff_realized topology.metric_space.completion noncomputable theory local attribute [instance, priority 0] classical.prop_decidable universes u v w open classical lattice set function topological_space filter metric quotient open bounded_continuous_function nat Kuratowski_embedding open sum (inl inr) set_option class.instance_max_depth 50 local attribute [instance] metric_space_sum local attribute [instance, priority 0] nat.cast_coe namespace Gromov_Hausdorff section GH_space /- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient of nonempty compact subsets of ℓ^∞(ℝ) by identifying isometric sets. Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty compact type to GH_space. -/ /-- Equivalence relation identifying two nonempty compact sets which are isometric -/ private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop := λx y, nonempty (x.val ≃ᵢ y.val) /-- This is indeed an equivalence relation -/ private lemma is_equivalence_isometry_rel : equivalence isometry_rel := ⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩ /-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/ instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) := setoid.mk isometry_rel is_equivalence_isometry_rel /-- The Gromov-Hausdorff space -/ definition GH_space : Type := quotient (isometry_rel.setoid) /-- Map any nonempty compact type to GH_space -/ definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space := ⟦nonempty_compacts.Kuratowski_embedding α⟧ /-- A metric space representative of any abstract point in GH_space -/ definition GH_space.rep (p : GH_space) : Type := (quot.out p).val lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val := begin simp only [to_GH_space, quotient.eq], split, { assume h, rcases setoid.symm h with ⟨e⟩, have f := (Kuratowski_embedding_isometry α).isometric_on_range.trans e, use λx, f x, split, { apply f.isometry.comp isometry_subtype_val }, { rw [range_comp, f.range_coe, set.image_univ, set.range_coe_subtype] } }, { rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩, have f := ((Kuratowski_embedding_isometry α).isometric_on_range.symm.trans isomΨ.isometric_on_range).symm, have E : (range Ψ) ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val = (p.val ≃ᵢ range (Kuratowski_embedding α)), by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl }, have g := cast E f, exact ⟨g⟩ } end lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val := begin refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.val_range⟩, apply isometry_subtype_val end section local attribute [reducible] GH_space.rep instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) := by apply_instance instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) := by apply_instance instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) := by apply_instance end lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p := begin change to_GH_space (quot.out p).val = p, rw ← eq_to_GH_space, exact quot.out_eq p end /-- Two nonempty compact spaces have the same image in GH_space if and only if they are isometric -/ lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type u} [metric_space β] [compact_space β] [nonempty β] : to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) := ⟨begin simp only [to_GH_space, quotient.eq], assume h, rcases h with e, have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val) = ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have e' := cast I e, have f := (Kuratowski_embedding_isometry α).isometric_on_range, have g := (Kuratowski_embedding_isometry β).isometric_on_range.symm, have h := (f.trans e').trans g, exact ⟨h⟩ end, begin rintros ⟨e⟩, simp only [to_GH_space, quotient.eq], have f := (Kuratowski_embedding_isometry α).isometric_on_range.symm, have g := (Kuratowski_embedding_isometry β).isometric_on_range, have h := (f.trans e).trans g, have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) = ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val), by { dunfold nonempty_compacts.Kuratowski_embedding, refl }, have h' := cast I h, exact ⟨h'⟩ end⟩ /-- Distance on GH_space : the distance between two nonempty compact spaces is the infimum Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition, we only consider embeddings in ℓ^∞(ℝ), but we will prove below that it works for all spaces. -/ instance : has_dist (GH_space) := { dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) } def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α] [metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β) lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) := by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep] /-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance of isometric copies of the spaces, in any metric space. -/ theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] {γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) : GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) := begin /- For the proof, we want to embed γ in ℓ^∞(ℝ), to say that the Hausdorff distance is realized in ℓ^∞(ℝ) and therefore bounded below by the Gromov-Hausdorff-distance. However, γ is not separable in general. We restrict to the union of the images of α and β in γ, which is separable and therefore embeddable in ℓ^∞(ℝ). -/ rcases exists_mem_of_nonempty α with ⟨xα, _⟩, letI : inhabited α := ⟨xα⟩, letI : inhabited β := classical.inhabited_of_nonempty (by assumption), let s : set γ := (range Φ) ∪ (range Ψ), let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩, let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩, have IΦ' : isometry Φ' := λx y, ha x y, have IΨ' : isometry Ψ' := λx y, hb x y, have : compact s, { apply compact_union_of_compact, { rw ← image_univ, apply compact_image compact_univ ha.continuous }, { rw ← image_univ, apply compact_image compact_univ hb.continuous } }, letI : metric_space (subtype s) := by apply_instance, haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹compact s›⟩, haveI : nonempty (subtype s) := ⟨Φ' xα⟩, have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl }, have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl }, have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'), { rw [ΦΦ', ΨΨ', range_comp, range_comp], exact Hausdorff_dist_image (isometry_subtype_val) }, rw this, -- Embed s in ℓ^∞(ℝ) through its Kuratowski embedding let F := Kuratowski_embedding (subtype s), have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') := Hausdorff_dist_image (Kuratowski_embedding_isometry _), rw ← this, -- Let A and B be the images of α and β under this embedding. They are in ℓ^∞(ℝ), and -- their Hausdorff distance is the same as in the original space. let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨by simp, begin rw [← range_comp, ← image_univ], exact compact_image compact_univ (IΦ'.continuous.comp (Kuratowski_embedding_isometry _).continuous), end⟩⟩, let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨by simp, begin rw [← range_comp, ← image_univ], exact compact_image compact_univ (IΨ'.continuous.comp (Kuratowski_embedding_isometry _).continuous), end⟩⟩, have Aα : ⟦A⟧ = to_GH_space α, { rw eq_to_GH_space_iff, exact ⟨λx, F (Φ' x), ⟨IΦ'.comp (Kuratowski_embedding_isometry _), by rw range_comp⟩⟩ }, have Bβ : ⟦B⟧ = to_GH_space β, { rw eq_to_GH_space_iff, exact ⟨λx, F (Ψ' x), ⟨IΨ'.comp (Kuratowski_embedding_isometry _), by rw range_comp⟩⟩ }, refine cInf_le ⟨0, begin simp, assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _, apply (mem_image _ _ _).2, existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simp [Aα, Bβ] end local attribute [instance, priority 0] inhabited_of_nonempty' /-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance, essentially by design. -/ lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β := begin /- we only need to check the inequality ≤, as the other one follows from the previous lemma. As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance in the optimal coupling is smaller than the Hausdorff distance of any coupling. First, we check this for couplings which already have small Hausdorff distance: in this case, the induced "distance" on α ⊕ β belongs to the candidates family introduced in the definition of the optimal coupling, and the conclusion follows from the optimality of the optimal coupling within this family. -/ have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq bound, rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩, rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩, have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β), { rcases exists_mem_of_nonempty α with ⟨xα, _⟩, have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β), { rw Ψrange, have : Φ xα ∈ p.val := begin rw ← Φrange, exact mem_range_self _ end, exact exists_dist_lt_of_Hausdorff_dist_lt this bound (Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2)) }, rcases this with ⟨y, hy, dy⟩, rcases mem_range.1 hy with ⟨z, hzy⟩, rw ← hzy at dy, have DΦ : diam (range Φ) = diam (univ : set α) := begin rw [← image_univ], apply metric.isometry.diam_image Φisom end, have DΨ : diam (range Ψ) = diam (univ : set β) := begin rw [← image_univ], apply metric.isometry.diam_image Ψisom end, calc diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) : diam_union (mem_range_self _) (mem_range_self _) ... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) : by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) } ... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring }, let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end, let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2), -- check that the induced "distance" is a candidate have Fgood : F ∈ candidates α β, { simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero, and_self, set.mem_set_of_eq], repeat {split}, { exact λx y, calc F (inl x, inl y) = dist (Φ x) (Φ y) : rfl ... = dist x y : Φisom.dist_eq }, { exact λx y, calc F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl ... = dist x y : Ψisom.dist_eq }, { exact λx y, dist_comm _ _ }, { exact λx y z, dist_triangle _ _ _ }, { exact λx y, calc F (x, y) ≤ diam (range Φ ∪ range Ψ) : begin have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ, { assume z, cases z, { apply mem_union_left, apply mem_range_self }, { apply mem_union_right, apply mem_range_self } }, refine dist_le_diam_of_mem _ (A _) (A _), rw [Φrange, Ψrange], exact bounded_of_compact (compact_union_of_compact p.2.2 q.2.2), end ... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } }, let Fb := candidates_b_of_candidates F Fgood, have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb := Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood), refine le_trans this (le_of_forall_le_of_dense (λr hr, _)), have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r, { assume x, have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt this hr (Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2)) with ⟨z, zq, hz⟩, have : z ∈ range Ψ, by rwa [← Ψrange] at zq, rcases mem_range.1 this with ⟨y, hy⟩, calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux1 0) ... = dist (Φ x) (Ψ y) : rfl ... = dist (f (inl x)) z : by rw hy ... ≤ r : le_of_lt hz }, have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r, { assume y, have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self }, rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr (Hausdorff_edist_ne_top_of_ne_empty_of_bounded p.2.1 q.2.1 (bounded_of_compact p.2.2) (bounded_of_compact q.2.2)) with ⟨z, zq, hz⟩, have : z ∈ range Φ, by rwa [← Φrange] at zq, rcases mem_range.1 this with ⟨x, hx⟩, calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) : cinfi_le (by simpa using HD_below_aux2 0) ... = dist (Φ x) (Ψ y) : rfl ... = dist z (f (inr y)) : by rw hx ... ≤ r : le_of_lt hz }, simp [HD, csupr_le I1, csupr_le I2] }, /- Get the same inequality for any coupling. If the coupling is quite good, the desired inequality has been proved above. If it is bad, then the inequality is obvious. -/ have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β → Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val), { assume p q hp hq, by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β), { exact A p q hp hq h }, { calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) : Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b) ... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le ... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } }, refine le_antisymm _ _, { apply le_cInf, { rw ne_empty_iff_exists_mem, simp only [set.mem_image, nonempty_of_inhabited, set.mem_set_of_eq, prod.exists], existsi [Hausdorff_dist (nonempty_compacts.Kuratowski_embedding α).val (nonempty_compacts.Kuratowski_embedding β).val, nonempty_compacts.Kuratowski_embedding α, nonempty_compacts.Kuratowski_embedding β], simp [to_GH_space, -quotient.eq] }, { rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩, exact B p q hp hq } }, { exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) } end /-- The Gromov-Hausdorff distance can also be realized by a coupling in ℓ^∞(ℝ), by embedding the optimal coupling through its Kuratowski embedding. -/ theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α] (β : Type v) [metric_space β] [compact_space β] [nonempty β] : ∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧ GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) := begin let F := Kuratowski_embedding (optimal_GH_coupling α β), let Φ := F ∘ optimal_GH_injl α β, let Ψ := F ∘ optimal_GH_injr α β, refine ⟨Φ, Ψ, _, _, _⟩, { exact isometry.comp (isometry_optimal_GH_injl α β) (Kuratowski_embedding_isometry _) }, { exact isometry.comp (isometry_optimal_GH_injr α β) (Kuratowski_embedding_isometry _) }, { rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β), image_univ, ← Hausdorff_dist_optimal], exact (Hausdorff_dist_image (Kuratowski_embedding_isometry _)).symm }, end -- without the next two lines, { exact closed_of_compact (range Φ) hΦ } in the next -- proof is very slow, as the t2_space instance is very hard to find local attribute [instance, priority 0] orderable_topology.t2_space local attribute [instance, priority 0] ordered_topology.to_t2_space /-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/ instance GH_space_metric_space : metric_space GH_space := { dist_self := λx, begin rcases exists_rep x with ⟨y, hy⟩, refine le_antisymm _ _, { apply cInf_le, { exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩}, { simp, existsi [y, y], simpa } }, { apply le_cInf, { simp only [set.image_eq_empty, ne.def], apply ne_empty_iff_exists_mem.2, existsi (⟨y, y⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), simpa }, { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } }, end, dist_comm := λx y, begin have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) = ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ), Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) := by { congr, funext, simp, rw Hausdorff_dist_comm }, simp only [dist, A, image_comp, prod.swap, image_swap_prod], end, eq_of_dist_eq_zero := λx y hxy, begin /- To show that two spaces at zero distance are isometric, we argue that the distance is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance, i.e., they coincide. Therefore, the original spaces are isometric. -/ rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩, rw [← dist_GH_dist, hxy] at DΦΨ, have : range Φ = range Ψ, { have hΦ : compact (range Φ) := by { rw [← image_univ], exact compact_image compact_univ Φisom.continuous }, have hΨ : compact (range Ψ) := by { rw [← image_univ], exact compact_image compact_univ Ψisom.continuous }, apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm), { exact closed_of_compact (range Φ) hΦ }, { exact closed_of_compact (range Ψ) hΨ }, { exact Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simp [-nonempty_subtype]) (by simp [-nonempty_subtype]) (bounded_of_compact hΦ) (bounded_of_compact hΨ) } }, have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this, have eΨ := cast T Ψisom.isometric_on_range.symm, have e := Φisom.isometric_on_range.trans eΨ, rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨e⟩ end, dist_triangle := λx y z, begin /- To show the triangular inequality between X, Y and Z, realize an optimal coupling between X and Y in a space γ1, and an optimal coupling between Y and Z in a space γ2. Then, glue these metric spaces along Y. We get a new space γ in which X and Y are optimally coupled, as well as Y and Z. Apply the triangle inequality for the Hausdorff distance in γ to conclude. -/ let X := x.rep, let Y := y.rep, let Z := z.rep, let γ1 := optimal_GH_coupling X Y, let γ2 := optimal_GH_coupling Y Z, let Φ : Y → γ1 := optimal_GH_injr X Y, have hΦ : isometry Φ := isometry_optimal_GH_injr X Y, let Ψ : Y → γ2 := optimal_GH_injl Y Z, have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z, let γ := glue_space hΦ hΨ, letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ, have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) := to_glue_commute hΦ hΨ, calc dist x z = dist (to_GH_space X) (to_GH_space Z) : by rw [x.to_GH_space_rep, z.to_GH_space_rep] ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : GH_dist_le_Hausdorff_dist (isometry.comp (isometry_optimal_GH_injl X Y) (to_glue_l_isometry hΦ hΨ)) (isometry.comp (isometry_optimal_GH_injr Y Z) (to_glue_r_isometry hΦ hΨ)) ... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y))) (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) + Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y))) (range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) : begin refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simp [-nonempty_subtype]) (by simp [-nonempty_subtype]) _ _), { rw [← image_univ], exact bounded_of_compact (compact_image compact_univ (isometry.continuous (isometry.comp (isometry_optimal_GH_injl X Y) (to_glue_l_isometry hΦ hΨ)))) }, { rw [← image_univ], exact bounded_of_compact (compact_image compact_univ (isometry.continuous (isometry.comp (isometry_optimal_GH_injr X Y) (to_glue_l_isometry hΦ hΨ)))) } end ... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y))) ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y))) + Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z))) ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) : by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj] ... = Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) + Hausdorff_dist (range (optimal_GH_injl Y Z)) (range (optimal_GH_injr Y Z)) : by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ), Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)] ... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) : by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist] ... = dist x y + dist y z: by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep] end } end GH_space --section end Gromov_Hausdorff /-- In particular, nonempty compacts of a metric space map to GH_space. We register this in the topological_space namespace to take advantage of the notation p.to_GH_space -/ definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α] (p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val open topological_space namespace Gromov_Hausdorff section nonempty_compacts variables {α : Type u} [metric_space α] theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) : dist p.to_GH_space q.to_GH_space ≤ dist p q := begin have ha : isometry (subtype.val : p.val → α) := isometry_subtype_val, have hb : isometry (subtype.val : q.val → α) := isometry_subtype_val, have A : dist p q = Hausdorff_dist p.val q.val := rfl, have I : p.val = range (subtype.val : p.val → α), by simp, have J : q.val = range (subtype.val : q.val → α), by simp, rw [I, J] at A, rw A, exact GH_dist_le_Hausdorff_dist ha hb end lemma to_GH_space_lipschitz : lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := ⟨zero_le_one, by { simp, exact GH_dist_le_nonempty_compacts_dist } ⟩ lemma to_GH_space_continuous : continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) := to_GH_space_lipschitz.to_continuous end nonempty_compacts section /- In this section, we show that if two metric spaces are isometric up to ε2, then their Gromov-Hausdorff distance is bounded by ε2 / 2. More generally, if there are subsets which are ε1-dense and ε3-dense in two spaces, and isometric up to ε2, then the Gromov-Hausdorff distance between the spaces is bounded by ε1 + ε2/2 + ε3. For this, we construct a suitable coupling between the two spaces, by gluing them (approximately) along the two matching subsets. -/ variables {α : Type u} [metric_space α] [compact_space α] [nonempty α] {β : Type v} [metric_space β] [compact_space β] [nonempty β] /-- If there are subsets which are ε1-dense and ε3-dense in two spaces, and isometric up to ε2, then the Gromov-Hausdorff distance between the spaces is bounded by ε1 + ε2/2 + ε3. -/ theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε1 ε2 ε3 : ℝ} (hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε1) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε3) (H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε2) : GH_dist α β ≤ ε1 + ε2 / 2 + ε3 := begin refine real.le_of_forall_epsilon_le (λδ δ0, _), rcases exists_mem_of_nonempty α with ⟨xα, _⟩, rcases hs xα with ⟨xs, hxs, Dxs⟩, have sne : s ≠ ∅ := ne_empty_of_mem hxs, letI : nonempty (subtype s) := ⟨⟨xs, hxs⟩⟩, have : 0 ≤ ε2 := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩), have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε2/2 + δ) := λp q, calc abs (dist p q - dist (Φ p) (Φ q)) ≤ ε2 : H p q ... ≤ 2 * (ε2/2 + δ) : by linarith, -- glue α and β along the almost matching subsets letI : metric_space (α ⊕ β) := glue_metric_approx (@subtype.val α s) (λx, Φ x) (ε2/2 + δ) (by linarith) this, let Fl := @sum.inl α β, let Fr := @sum.inr α β, have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl), have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl), /- The proof goes as follows : the GH_dist is bounded by the Hausdorff distance of the images in the coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances of α and s (in the coupling or, equivalently in the original space), of s and Φ s, and of Φ s and β (in the coupling or, equivalently, in the original space). The first term is bounded by ε1, by ε1-density. The third one is bounded by ε3. And the middle one is bounded by ε2/2 as in the coupling the points x and Φ x are at distance ε2/2 by construction of the coupling (in fact ε2/2 + δ where δ is an arbitrarily small positive constant where positivity is used to ensure that the coupling is really a metric space and not a premetric space on α ⊕ β). -/ have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) := GH_dist_le_Hausdorff_dist Il Ir, have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s) + Hausdorff_dist (Fl '' s) (range Fr), { have B : bounded (range Fl) := bounded_of_compact (compact_range Il.continuous), exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simpa) (by simpa) B (bounded.subset (image_subset_range _ _) B)) }, have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) + Hausdorff_dist (Fr '' (range Φ)) (range Fr), { have B : bounded (range Fr) := bounded_of_compact (compact_range Ir.continuous), exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_ne_empty_of_bounded (by simpa [-nonempty_subtype]) (by simpa) (bounded.subset (image_subset_range _ _) B) B) }, have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε1, { rw [← image_univ, Hausdorff_dist_image Il], have : 0 ≤ ε1 := le_trans dist_nonneg Dxs, refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x) (λx hx, ⟨x, mem_univ _, by simpa⟩) }, have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε2/2 + δ, { refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩, rw ← xx', use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)], exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) ⟨x, x_in_s⟩) }, { assume x' hx', rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩, rcases mem_range.1 y_in_s' with ⟨x, xy⟩, use [Fl x, mem_image_of_mem _ x.2], rw [← yx', ← xy, dist_comm], exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε2/2 + δ) x) } }, have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε3, { rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir], rcases exists_mem_of_nonempty β with ⟨xβ, _⟩, rcases hs' xβ with ⟨xs', Dxs'⟩, have : 0 ≤ ε3 := le_trans dist_nonneg Dxs', refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _), rcases hs' x with ⟨y, Dy⟩, exact ⟨Φ y, mem_range_self _, Dy⟩ }, linarith end end --section /-- The Gromov-Hausdorff space is second countable. -/ lemma second_countable : second_countable_topology GH_space := begin refine second_countable_of_countable_discretization (λδ δpos, _), let ε := (2/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) := λp, by simpa using finite_cover_balls_of_compact (@compact_univ (p.rep) _ _ _) εpos, -- for each p, s p is a finite ε-dense subset of p (or rather the metric space -- p.rep representing p) choose s hs using this, have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true, { assume p t ht, letI : fintype t := finite.fintype ht, rcases fintype.exists_equiv_fin t with ⟨n, hn⟩, rcases hn with e, exact ⟨n, e, trivial⟩ }, choose N e hne using this, -- cardinality of the nice finite subset s p of p.rep, called N p let N := λp:GH_space, N p (s p) (hs p).1, -- equiv from s p, a nice finite subset of p.rep, to fin (N p), called E p let E := λp:GH_space, e p (s p) (hs p).1, -- A function F associating to p ∈ GH_space the data of all distances of points -- in the ε-dense set s p. let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) := λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))⟩, refine ⟨_, by apply_instance, F, λp q hpq, _⟩, /- As the target space of F is countable, it suffices to show that two points p and q with F p = F q are at distance ≤ δ. For this, we construct a map Φ from s p ⊆ p.rep (representing p) to q.rep (representing q) which is almost an isometry on s p, and with image s q. For this, we compose the identification of s p with fin (N p) and the inverse of the identification of s q with fin (N q). Together with the fact that N p = N q, this constructs Ψ between s p and s q, and then composing with the canonical inclusion we get Φ. -/ have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)), let Φ : s p → q.rep := λx, Ψ x, -- Use the almost isometry Φ to show that p.rep and q.rep -- are within controlled Gromov-Hausdorff distance. have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε, { refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, s p is ε-dense assume x, have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩, exact ⟨y, ys, le_of_lt hy⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, s q is ε-dense, and it is the range of Φ assume x, have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩, let i := ((E q).to_fun ⟨y, ys⟩).1, let hi := ((E q).to_fun ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff, have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).inv_fun ⟨i, hip⟩, use z, have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_of_lt hy }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between x and y is encoded in F p, and the distance between Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε. As F p = F q, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce i, that codes both x and Φ x in fin (N p) = fin (N q) let i := ((E p).to_fun x).1, have hip : i < N p := ((E p).to_fun x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] }, -- introduce j, that codes both y and Φ y in fin (N p) = fin (N q) let j := ((E p).to_fun y).1, have hjp : j < N p := ((E p).to_fun y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] }, -- Express dist x y in terms of F p have : (F p).2 ((E p).to_fun x) ((E p).to_fun y) = floor (ε⁻¹ * dist x y), by simp only [F, (E p).left_inv _], have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y), by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl }, -- Express dist (Φ x) (Φ y) in terms of F q have : (F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by simp only [F, (E q).left_inv _], have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }, -- use the equality between F p and F q to deduce that the distances have equal -- integer parts have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant f -- then subst revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, rw [Ap, Aq] at this, -- deduce that the distances coincide up to ε, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ : by { simp [ε], ring } end /-- Compactness criterion : a closed set of compact metric spaces is compact if the spaces have a uniformly bounded diameter, and for all ε the number of balls of radius ε required to cover the space is uniformly bounded. This is an equivalence, but we only prove the interesting direction that these conditions imply compactness. -/ lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ} (ulim : tendsto u at_top (nhds 0)) (hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C) (hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) : totally_bounded t := begin /- Let δ>0, and ε = δ/5. For each p, we construct a finite subset s p of p, which is ε-dense and has cardinality at most K n. Encoding the mutual distances of points in s p, up to ε, we will get a map F associating to p finitely many data, and making it possible to reconstruct p up to ε. This is enough to prove total boundedness. -/ refine metric.totally_bounded_of_finite_discretization (λδ δpos, _), let ε := (1/5) * δ, have εpos : 0 < ε := mul_pos (by norm_num) δpos, -- choose n for which ε < u n rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩, have u_le_ε : u n ≤ ε, { have := hn n (le_refl _), simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this, exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) }, -- construct a finite subset s p of p which is ε-dense and has cardinal ≤ K n have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N), p ∈ t → univ ⊆ ⋃x∈s, ball x (u n), { assume p, by_cases hp : p ∉ t, { have : nonempty (equiv (∅ : set (p.rep)) (fin 0)), { rw ← fintype.card_eq, simp }, use [∅, 0, bot_le, choice (this)] }, { rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩, rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩, rw [hN, cardinal.nat_cast_le] at scard, have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin], cases quotient.exact this with E, use [s, N, scard, E], simp [hp, scover] } }, choose s N hN E hs using this, -- Define a function F taking values in a finite type and associating to p enough data -- to reconstruct it up to ε, namely the (discretized) distances between elements of s p. let M := (floor (ε⁻¹ * max C 0)).to_nat, let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) := λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩, λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).inv_fun a) ((E p).inv_fun b))).to_nat, lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩, refine ⟨_, by apply_instance, (λp, F p), _⟩, -- It remains to show that if F p = F q, then p and q are ε-close rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq, have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1, let Ψ : s p → s q := λx, (E q).inv_fun (fin.cast Npq ((E p).to_fun x)), let Φ : s p → q.rep := λx, Ψ x, have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε, { -- to prove the main inequality, argue that s p is ε-dense in p, and s q is ε-dense in q, -- and s p and s q are almost isometric. Then closeness follows -- from GH_dist_le_of_approx_subsets refine GH_dist_le_of_approx_subsets Φ _ _ _, show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε, { -- by construction, s p is ε-dense assume x, have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩, exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ }, show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε, { -- by construction, s q is ε-dense, and it is the range of Φ assume x, have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _), rcases mem_bUnion_iff.1 this with ⟨y, ⟨ys, hy⟩⟩, let i := ((E q).to_fun ⟨y, ys⟩).1, let hi := ((E q).to_fun ⟨y, ys⟩).2, have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q).to_fun ⟨y, ys⟩, by rw fin.ext_iff, have hiq : i < N q := hi, have hip : i < N p, { rwa Npq.symm at hiq }, let z := (E p).inv_fun ⟨i, hip⟩, use z, have C1 : (E p).to_fun z = ⟨i, hip⟩ := (E p).right_inv ⟨i, hip⟩, have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl, have C3 : (E q).inv_fun ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).left_inv ⟨y, ys⟩ }, have : Φ z = y := by { simp only [Φ, Ψ], rw [C1, C2, C3], refl }, rw this, exact le_trans (le_of_lt hy) u_le_ε }, show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε, { /- the distance between x and y is encoded in F p, and the distance between Φ x and Φ y (two points of s q) is encoded in F q, all this up to ε. As F p = F q, the distances are almost equal. -/ assume x y, have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl, rw this, -- introduce i, that codes both x and Φ x in fin (N p) = fin (N q) let i := ((E p).to_fun x).1, have hip : i < N p := ((E p).to_fun x).2, have hiq : i < N q, by rwa Npq at hip, have i' : i = ((E q).to_fun (Ψ x)).1, by { simp [Ψ, (E q).right_inv _] }, -- introduce j, that codes both y and Φ y in fin (N p) = fin (N q) let j := ((E p).to_fun y).1, have hjp : j < N p := ((E p).to_fun y).2, have hjq : j < N q, by rwa Npq at hjp, have j' : j = ((E q).to_fun (Ψ y)).1, by { simp [Ψ, (E q).right_inv _] }, -- Express dist x y in terms of F p have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p).to_fun x) ((E p).to_fun y)).1 : by { congr; apply (fin.ext_iff _ _).2; refl } ... = min M (floor (ε⁻¹ * dist x y)).to_nat : by simp only [F, (E p).left_inv _] ... = (floor (ε⁻¹ * dist x y)).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)), change dist (x : p.rep) y ≤ C, refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _, exact hdiam p pt end, -- Express dist (Φ x) (Φ y) in terms of F q have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q).to_fun (Ψ x)) ((E q).to_fun (Ψ y))).1 : by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] } ... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : by simp only [F, (E q).left_inv _] ... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat : begin refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)), refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos εpos)), change dist (Ψ x : q.rep) (Ψ y) ≤ C, refine le_trans (dist_le_diam_of_mem (bounded_of_compact compact_univ) (mem_univ _) (mem_univ _)) _, exact hdiam q qt end, -- use the equality between F p and F q to deduce that the distances have equal -- integer parts have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1, { -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works -- with a constant, so replace `F q` (and everything that depends on it) by a constant f -- then subst revert hiq hjq, change N q with (F q).1, generalize_hyp : F q = f at hpq ⊢, subst hpq, intros, refl }, have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)), { rw [Ap, Aq] at this, have D : 0 ≤ floor (ε⁻¹ * dist x y) := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg), have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 := floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos εpos)) dist_nonneg), rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] }, -- deduce that the distances coincide up to ε, by a straightforward computation -- that should be automated have I := calc abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) = abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm ... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring } ... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this), calc abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) : by rw [mul_inv_cancel (ne_of_gt εpos), one_mul] ... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) : by rw [abs_of_nonneg (le_of_lt (inv_pos εpos)), mul_assoc] ... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos) ... = ε : mul_one _ } }, calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q ... ≤ ε + ε/2 + ε : main ... = δ/2 : by { simp [ε], ring } ... < δ : half_lt_self δpos end section complete /- We will show that a sequence `u n` of compact metric spaces satisfying `dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space. We need to exhibit the limiting compact metric space. For this, start from a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)` for all `n`, in a common metric space. Formally, this is done as follows. Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space `Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive limit of the `Y n`, and finally let `Z` be the completion of `Z0`. The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty compact metric space we are looking for. -/ variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)] structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 := (space : Type) (metric : metric_space space) (embed : A → space) (isom : isometry embed) def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n { space := X 0, metric := by apply_instance, embed := id, isom := λx y, rfl } (λn a, by letI : metric_space a.space := a.metric; exact { space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)), embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injr (X n) (X n.succ)), isom := (isometry_optimal_GH_injr (X n) (X n.succ)).comp (to_glue_r_isometry _ _) }) /-- The Gromov-Hausdorff space is complete. -/ instance : complete_space (GH_space) := begin have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num }, -- start from a sequence of nonempty compact metric spaces within distance 1/2^n of each other refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _), -- X n is a representative of u n let X := λn, (u n).rep, -- glue them together successively in an optimal way, getting a sequence of metric spaces Y n let Y := aux_gluing X, letI : ∀n, metric_space (Y n).space := λn, (Y n).metric, have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space := λn, by { simp [Y, aux_gluing], refl }, let c := λn, cast (E n), have ic : ∀n, isometry (c n) := λn x y, rfl, -- there is a canonical embedding of Y n in Y (n+1), by construction let f : Πn, (Y n).space → (Y n.succ).space := λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))), have I : ∀n, isometry (f n), { assume n, apply isometry.comp, { apply to_glue_l_isometry }, { assume x y, refl } }, -- consider the inductive limit Z0 of the Y n, and then its completion Z let Z0 := metric.inductive_limit I, let Z := uniform_space.completion Z0, let Φ := to_inductive_limit I, let coeZ := (coe : Z0 → Z), -- let X2 n be the image of X n in the space Z let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed), have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed), { assume n, apply isometry.comp _ completion.coe_isometry, apply isometry.comp (Y n).isom _, apply to_inductive_limit_isometry }, -- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between -- `u n` and `u (n+1)`, therefore bounded by 1/2^n have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n, { assume n, have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injl (X n) (X n.succ))), { change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))) ∘ (optimal_GH_injl (X n) (X n.succ))), simp only [X2, Φ], rw [← to_inductive_limit_commute I], simp only [f], rw ← to_glue_commute }, rw range_comp at X2n, have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n) ∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))) ∘ (optimal_GH_injr (X n) (X n.succ))), by refl, rw range_comp at X2nsucc, rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist], { exact hu n n n.succ (le_refl n) (le_succ n) }, { apply isometry.comp _ completion.coe_isometry, apply ((to_glue_r_isometry _ _).comp (ic n)).comp, apply to_inductive_limit_isometry } }, -- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which -- is a metric space let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n, ⟨by { simp only [X2, set.range_eq_empty, not_not, ne.def], apply_instance }, compact_range (isom n).continuous ⟩⟩, -- `X3 n` is a Cauchy sequence by construction, as the successive distances are -- bounded by (1/2)^n have : cauchy_seq X3, { refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _), rw one_mul, exact le_of_lt (D2 n) }, -- therefore, it converges to a limit `L` rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩, -- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L` have M : tendsto (λn, (X3 n).to_GH_space) at_top (nhds L.to_GH_space) := tendsto.comp hL (to_GH_space_continuous.tendsto _), -- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`. have : ∀n, (X3 n).to_GH_space = u n, { assume n, rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric], exact ⟨(isom n).isometric_on_range.symm⟩ }, -- Finally, we have proved the convergence of `u n` exact ⟨L.to_GH_space, by simpa [this] using M⟩ end end complete--section end Gromov_Hausdorff --namespace
f59fdb0c6193fd740f3326667d8aaebff990bb24
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/inductiveIndicesIssue.lean
cb4bbbb638b1d0c08371047000a17911d745b072
[ "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
795
lean
import Lean inductive sublist : List α → List α → Prop | slnil : sublist [] [] | cons l₁ l₂ a : sublist l₁ l₂ → sublist l₁ (a :: l₂) | cons2 l₁ l₂ a : sublist l₁ l₂ → sublist (a :: l₁) (a :: l₂) namespace Lean.PrefixTreeNode namespace Ex1 inductive WellFormed (cmp : α → α → Ordering) : PrefixTreeNode α β → Prop where | emptyWff : WellFormed cmp empty | insertWff {t : PrefixTreeNode α β} {k : List α} {val : β} : WellFormed cmp t → WellFormed cmp (insert t cmp k val) end Ex1 namespace Ex2 inductive WellFormed (cmp : α → α → Ordering) : PrefixTreeNode α β → Prop where | emptyWff : WellFormed cmp empty | insertWff : WellFormed cmp t → WellFormed cmp (insert t cmp k val) end Ex2 end Lean.PrefixTreeNode
92ea46fd09b7490491e5f4bdf86d01dcaed3de77
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/linear_algebra/finite_dimensional.lean
15bdda21be03a4398d9b55441ad5972a2c60159a
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
53,468
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 linear_algebra.dimension import ring_theory.principal_ideal_domain import algebra.algebra.subalgebra /-! # Finite dimensional vector spaces Definition and basic properties of finite dimensional vector spaces, of their dimensions, and of linear maps on such spaces. ## Main definitions Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of finite-dimensionality of `V`: - it admits a finite basis. - it is finitely generated. - it is noetherian, i.e., every subspace is finitely generated. We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove that all these points of view are equivalent, with the following lemmas (in the namespace `finite_dimensional`): - `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis - `of_fintype_basis` states that the existence of a basis indexed by a finite type implies finite-dimensionality - `of_finset_basis` states that the existence of a basis indexed by a `finset` implies finite-dimensionality - `of_finite_basis` states that the existence of a basis indexed by a finite set implies finite-dimensionality - `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`, as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its `findim` is by convention set to `0`. Preservation of finite-dimensionality and formulas for the dimension are given for - submodules - quotients (for the dimension of a quotient, see `findim_quotient_add_findim`) - linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq` - image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`) Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`, and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and `comp_eq_id_comm`. ## Implementation notes Most results are deduced from the corresponding results for the general dimension (as a cardinal), in `dimension.lean`. Not all results have been ported yet. One of the characterizations of finite-dimensionality is in terms of finite generation. This property is currently defined only for submodules, so we express it through the fact that the maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is not very convenient to use, although there are some helper functions. However, this becomes very convenient when speaking of submodules which are finite-dimensional, as this notion coincides with the fact that the submodule is finitely generated (as a submodule of the whole space). This equivalence is proved in `submodule.fg_iff_finite_dimensional`. -/ universes u v v' w open_locale classical open vector_space cardinal submodule module function variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V] {V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂] /-- `finite_dimensional` vector spaces are defined to be noetherian modules. Use `finite_dimensional.iff_fg` or `finite_dimensional.of_fintype_basis` to prove finite dimension from a conventional definition. -/ @[reducible] def finite_dimensional (K V : Type*) [field K] [add_comm_group V] [vector_space K V] := is_noetherian K V namespace finite_dimensional open is_noetherian /-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly less than the first infinite cardinal `omega`. -/ lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} := begin cases exists_is_basis K V with b hb, have := is_basis.mk_eq_dim hb, simp only [lift_id] at this, rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.range_coe_subtype], split, { intro, resetI, convert finite_of_linear_independent hb.1, simp }, { assume hbfinite, refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _ _ _ _ _ (linear_equiv.of_top _ rfl) (id _), refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩, rw [set.finite.coe_to_finset, ← hb.2], refl } end /-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the first infinite cardinal `omega`. -/ lemma dim_lt_omega (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ∀ [finite_dimensional K V], dim K V < omega.{v} := finite_dimensional_iff_dim_lt_omega.1 /-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of a function), and use as parametrizing type this set (and as a function the coercion `coe : s → V`). -/ variables (K V) lemma exists_is_basis_finite [finite_dimensional K V] : ∃ s : set V, (is_basis K (coe : s → V)) ∧ s.finite := begin cases exists_is_basis K V with s hs, exact ⟨s, hs, finite_of_linear_independent hs.1⟩ end /-- In a finite dimensional space, there exists a finite basis. Provides the basis as a finset. This is in contrast to `exists_is_basis_finite`, which provides a set and a `set.finite`. -/ lemma exists_is_basis_finset [finite_dimensional K V] : ∃ b : finset V, is_basis K (coe : (↑b : set V) → V) := begin obtain ⟨s, s_basis, s_finite⟩ := exists_is_basis_finite K V, refine ⟨s_finite.to_finset, _⟩, rw set.finite.coe_to_finset, exact s_basis, end /-- A finite dimensional vector space over a finite field is finite -/ noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V := module.fintype_of_fintype (classical.some_spec (finite_dimensional.exists_is_basis_finset K V) : _) variables {K V} /-- A vector space is finite-dimensional if and only if it is finitely generated. As the finitely-generated property is a property of submodules, we formulate this in terms of the maximal submodule, equal to the whole space as a set by definition.-/ lemma iff_fg : finite_dimensional K V ↔ (⊤ : submodule K V).fg := begin split, { introI h, rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ }, { rintros ⟨s, hs⟩, rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs], exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) } end /-- If a vector space has a finite basis, then it is finite-dimensional. -/ lemma of_fintype_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : finite_dimensional K V := iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩ /-- If a vector space has a basis indexed by elements of a finite set, then it is finite-dimensional. -/ lemma of_finite_basis {ι} {s : set ι} {b : s → V} (h : is_basis K b) (hs : set.finite s) : finite_dimensional K V := by haveI := hs.fintype; exact of_fintype_basis h /-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/ lemma of_finset_basis {ι} {s : finset ι} {b : (↑s : set ι) → V} (h : is_basis K b) : finite_dimensional K V := of_finite_basis h s.finite_to_set /-- A subspace of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) : finite_dimensional K S := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V)) /-- A quotient of a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) : finite_dimensional K (quotient S) := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V)) /-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to be `0` if the space is infinite-dimensional. -/ noncomputable def findim (K V : Type*) [field K] [add_comm_group V] [vector_space K V] : ℕ := if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0 /-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its `findim`. -/ lemma findim_eq_dim (K : Type u) (V : Type v) [field K] [add_comm_group V] [vector_space K V] [finite_dimensional K V] : (findim K V : cardinal.{v}) = dim K V := begin have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) := dif_pos (dim_lt_omega K V), rw this, exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm end lemma findim_of_infinite_dimensional {K V : Type*} [field K] [add_comm_group V] [vector_space K V] (h : ¬finite_dimensional K V) : findim K V = 0 := dif_neg $ mt finite_dimensional_iff_dim_lt_omega.2 h /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : dim K V = fintype.card ι := by rw [←h.mk_range_eq_dim, cardinal.fintype_card, set.card_range_of_injective h.injective] /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. -/ lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) : findim K V = fintype.card ι := begin haveI : finite_dimensional K V := of_fintype_basis h, have := dim_eq_card_basis h, rw ← findim_eq_dim at this, exact_mod_cast this end /-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its `findim`. -/ lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) : (findim K V : cardinal.{w}) = cardinal.mk ι := begin rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩, letI: fintype s := s_finite.fintype, have A : cardinal.mk s = fintype.card s := fintype_card _, have B : findim K V = fintype.card s := findim_eq_card_basis s_basis, have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) := mk_eq_mk_of_basis h s_basis, rw [A, ← B, lift_nat_cast] at C, have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V), by { simp, exact C }, exact (lift_inj.mp this).symm end /-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the basis. This lemma uses a `finset` instead of indexed types. -/ lemma findim_eq_card_finset_basis {b : finset V} (h : is_basis K (subtype.val : (↑b : set V) -> V)) : findim K V = finset.card b := by { rw [findim_eq_card_basis h, fintype.subtype_card], intros x, refl } lemma equiv_fin {ι : Type*} [finite_dimensional K V] {v : ι → V} (hv : is_basis K v) : ∃ g : fin (findim K V) ≃ ι, is_basis K (v ∘ g) := begin have : (cardinal.mk (fin $ findim K V)).lift = (cardinal.mk ι).lift, { simp [cardinal.mk_fin (findim K V), ← findim_eq_card_basis' hv] }, rcases cardinal.lift_mk_eq.mp this with ⟨g⟩, exact ⟨g, hv.comp _ g.bijective⟩ end variables (K V) lemma fin_basis [finite_dimensional K V] : ∃ v : fin (findim K V) → V, is_basis K v := let ⟨B, hB, B_fin⟩ := exists_is_basis_finite K V, ⟨g, hg⟩ := finite_dimensional.equiv_fin hB in ⟨coe ∘ g, hg⟩ variables {K V} lemma cardinal_mk_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) : cardinal.mk ι ≤ findim K V := begin rw ← lift_le.{_ (max v w)}, simpa [← findim_eq_dim K V] using cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h end lemma fintype_card_le_findim_of_linear_independent [finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) : fintype.card ι ≤ findim K V := by simpa [fintype_card] using cardinal_mk_le_findim_of_linear_independent h lemma finset_card_le_findim_of_linear_independent [finite_dimensional K V] {b : finset V} (h : linear_independent K (λ x, x : (↑b : set V) → V)) : b.card ≤ findim K V := begin rw ←fintype.card_coe, exact fintype_card_le_findim_of_linear_independent h, end lemma lt_omega_of_linear_independent {ι : Type w} [finite_dimensional K V] {v : ι → V} (h : linear_independent K v) : cardinal.mk ι < cardinal.omega := begin apply cardinal.lift_lt.1, apply lt_of_le_of_lt, apply linear_independent_le_dim h, rw [←findim_eq_dim, cardinal.lift_omega, cardinal.lift_nat_cast], apply cardinal.nat_lt_omega, end lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V] (v : ι → V) : ¬ linear_independent K v := begin intro h_lin_indep, have : ¬ omega ≤ mk ι := not_le.mpr (lt_omega_of_linear_independent h_lin_indep), have : omega ≤ mk ι := infinite_iff.mp inf, contradiction end /-- A finite dimensional space has positive `findim` iff it has a nonzero element. -/ lemma findim_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < findim K V ↔ ∃ x : V, x ≠ 0 := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _) /-- A finite dimensional space has positive `findim` iff it is nontrivial. -/ lemma findim_pos_iff [finite_dimensional K V] : 0 < findim K V ↔ nontrivial V := iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _) /-- A nontrivial finite dimensional space has positive `findim`. -/ lemma findim_pos [finite_dimensional K V] [h : nontrivial V] : 0 < findim K V := findim_pos_iff.mpr h section open_locale big_operators open finset /-- If a finset has cardinality larger than the dimension of the space, then there is a nontrivial linear relation amongst its elements. -/ lemma exists_nontrivial_relation_of_dim_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin have := mt finset_card_le_findim_of_linear_independent (by { simpa using h }), rw linear_dependent_iff at this, obtain ⟨s, g, sum, z, zm, nonzero⟩ := this, -- Now we have to extend `g` to all of `t`, then to all of `V`. let f : V → K := λ x, if h : x ∈ t then if (⟨x, h⟩ : (↑t : set V)) ∈ s then g ⟨x, h⟩ else 0 else 0, -- and finally clean up the mess caused by the extension. refine ⟨f, _, _⟩, { dsimp [f], rw ← sum, fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})), { intros v hvt H, dsimp, rw [dif_pos hvt] at H, contrapose! H, rw [if_neg H, zero_smul], }, { intros _ _ _ _ _ _, exact subtype.mk.inj, }, { intros b hbs hb, use b, simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem, eq_self_iff_true, exists_prop_of_true, ne.def] using hb, }, { intros a h₁, dsimp, rw [dif_pos h₁], intro h₂, rw [if_pos], contrapose! h₂, rw [if_neg h₂, zero_smul], }, }, { refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] }, end /-- If a finset has cardinality larger than `findim + 1`, then there is a nontrivial linear relation amongst its elements, such that the coefficients of the relation sum to zero. -/ lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card [finite_dimensional K V] {t : finset V} (h : findim K V + 1 < t.card) : ∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 := begin -- Pick an element x₀ ∈ t, have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h, obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex, -- and apply the previous lemma to the {xᵢ - x₀} let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩, let t' := (t.erase x₀).map shift, have h' : findim K V < t'.card, { simp only [t', card_map, finset.card_erase_of_mem m], exact nat.lt_pred_iff.mpr h, }, -- to obtain a function `g`. obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h', -- Then obtain `f` by translating back by `x₀`, -- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`. let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀), refine ⟨f, _ ,_ ,_⟩, -- After this, it's a matter of verifiying the properties, -- based on the corresponding properties for `g`. { show ∑ (e : V) in t, f e • e = 0, -- We prove this by splitting off the `x₀` term of the sum, -- which is itself a sum over `t.erase x₀`, -- combining the two sums, and -- observing that after reindexing we have exactly -- ∑ (x : V) in t', g x • x = 0. simp only [f], conv_lhs { apply_congr, skip, rw [ite_smul], }, rw [finset.sum_ite], conv { congr, congr, apply_congr, simp [filter_eq', m], }, conv { congr, congr, skip, apply_congr, simp [filter_ne'], }, rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib], simp only [←smul_sub], -- At the end we have to reindex the sum, so we use `change` to -- express the summand using `shift`. change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0, rw ←sum_map _ shift, exact gsum, }, { show ∑ (e : V) in t, f e = 0, -- Again we split off the `x₀` term, -- observing that it exactly cancels the other terms. rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)], dsimp [f], rw [if_pos rfl], conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), }, exact neg_add_self _, }, { show ∃ (x : V) (H : x ∈ t), f x ≠ 0, -- We can use x₁ + x₀. refine ⟨x₁ + x₀, _, _⟩, { rw finset.mem_map at x₁_mem, rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩, rw mem_erase at x₁_mem, simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], }, { dsimp only [f], rwa [if_neg, add_sub_cancel], rw [add_left_eq_self], rintro rfl, simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true, mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } }, end section variables {L : Type*} [linear_ordered_field L] variables {W : Type v} [add_comm_group W] [vector_space L W] /-- A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card` available when working over an ordered field: we can ensure a positive coefficient, not just a nonzero coefficient. -/ lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card [finite_dimensional L W] {t : finset W} (h : findim L W + 1 < t.card) : ∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x := begin obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h, exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩, end end end /-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the whole space. -/ lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V} (h : findim K S = findim K V) : S = ⊤ := begin cases exists_is_basis K S with bS hbS, have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V), from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _ (submodule.subtype S) hbS.1 (by simp), cases exists_subset_is_basis this with b hb, letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1), letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this), letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1), have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1 (by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS, ← findim_eq_card_basis hb.2, h]; apply_instance), erw [← hb.2.2, subtype.range_coe, ← this, ← subtype_eq_val, span_image], have := hbS.2, erw [subtype.range_coe] at this, rw [this, map_top (submodule.subtype S), range_subtype], end variable (K) /-- A field is one-dimensional as a vector space over itself. -/ @[simp] lemma findim_of_field : findim K K = 1 := begin have := dim_of_field K, rw [← findim_eq_dim] at this, exact_mod_cast this end /-- The vector space of functions on a fintype has finite dimension. -/ instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] : finite_dimensional K (ι → K) := by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ } /-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/ @[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] : findim K (ι → K) = fintype.card ι := begin have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun', rwa [← findim_eq_dim, nat_cast_inj] at this, end /-- The vector space of functions on `fin n` has findim equal to `n`. -/ @[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n := by simp /-- The submodule generated by a finite set is finite-dimensional. -/ theorem span_of_finite {A : set V} (hA : set.finite A) : finite_dimensional K (submodule.span K A) := is_noetherian_span_of_finite K hA /-- The submodule generated by a single element is finite-dimensional. -/ instance (x : V) : finite_dimensional K (K ∙ x) := by {apply span_of_finite, simp} end finite_dimensional section zero_dim open vector_space finite_dimensional lemma finite_dimensional_of_dim_eq_zero (h : vector_space.dim K V = 0) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact cardinal.omega_pos lemma finite_dimensional_of_dim_eq_one (h : vector_space.dim K V = 1) : finite_dimensional K V := by rw [finite_dimensional_iff_dim_lt_omega, h]; exact one_lt_omega lemma findim_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : vector_space.dim K V = 0) : findim K V = 0 := begin convert findim_eq_dim K V, rw h, norm_cast end variables (K V) lemma finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) := finite_dimensional_of_dim_eq_zero $ by simp @[simp] lemma findim_bot : findim K (⊥ : submodule K V) = 0 := begin haveI := finite_dimensional_bot K V, convert findim_eq_dim K (⊥ : submodule K V), rw dim_bot, norm_cast end variables {K V} lemma bot_eq_top_of_dim_eq_zero (h : vector_space.dim K V = 0) : (⊥ : submodule K V) = ⊤ := begin haveI := finite_dimensional_of_dim_eq_zero h, apply eq_top_of_findim_eq, rw [findim_bot, findim_eq_zero_of_dim_eq_zero h] end @[simp] theorem dim_eq_zero {S : submodule K V} : dim K S = 0 ↔ S = ⊥ := ⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $ ((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top, λ h, by rw [h, dim_bot]⟩ @[simp] theorem findim_eq_zero {S : submodule K V} [finite_dimensional K S] : findim K S = 0 ↔ S = ⊥ := by rw [← dim_eq_zero, ← findim_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj] end zero_dim namespace submodule open finite_dimensional /-- A submodule is finitely generated if and only if it is finite-dimensional -/ theorem fg_iff_finite_dimensional (s : submodule K V) : s.fg ↔ finite_dimensional K s := ⟨λh, is_noetherian_of_fg_of_noetherian s h, λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩ /-- A submodule contained in a finite-dimensional submodule is finite-dimensional. -/ lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) : finite_dimensional K S₁ := finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h) (dim_lt_omega K S₂)) /-- The inf of two submodules, the first finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_left /-- The inf of two submodules, the second finite-dimensional, is finite-dimensional. -/ instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] : finite_dimensional K (S₁ ⊓ S₂ : submodule K V) := finite_dimensional_of_le inf_le_right /-- The sup of two finite-dimensional submodules is finite-dimensional. -/ instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁] [h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) := begin rw ←submodule.fg_iff_finite_dimensional at *, exact submodule.fg_sup h₁ h₂ end /-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding quotient add up to the dimension of the space. -/ theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) : findim K s.quotient + findim K s = findim K V := begin have := dim_quotient_add_dim s, rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this, exact_mod_cast this end /-- The dimension of a submodule is bounded by the dimension of the ambient space. -/ lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ } /-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient space. -/ lemma findim_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) : findim K s < findim K V := begin rw [← s.findim_quotient_add_findim, add_comm], exact nat.lt_add_of_zero_lt_left _ _ (findim_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h)) end /-- The dimension of a quotient is bounded by the dimension of the ambient space. -/ lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) : findim K s.quotient ≤ findim K V := by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ } /-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/ theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s] [finite_dimensional K t] : findim K ↥(s ⊔ t) + findim K ↥(s ⊓ t) = findim K ↥s + findim K ↥t := begin have key : dim K ↥(s ⊔ t) + dim K ↥(s ⊓ t) = dim K s + dim K t := dim_sup_add_dim_inf_eq s t, repeat { rw ←findim_eq_dim at key }, norm_cast at key, exact key end lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V) (hdim : findim K s + findim K t = findim K V) (hdisjoint : disjoint s t) : s ⊔ t = ⊤ := begin have h_findim_inf : findim K ↥(s ⊓ t) = 0, { rw [disjoint, le_bot_iff] at hdisjoint, rw [hdisjoint, findim_bot] }, apply eq_top_of_findim_eq, rw ←hdim, convert s.dim_sup_add_dim_inf_eq t, rw h_findim_inf, refl, end end submodule namespace linear_equiv open finite_dimensional /-- Finite dimensionality is preserved under linear equivalence. -/ protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : finite_dimensional K V₂ := is_noetherian_of_linear_equiv f /-- The dimension of a finite dimensional space is preserved under linear equivalence. -/ theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] : findim K V = findim K V₂ := begin haveI : finite_dimensional K V₂ := f.finite_dimensional, simpa [← findim_eq_dim] using f.lift_dim_eq end end linear_equiv namespace finite_dimensional /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : nonempty (V ≃ₗ[K] V₂) := nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← findim_eq_dim, cond, lift_nat_cast] /-- Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite) dimension. -/ theorem nonempty_linear_equiv_iff_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] : nonempty (V ≃ₗ[K] V₂) ↔ findim K V = findim K V₂ := ⟨λ ⟨h⟩, h.findim_eq, λ h, nonempty_linear_equiv_of_findim_eq h⟩ section variables (V V₂) /-- Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension. -/ noncomputable def linear_equiv.of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] (cond : findim K V = findim K V₂) : V ≃ₗ[K] V₂ := classical.choice $ nonempty_linear_equiv_of_findim_eq cond end lemma eq_of_le_of_findim_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₂ ≤ findim K S₁) : S₁ = S₂ := begin rw ←linear_equiv.findim_eq (submodule.comap_subtype_equiv_of_le hle) at hd, exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_findim_eq (le_antisymm (comap (submodule.subtype S₂) S₁).findim_le hd))), end /-- If a submodule is less than or equal to a finite-dimensional submodule with the same dimension, they are equal. -/ lemma eq_of_le_of_findim_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂) (hd : findim K S₁ = findim K S₂) : S₁ = S₂ := eq_of_le_of_findim_le hle hd.ge end finite_dimensional namespace linear_map open finite_dimensional /-- On a finite-dimensional space, an injective linear map is surjective. -/ lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V} (hinj : injective f) : surjective f := begin have h := dim_eq_of_injective _ hinj, rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h, exact range_eq_top.1 (eq_top_of_findim_eq h.symm) end /-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/ lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} : injective f ↔ surjective f := ⟨surjective_of_injective, λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in have function.right_inverse g f, from linear_map.ext_iff.1 hg, (left_inverse_of_surjective_of_right_inverse (surjective_of_injective this.injective) this).injective⟩ lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} : f.ker = ⊥ ↔ f.range = ⊤ := by rw [range_eq_top, ker_eq_bot, injective_iff_surjective] /-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they are also inverse to each other on the other side. -/ lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) : g * f = 1 := have ginj : injective g, from has_left_inverse.injective ⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩, let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective (range_eq_top.2 (injective_iff_surjective.1 ginj)) in have f * (g * i) = f * 1, from congr_arg _ hi, by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 := ⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩ /-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if they are inverse to each other on the other side. -/ lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id := mul_eq_one_comm /-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/ lemma finite_dimensional_of_surjective [h : finite_dimensional K V] (f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ := is_noetherian_of_surjective V f hf /-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/ instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) : finite_dimensional K f.range := f.quot_ker_equiv_range.finite_dimensional /-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to the dimension of the source space. -/ theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) : findim K f.range + findim K f.ker = findim K V := by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ } end linear_map namespace linear_equiv open finite_dimensional variables [finite_dimensional K V] /-- The linear equivalence corresponging to an injective endomorphism. -/ noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : V ≃ₗ[K] V := (linear_equiv.of_injective f h_inj).trans (linear_equiv.of_top _ (linear_map.ker_eq_bot_iff_range_eq_top.1 h_inj)) lemma of_injective_endo_to_fun (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : (of_injective_endo f h_inj).to_fun = f := rfl lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : f * (of_injective_endo f h_inj).symm = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change f ((of_injective_endo f h_inj).symm x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).right_inv, end lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : ((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 := begin ext, simp only [linear_map.one_app, linear_map.mul_app], change (of_injective_endo f h_inj).symm (f x) = x, rw ← linear_equiv.inv_fun_apply (of_injective_endo f h_inj), apply (of_injective_endo f h_inj).left_inv, end end linear_equiv namespace linear_map lemma is_unit_iff [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ := begin split, { intro h_is_unit, rcases h_is_unit with ⟨u, hu⟩, rw [←hu, linear_map.ker_eq_bot'], intros x hx, change (1 : V →ₗ[K] V) x = 0, rw ← u.inv_val, change u.inv (u x) = 0, simp [hx] }, { intro h_inj, use ⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map, linear_equiv.of_injective_endo_right_inv f h_inj, linear_equiv.of_injective_endo_left_inv f h_inj⟩, refl } end end linear_map open vector_space finite_dimensional section top @[simp] theorem findim_top : findim K (⊤ : submodule K V) = findim K V := by { unfold findim, simp [dim_top] } end top namespace linear_map theorem injective_iff_surjective_of_findim_eq_findim [finite_dimensional K V] [finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} : function.injective f ↔ function.surjective f := begin have := findim_range_add_findim_ker f, rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩, { rw [h, findim_bot, add_zero, H] at this, exact eq_top_of_findim_eq this }, { rw [h, findim_top, H] at this, exact findim_eq_zero.1 (add_right_injective _ this) } end theorem findim_le_findim_of_injective [finite_dimensional K V] [finite_dimensional K V₂] {f : V →ₗ[K] V₂} (hf : function.injective f) : findim K V ≤ findim K V₂ := calc findim K V = findim K f.range + findim K f.ker : (findim_range_add_findim_ker f).symm ... = findim K f.range : by rw [ker_eq_bot.2 hf, findim_bot, add_zero] ... ≤ findim K V₂ : submodule.findim_le _ end linear_map namespace alg_hom lemma bijective {F : Type*} [field F] {E : Type*} [field E] [algebra F E] [finite_dimensional F E] (ϕ : E →ₐ[F] E) : function.bijective ϕ := have inj : function.injective ϕ.to_linear_map := ϕ.to_ring_hom.injective, ⟨inj, (linear_map.injective_iff_surjective_of_findim_eq_findim rfl).mp inj⟩ end alg_hom /-- Bijection between algebra equivalences and algebra homomorphisms -/ noncomputable def alg_equiv_equiv_alg_hom (F : Type u) [field F] (E : Type v) [field E] [algebra F E] [finite_dimensional F E] : (E ≃ₐ[F] E) ≃ (E →ₐ[F] E) := { to_fun := λ ϕ, ϕ.to_alg_hom, inv_fun := λ ϕ, alg_equiv.of_bijective ϕ ϕ.bijective, left_inv := λ _, by {ext, refl}, right_inv := λ _, by {ext, refl} } section /-- An integral domain that is module-finite as an algebra over a field is a field. -/ noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [integral_domain K] [algebra F K] [finite_dimensional F K] : field K := { inv := λ x, if H : x = 0 then 0 else classical.some $ (show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1, mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx, exact classical.some_spec ((show function.surjective (algebra.lmul_left F x), from linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) }, inv_zero := dif_pos rfl, .. ‹integral_domain K› } end namespace submodule lemma findim_mono [finite_dimensional K V] : monotone (λ (s : submodule K V), findim K s) := λ s t hst, calc findim K s = findim K (comap t.subtype s) : linear_equiv.findim_eq (comap_subtype_equiv_of_le hst).symm ... ≤ findim K t : submodule.findim_le _ lemma lt_of_le_of_findim_lt_findim {s t : submodule K V} (le : s ≤ t) (lt : findim K s < findim K t) : s < t := lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h)) lemma lt_top_of_findim_lt_findim {s : submodule K V} (lt : findim K s < findim K V) : s < ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, rw ← @findim_top K V at lt, exact lt_of_le_of_findim_lt_findim le_top lt }, { exfalso, have : findim K V = 0 := dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin), rw this at lt, exact nat.not_lt_zero _ lt } end lemma findim_lt_findim_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) : findim K s < findim K t := begin rw linear_equiv.findim_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm, refine findim_lt (lt_of_le_of_ne le_top _), intro h_eq_top, rw comap_subtype_eq_top at h_eq_top, apply not_le_of_lt hst h_eq_top, end end submodule section span open submodule lemma findim_span_le_card (s : set V) [fin : fintype s] : findim K (span K s) ≤ s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) ≤ (mk s : cardinal) := dim_span_le s, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma findim_span_eq_card {ι : Type*} [fintype ι] {b : ι → V} (hb : linear_independent K b) : findim K (span K (set.range b)) = fintype.card ι := begin haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b), have : dim K (span K (set.range b)) = (mk (set.range b) : cardinal) := dim_span hb, rwa [←findim_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective, cardinal.fintype_card, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this, end lemma findim_span_set_eq_card (s : set V) [fin : fintype s] (hs : linear_independent K (coe : s → V)) : findim K (span K s) = s.to_finset.card := begin haveI := span_of_finite K ⟨fin⟩, have : dim K (span K s) = (mk s : cardinal) := dim_span_set hs, rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this, exact_mod_cast this end lemma span_lt_of_subset_of_card_lt_findim {s : set V} [fintype s] {t : submodule K V} (subset : s ⊆ t) (card_lt : s.to_finset.card < findim K t) : span K s < t := lt_of_le_of_findim_lt_findim (span_le.mpr subset) (lt_of_le_of_lt (findim_span_le_card _) card_lt) lemma span_lt_top_of_card_lt_findim {s : set V} [fintype s] (card_lt : s.to_finset.card < findim K V) : span K s < ⊤ := lt_top_of_findim_lt_findim (lt_of_le_of_lt (findim_span_le_card _) card_lt) end span section is_basis lemma linear_independent_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : linear_independent K b := linear_independent_iff'.mpr $ λ s g dependent i i_mem_s, begin by_contra gx_ne_zero, -- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1` -- spans a vector space of dimension `n`. refine ne_of_lt (span_lt_top_of_card_lt_findim (show (b '' (set.univ \ {i})).to_finset.card < findim K V, from _)) _, { calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card : by rw [set.to_finset_card, fintype.card_of_finset] ... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le ... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm])) ... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i) ... = findim K V : card_eq }, -- We already have that `b '' univ` spans the whole space, -- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`. refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq, rintros _ ⟨j, rfl, rfl⟩, -- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`. by_cases j_eq : j = i, swap, { refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩, exact mt set.mem_singleton_iff.mp j_eq }, -- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum -- of the other `b j`s. rw [j_eq, mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _], { refine submodule.neg_mem _ (smul_mem _ _ (sum_mem _ (λ k hk, _))), obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk, refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩), simpa using k_mem }, -- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum -- to have the form of the assumption `dependent`. apply eq_neg_of_add_eq_zero, calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j) = (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j)) : by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul] ... = (g i)⁻¹ • 0 : congr_arg _ _ ... = 0 : smul_zero _, -- And then it's just a bit of manipulation with finite sums. rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent end /-- A finite family of vectors is linearly independent if and only if its cardinality equals the dimension of its span. -/ lemma linear_independent_iff_card_eq_findim_span {ι : Type*} [fintype ι] {b : ι → V} : linear_independent K b ↔ fintype.card ι = findim K (span K (set.range b)) := begin split, { intro h, exact (findim_span_eq_card h).symm }, { intro hc, let f := (submodule.subtype (span K (set.range b))), let b' : ι → span K (set.range b) := λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩, have hs : span K (set.range b') = ⊤, { rw eq_top_iff', intro x, have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f, have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] }, rw hf at h, have hx : (x : V) ∈ span K (set.range b) := x.property, conv at hx { congr, skip, rw h }, simpa [mem_map] using hx }, have hi : f.ker = ⊥ := ker_subtype _, convert (linear_independent_of_span_eq_top_of_card_eq_findim hs hc).map' _ hi } end lemma is_basis_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V} (span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨linear_independent_of_span_eq_top_of_card_eq_findim span_eq card_eq, span_eq⟩ lemma finset_is_basis_of_span_eq_top_of_card_eq_findim {s : finset V} (span_eq : span K (↑s : set V) = ⊤) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq) (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_span_eq_top_of_card_eq_findim {s : set V} [fintype s] (span_eq : span K s = ⊤) (card_eq : s.to_finset.card = findim K V) : is_basis K (λ (x : s), (x : V)) := is_basis_of_span_eq_top_of_card_eq_findim ((@subtype.range_coe_subtype _ s).symm ▸ span_eq) (trans s.to_finset_card.symm card_eq) lemma span_eq_top_of_linear_independent_of_card_eq_findim {ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : span K (set.range b) = ⊤ := begin by_cases fin : (finite_dimensional K V), { haveI := fin, by_contra ne_top, have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top, exact ne_of_lt (submodule.findim_lt lt_top) (trans (findim_span_eq_card lin_ind) card_eq) }, { exfalso, apply ne_of_lt (fintype.card_pos_iff.mpr hι), symmetry, calc fintype.card ι = findim K V : card_eq ... = 0 : dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin) } end lemma is_basis_of_linear_independent_of_card_eq_findim {ι : Type*} [nonempty ι] [fintype ι] {b : ι → V} (lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) : is_basis K b := ⟨lin_ind, span_eq_top_of_linear_independent_of_card_eq_findim lin_ind card_eq⟩ lemma finset_is_basis_of_linear_independent_of_card_eq_findim {s : finset V} (hs : s.nonempty) (lin_ind : linear_independent K (coe : (↑s : set V) → V)) (card_eq : s.card = findim K V) : is_basis K (coe : (↑s : set V) → V) := @is_basis_of_linear_independent_of_card_eq_findim _ _ _ _ _ _ ⟨(⟨hs.some, hs.some_spec⟩ : (↑s : set V))⟩ _ _ lin_ind (trans (fintype.card_coe _) card_eq) lemma set_is_basis_of_linear_independent_of_card_eq_findim {s : set V} [nonempty s] [fintype s] (lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = findim K V) : is_basis K (coe : s → V) := is_basis_of_linear_independent_of_card_eq_findim lin_ind (trans s.to_finset_card.symm card_eq) end is_basis section subalgebra_dim open vector_space variables {F E : Type*} [field F] [field E] [algebra F E] lemma subalgebra.dim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : dim F S = 1 := begin rw [← S.to_submodule_equiv.dim_eq, h, (linear_equiv.of_eq ↑(⊥ : subalgebra F E) _ algebra.to_submodule_bot).dim_eq, dim_span_set], exacts [mk_singleton _, linear_independent_singleton one_ne_zero] end @[simp] lemma subalgebra.dim_bot : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_eq_one_of_eq_bot rfl lemma subalgebra_top_dim_eq_submodule_top_dim : dim F (⊤ : subalgebra F E) = dim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra_top_findim_eq_submodule_top_findim : findim F (⊤ : subalgebra F E) = findim F (⊤ : submodule F E) := by { rw ← algebra.coe_top, refl } lemma subalgebra.dim_top : dim F (⊤ : subalgebra F E) = dim F E := by { rw subalgebra_top_dim_eq_submodule_top_dim, exact dim_top } lemma subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) := finite_dimensional_of_dim_eq_one subalgebra.dim_bot @[simp] lemma subalgebra.findim_bot : findim F (⊥ : subalgebra F E) = 1 := begin haveI : finite_dimensional F (⊥ : subalgebra F E) := subalgebra.finite_dimensional_bot, have : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_bot, rw ← findim_eq_dim at this, norm_cast at *, simp *, end lemma subalgebra.findim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : findim F S = 1 := by { rw h, exact subalgebra.findim_bot } lemma subalgebra.eq_bot_of_findim_one {S : subalgebra F E} (h : findim F S = 1) : S = ⊥ := begin rw eq_bot_iff, let b : set S := {1}, have : fintype b := unique.fintype, have b_lin_ind : linear_independent F (coe : b → S) := linear_independent_singleton one_ne_zero, have b_card : fintype.card b = 1 := fintype.card_of_subsingleton _, obtain ⟨_, b_spans⟩ := set_is_basis_of_linear_independent_of_card_eq_findim b_lin_ind (by simp only [*, set.to_finset_card]), intros x hx, rw [subalgebra.mem_coe, algebra.mem_bot], have x_in_span_b : (⟨x, hx⟩ : S) ∈ submodule.span F b, { rw subtype.range_coe at b_spans, rw b_spans, exact submodule.mem_top, }, obtain ⟨a, ha⟩ := submodule.mem_span_singleton.mp x_in_span_b, replace ha : a • 1 = x := by injections with ha, exact ⟨a, by rw [← ha, algebra.smul_def, mul_one]⟩, end lemma subalgebra.eq_bot_of_dim_one {S : subalgebra F E} (h : dim F S = 1) : S = ⊥ := begin haveI : finite_dimensional F S := finite_dimensional_of_dim_eq_one h, rw ← findim_eq_dim at h, norm_cast at h, exact subalgebra.eq_bot_of_findim_one h, end @[simp] lemma subalgebra.bot_eq_top_of_dim_eq_one (h : dim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim] at h, exact eq.symm (subalgebra.eq_bot_of_dim_one h), end @[simp] lemma subalgebra.bot_eq_top_of_findim_eq_one (h : findim F E = 1) : (⊥ : subalgebra F E) = ⊤ := begin rw [← findim_top, ← subalgebra_top_findim_eq_submodule_top_findim] at h, exact eq.symm (subalgebra.eq_bot_of_findim_one h), end @[simp] theorem subalgebra.dim_eq_one_iff {S : subalgebra F E} : dim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_dim_one, subalgebra.dim_eq_one_of_eq_bot⟩ @[simp] theorem subalgebra.findim_eq_one_iff {S : subalgebra F E} : findim F S = 1 ↔ S = ⊥ := ⟨subalgebra.eq_bot_of_findim_one, subalgebra.findim_eq_one_of_eq_bot⟩ end subalgebra_dim namespace module namespace End lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) : ∃ (k : ℕ), k ≤ findim K V ∧ (f ^ k).ker = (f ^ k.succ).ker := begin classical, by_contradiction h_contra, simp_rw [not_exists, not_and] at h_contra, have h_le_ker_pow : ∀ (n : ℕ), n ≤ (findim K V).succ → n ≤ findim K (f ^ n).ker, { intros n hn, induction n with n ih, { exact zero_le (findim _ _) }, { have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker, { refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)), rw pow_succ, apply linear_map.ker_le_ker_comp }, have h_findim_lt_findim : findim K (f ^ n).ker < findim K (f ^ n.succ).ker, { apply submodule.findim_lt_findim_of_lt h_ker_lt_ker }, calc n.succ ≤ (findim K ↥(linear_map.ker (f ^ n))).succ : nat.succ_le_succ (ih (nat.le_of_succ_le hn)) ... ≤ findim K ↥(linear_map.ker (f ^ n.succ)) : nat.succ_le_of_lt h_findim_lt_findim } }, have h_le_findim_V : ∀ n, findim K (f ^ n).ker ≤ findim K V := λ n, submodule.findim_le _, have h_any_n_lt: ∀ n, n ≤ (findim K V).succ → n ≤ findim K V := λ n hn, (h_le_ker_pow n hn).trans (h_le_findim_V n), show false, from nat.not_succ_le_self _ (h_any_n_lt (findim K V).succ (findim K V).succ.le_refl), end lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) : ∀ m, (f ^ k).ker = (f ^ (k + m)).ker | 0 := by simp | (m + 1) := begin apply le_antisymm, { rw [add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m], change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)), rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one], exact le_refl _, } end lemma ker_pow_eq_ker_pow_findim_of_le [finite_dimensional K V] {f : End K V} {m : ℕ} (hm : findim K V ≤ m) : (f ^ m).ker = (f ^ findim K V).ker := begin obtain ⟨k, h_k_le, hk⟩ : ∃ k, k ≤ findim K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) := exists_ker_pow_eq_ker_pow_succ f, calc (f ^ m).ker = (f ^ (k + (m - k))).ker : by rw nat.add_sub_of_le (h_k_le.trans hm) ... = (f ^ k).ker : by rw ker_pow_constant hk _ ... = (f ^ (k + (findim K V - k))).ker : ker_pow_constant hk (findim K V - k) ... = (f ^ findim K V).ker : by rw nat.add_sub_of_le h_k_le end lemma ker_pow_le_ker_pow_findim [finite_dimensional K V] (f : End K V) (m : ℕ) : (f ^ m).ker ≤ (f ^ findim K V).ker := begin by_cases h_cases: m < findim K V, { rw [←nat.add_sub_of_le (nat.le_of_lt h_cases), add_comm, pow_add], apply linear_map.ker_le_ker_comp }, { rw [ker_pow_eq_ker_pow_findim_of_le (le_of_not_lt h_cases)], exact le_refl _ } end end End end module
aef50b01545ad1862835a47284b0a645850f7388
64874bd1010548c7f5a6e3e8902efa63baaff785
/library/data/list/basic.lean
7d30a58a5bf578fba3d0e1193cf1b6d247035487
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,982
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.list.basic Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura Basic properties of lists. -/ import logic tools.helper_tactics data.nat.basic open eq.ops helper_tactics nat inductive list (T : Type) : Type := nil {} : list T, cons : T → list T → list T namespace list notation h :: t := cons h t notation `[` l:(foldr `,` (h t, cons h t) nil) `]` := l variable {T : Type} /- append -/ definition append : list T → list T → list T, append nil l := l, append (h :: s) t := h :: (append s t) notation l₁ ++ l₂ := append l₁ l₂ theorem append_nil_left (t : list T) : nil ++ t = t theorem append_cons (x : T) (s t : list T) : (x::s) ++ t = x::(s ++ t) theorem append_nil_right : ∀ (t : list T), t ++ nil = t, append_nil_right nil := rfl, append_nil_right (a :: l) := calc (a :: l) ++ nil = a :: (l ++ nil) : rfl ... = a :: l : append_nil_right l theorem append.assoc : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u), append.assoc nil t u := rfl, append.assoc (a :: l) t u := calc (a :: l) ++ t ++ u = a :: (l ++ t ++ u) : rfl ... = a :: (l ++ (t ++ u)) : append.assoc ... = (a :: l) ++ (t ++ u) : rfl /- length -/ definition length : list T → nat, length nil := 0, length (a :: l) := length l + 1 theorem length_nil : length (@nil T) = 0 theorem length_cons (x : T) (t : list T) : length (x::t) = length t + 1 theorem length_append : ∀ (s t : list T), length (s ++ t) = length s + length t, length_append nil t := calc length (nil ++ t) = length t : rfl ... = length nil + length t : zero_add, length_append (a :: s) t := calc length (a :: s ++ t) = length (s ++ t) + 1 : rfl ... = length s + length t + 1 : length_append ... = (length s + 1) + length t : add.succ_left ... = length (a :: s) + length t : rfl -- add_rewrite length_nil length_cons /- concat -/ definition concat : Π (x : T), list T → list T, concat a nil := [a], concat a (b :: l) := b :: concat a l theorem concat_nil (x : T) : concat x nil = [x] theorem concat_cons (x y : T) (l : list T) : concat x (y::l) = y::(concat x l) theorem concat_eq_append (a : T) : ∀ (l : list T), concat a l = l ++ [a], concat_eq_append nil := rfl, concat_eq_append (b :: l) := calc concat a (b :: l) = b :: (concat a l) : rfl ... = b :: (l ++ [a]) : concat_eq_append ... = (b :: l) ++ [a] : rfl -- add_rewrite append_nil append_cons /- reverse -/ definition reverse : list T → list T, reverse nil := nil, reverse (a :: l) := concat a (reverse l) theorem reverse_nil : reverse (@nil T) = nil theorem reverse_cons (x : T) (l : list T) : reverse (x::l) = concat x (reverse l) theorem reverse_singleton (x : T) : reverse [x] = [x] theorem reverse_append : ∀ (s t : list T), reverse (s ++ t) = (reverse t) ++ (reverse s), reverse_append nil t2 := calc reverse (nil ++ t2) = reverse t2 : rfl ... = (reverse t2) ++ nil : append_nil_right ... = (reverse t2) ++ (reverse nil) : {reverse_nil⁻¹}, reverse_append (a2 :: s2) t2 := calc reverse ((a2 :: s2) ++ t2) = concat a2 (reverse (s2 ++ t2)) : rfl ... = concat a2 (reverse t2 ++ reverse s2) : reverse_append ... = (reverse t2 ++ reverse s2) ++ [a2] : concat_eq_append ... = reverse t2 ++ (reverse s2 ++ [a2]) : append.assoc ... = reverse t2 ++ concat a2 (reverse s2) : concat_eq_append ... = reverse t2 ++ reverse (a2 :: s2) : rfl theorem reverse_reverse : ∀ (l : list T), reverse (reverse l) = l, reverse_reverse nil := rfl, reverse_reverse (a :: l) := calc reverse (reverse (a :: l)) = reverse (concat a (reverse l)) : rfl ... = reverse (reverse l ++ [a]) : concat_eq_append ... = reverse [a] ++ reverse (reverse l) : reverse_append ... = reverse [a] ++ l : reverse_reverse ... = a :: l : rfl theorem concat_eq_reverse_cons (x : T) (l : list T) : concat x l = reverse (x :: reverse l) := calc concat x l = concat x (reverse (reverse l)) : reverse_reverse ... = reverse (x :: reverse l) : rfl /- head and tail -/ definition head [h : inhabited T] : list T → T, head nil := arbitrary T, head (a :: l) := a theorem head_cons [h : inhabited T] (a : T) (l : list T) : head (a::l) = a theorem head_concat [h : inhabited T] {s : list T} (t : list T) : s ≠ nil → head (s ++ t) = head s := cases_on s (take H : nil ≠ nil, absurd rfl H) (take (x : T) (s : list T), take H : x::s ≠ nil, calc head ((x::s) ++ t) = head (x::(s ++ t)) : rfl ... = x : head_cons ... = head (x::s) : rfl) definition tail : list T → list T, tail nil := nil, tail (a :: l) := l theorem tail_nil : tail (@nil T) = nil theorem tail_cons (a : T) (l : list T) : tail (a::l) = l theorem cons_head_tail [h : inhabited T] {l : list T} : l ≠ nil → (head l)::(tail l) = l := cases_on l (assume H : nil ≠ nil, absurd rfl H) (take x l, assume H : x::l ≠ nil, rfl) /- list membership -/ definition mem : T → list T → Prop, mem a nil := false, mem a (b :: l) := a = b ∨ mem a l notation e ∈ s := mem e s theorem mem_nil (x : T) : x ∈ nil ↔ false := iff.rfl theorem mem_cons (x y : T) (l : list T) : x ∈ y::l ↔ (x = y ∨ x ∈ l) := iff.rfl theorem mem_concat_imp_or {x : T} {s t : list T} : x ∈ s ++ t → x ∈ s ∨ x ∈ t := induction_on s or.inr (take y s, assume IH : x ∈ s ++ t → x ∈ s ∨ x ∈ t, assume H1 : x ∈ y::s ++ t, have H2 : x = y ∨ x ∈ s ++ t, from H1, have H3 : x = y ∨ x ∈ s ∨ x ∈ t, from or_of_or_of_imp_right H2 IH, iff.elim_right or.assoc H3) theorem mem_or_imp_concat {x : T} {s t : list T} : x ∈ s ∨ x ∈ t → x ∈ s ++ t := induction_on s (take H, or.elim H false.elim (assume H, H)) (take y s, assume IH : x ∈ s ∨ x ∈ t → x ∈ s ++ t, assume H : x ∈ y::s ∨ x ∈ t, or.elim H (assume H1, or.elim H1 (take H2 : x = y, or.inl H2) (take H2 : x ∈ s, or.inr (IH (or.inl H2)))) (assume H1 : x ∈ t, or.inr (IH (or.inr H1)))) theorem mem_concat (x : T) (s t : list T) : x ∈ s ++ t ↔ x ∈ s ∨ x ∈ t := iff.intro mem_concat_imp_or mem_or_imp_concat local attribute mem [reducible] local attribute append [reducible] theorem mem_split {x : T} {l : list T} : x ∈ l → ∃s t : list T, l = s ++ (x::t) := induction_on l (take H : x ∈ nil, false.elim (iff.elim_left !mem_nil H)) (take y l, assume IH : x ∈ l → ∃s t : list T, l = s ++ (x::t), assume H : x ∈ y::l, or.elim H (assume H1 : x = y, exists.intro nil (!exists.intro (H1 ▸ rfl))) (assume H1 : x ∈ l, obtain s (H2 : ∃t : list T, l = s ++ (x::t)), from IH H1, obtain t (H3 : l = s ++ (x::t)), from H2, have H4 : y :: l = (y::s) ++ (x::t), from H3 ▸ rfl, !exists.intro (!exists.intro H4))) definition mem.is_decidable [instance] (H : decidable_eq T) (x : T) (l : list T) : decidable (x ∈ l) := rec_on l (decidable.inr (not_of_iff_false !mem_nil)) (take (h : T) (l : list T) (iH : decidable (x ∈ l)), show decidable (x ∈ h::l), from decidable.rec_on iH (assume Hp : x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, decidable.inl (or.inr Hp))) (assume Hn : ¬x ∈ l, decidable.rec_on (H x h) (assume Heq : x = h, decidable.inl (or.inl Heq)) (assume Hne : x ≠ h, have H1 : ¬(x = h ∨ x ∈ l), from assume H2 : x = h ∨ x ∈ l, or.elim H2 (assume Heq, absurd Heq Hne) (assume Hp, absurd Hp Hn), have H2 : ¬x ∈ h::l, from iff.elim_right (not_iff_not_of_iff !mem_cons) H1, decidable.inr H2))) /- find -/ section variable [H : decidable_eq T] include H definition find : T → list T → nat, find a nil := 0, find a (b :: l) := if a = b then 0 else succ (find a l) theorem find_nil (x : T) : find x nil = 0 theorem find_cons (x y : T) (l : list T) : find x (y::l) = if x = y then 0 else succ (find x l) theorem find.not_mem {l : list T} {x : T} : ¬x ∈ l → find x l = length l := rec_on l (assume P₁ : ¬x ∈ nil, _) (take y l, assume iH : ¬x ∈ l → find x l = length l, assume P₁ : ¬x ∈ y::l, have P₂ : ¬(x = y ∨ x ∈ l), from iff.elim_right (not_iff_not_of_iff !mem_cons) P₁, have P₃ : ¬x = y ∧ ¬x ∈ l, from (iff.elim_left not_or_iff_not_and_not P₂), calc find x (y::l) = if x = y then 0 else succ (find x l) : !find_cons ... = succ (find x l) : if_neg (and.elim_left P₃) ... = succ (length l) : {iH (and.elim_right P₃)} ... = length (y::l) : !length_cons⁻¹) end /- nth element -/ definition nth [h : inhabited T] : list T → nat → T, nth nil n := arbitrary T, nth (a :: l) 0 := a, nth (a :: l) (n+1) := nth l n theorem nth_zero [h : inhabited T] (a : T) (l : list T) : nth (a :: l) 0 = a theorem nth_succ [h : inhabited T] (a : T) (l : list T) (n : nat) : nth (a::l) (n+1) = nth l n end list
7eacedb9ef2ec59db71883990caeba57f1b1711f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/data/pnat/basic.lean
6608c0afa66d14c2c8742e236e3c685ea2d570a5
[ "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,582
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Neil Strickland -/ import data.nat.basic /-! # The positive natural numbers This file defines the type `ℕ+` or `pnat`, the subtype of natural numbers that are positive. -/ /-- `ℕ+` is the type of positive natural numbers. It is defined as a subtype, and the VM representation of `ℕ+` is the same as `ℕ` because the proof is not stored. -/ def pnat := {n : ℕ // 0 < n} notation `ℕ+` := pnat instance coe_pnat_nat : has_coe ℕ+ ℕ := ⟨subtype.val⟩ instance : has_repr ℕ+ := ⟨λ n, repr n.1⟩ /-- Predecessor of a `ℕ+`, as a `ℕ`. -/ def pnat.nat_pred (i : ℕ+) : ℕ := i - 1 namespace nat /-- Convert a natural number to a positive natural number. The positivity assumption is inferred by `dec_trivial`. -/ def to_pnat (n : ℕ) (h : 0 < n . tactic.exact_dec_trivial) : ℕ+ := ⟨n, h⟩ /-- Write a successor as an element of `ℕ+`. -/ def succ_pnat (n : ℕ) : ℕ+ := ⟨succ n, succ_pos n⟩ @[simp] theorem succ_pnat_coe (n : ℕ) : (succ_pnat n : ℕ) = succ n := rfl theorem succ_pnat_inj {n m : ℕ} : succ_pnat n = succ_pnat m → n = m := λ h, by { let h' := congr_arg (coe : ℕ+ → ℕ) h, exact nat.succ.inj h' } /-- Convert a natural number to a pnat. `n+1` is mapped to itself, and `0` becomes `1`. -/ def to_pnat' (n : ℕ) : ℕ+ := succ_pnat (pred n) @[simp] theorem to_pnat'_coe : ∀ (n : ℕ), ((to_pnat' n) : ℕ) = ite (0 < n) n 1 | 0 := rfl | (m + 1) := by {rw [if_pos (succ_pos m)], refl} end nat namespace pnat open nat /-- We now define a long list of structures on ℕ+ induced by similar structures on ℕ. Most of these behave in a completely obvious way, but there are a few things to be said about subtraction, division and powers. -/ instance : decidable_eq ℕ+ := λ (a b : ℕ+), by apply_instance instance : linear_order ℕ+ := subtype.linear_order _ @[simp] lemma mk_le_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) ≤ ⟨k, hk⟩ ↔ n ≤ k := iff.rfl @[simp] lemma mk_lt_mk (n k : ℕ) (hn : 0 < n) (hk : 0 < k) : (⟨n, hn⟩ : ℕ+) < ⟨k, hk⟩ ↔ n < k := iff.rfl @[simp, norm_cast] lemma coe_le_coe (n k : ℕ+) : (n:ℕ) ≤ k ↔ n ≤ k := iff.rfl @[simp, norm_cast] lemma coe_lt_coe (n k : ℕ+) : (n:ℕ) < k ↔ n < k := iff.rfl @[simp] theorem pos (n : ℕ+) : 0 < (n : ℕ) := n.2 theorem eq {m n : ℕ+} : (m : ℕ) = n → m = n := subtype.eq @[simp] lemma coe_inj {m n : ℕ+} : (m : ℕ) = n ↔ m = n := set_coe.ext_iff @[simp] theorem mk_coe (n h) : ((⟨n, h⟩ : ℕ+) : ℕ) = n := rfl instance : add_comm_semigroup ℕ+ := { add := λ a b, ⟨(a + b : ℕ), add_pos a.pos b.pos⟩, add_comm := λ a b, subtype.eq (add_comm a b), add_assoc := λ a b c, subtype.eq (add_assoc a b c) } @[simp] theorem add_coe (m n : ℕ+) : ((m + n : ℕ+) : ℕ) = m + n := rfl instance coe_add_hom : is_add_hom (coe : ℕ+ → ℕ) := ⟨add_coe⟩ instance : add_left_cancel_semigroup ℕ+ := { add_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_right_inj (a : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } instance : add_right_cancel_semigroup ℕ+ := { add_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, rw [add_coe, add_coe] at h, exact eq ((add_left_inj (b : ℕ)).mp h)}, .. (pnat.add_comm_semigroup) } @[simp] theorem ne_zero (n : ℕ+) : (n : ℕ) ≠ 0 := ne_of_gt n.2 theorem to_pnat'_coe {n : ℕ} : 0 < n → (n.to_pnat' : ℕ) = n := succ_pred_eq_of_pos @[simp] theorem coe_to_pnat' (n : ℕ+) : (n : ℕ).to_pnat' = n := eq (to_pnat'_coe n.pos) instance : comm_monoid ℕ+ := { mul := λ m n, ⟨m.1 * n.1, mul_pos m.2 n.2⟩, mul_assoc := λ a b c, subtype.eq (mul_assoc _ _ _), one := succ_pnat 0, one_mul := λ a, subtype.eq (one_mul _), mul_one := λ a, subtype.eq (mul_one _), mul_comm := λ a b, subtype.eq (mul_comm _ _) } theorem lt_add_one_iff : ∀ {a b : ℕ+}, a < b + 1 ↔ a ≤ b := λ a b, nat.lt_add_one_iff theorem add_one_le_iff : ∀ {a b : ℕ+}, a + 1 ≤ b ↔ a < b := λ a b, nat.add_one_le_iff @[simp] lemma one_le (n : ℕ+) : (1 : ℕ+) ≤ n := n.2 instance : order_bot ℕ+ := { bot := 1, bot_le := λ a, a.property, ..(by apply_instance : partial_order ℕ+) } @[simp] lemma bot_eq_zero : (⊥ : ℕ+) = 1 := rfl instance : inhabited ℕ+ := ⟨1⟩ -- Some lemmas that rewrite `pnat.mk n h`, for `n` an explicit numeral, into explicit numerals. @[simp] lemma mk_one {h} : (⟨1, h⟩ : ℕ+) = (1 : ℕ+) := rfl @[simp] lemma mk_bit0 (n) {h} : (⟨bit0 n, h⟩ : ℕ+) = (bit0 ⟨n, pos_of_bit0_pos h⟩ : ℕ+) := rfl @[simp] lemma mk_bit1 (n) {h} {k} : (⟨bit1 n, h⟩ : ℕ+) = (bit1 ⟨n, k⟩ : ℕ+) := rfl -- Some lemmas that rewrite inequalities between explicit numerals in `pnat` -- into the corresponding inequalities in `nat`. -- TODO: perhaps this should not be attempted by `simp`, -- and instead we should expect `norm_num` to take care of these directly? -- TODO: these lemmas are perhaps incomplete: -- * 1 is not represented as a bit0 or bit1 -- * strict inequalities? @[simp] lemma bit0_le_bit0 (n m : ℕ+) : (bit0 n) ≤ (bit0 m) ↔ (bit0 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit0_le_bit1 (n m : ℕ+) : (bit0 n) ≤ (bit1 m) ↔ (bit0 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit0 (n m : ℕ+) : (bit1 n) ≤ (bit0 m) ↔ (bit1 (n : ℕ)) ≤ (bit0 (m : ℕ)) := iff.rfl @[simp] lemma bit1_le_bit1 (n m : ℕ+) : (bit1 n) ≤ (bit1 m) ↔ (bit1 (n : ℕ)) ≤ (bit1 (m : ℕ)) := iff.rfl @[simp] theorem one_coe : ((1 : ℕ+) : ℕ) = 1 := rfl @[simp] theorem mul_coe (m n : ℕ+) : ((m * n : ℕ+) : ℕ) = m * n := rfl instance coe_mul_hom : is_monoid_hom (coe : ℕ+ → ℕ) := {map_one := one_coe, map_mul := mul_coe} @[simp] lemma coe_eq_one_iff {m : ℕ+} : (m : ℕ) = 1 ↔ m = 1 := by { split; intro h; try { apply pnat.eq}; rw h; simp } @[simp] lemma coe_bit0 (a : ℕ+) : ((bit0 a : ℕ+) : ℕ) = bit0 (a : ℕ) := rfl @[simp] lemma coe_bit1 (a : ℕ+) : ((bit1 a : ℕ+) : ℕ) = bit1 (a : ℕ) := rfl @[simp] theorem pow_coe (m : ℕ+) (n : ℕ) : ((m ^ n : ℕ+) : ℕ) = (m : ℕ) ^ n := by induction n with n ih; [refl, rw [pow_succ', pow_succ, mul_coe, mul_comm, ih]] instance : left_cancel_semigroup ℕ+ := { mul_left_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_right_inj a.pos).mp h)}, .. (pnat.comm_monoid) } instance : right_cancel_semigroup ℕ+ := { mul_right_cancel := λ a b c h, by { replace h := congr_arg (coe : ℕ+ → ℕ) h, exact eq ((nat.mul_left_inj b.pos).mp h)}, .. (pnat.comm_monoid) } instance : ordered_cancel_comm_monoid ℕ+ := { mul_le_mul_left := by { intros, apply nat.mul_le_mul_left, assumption }, le_of_mul_le_mul_left := by { intros a b c h, apply nat.le_of_mul_le_mul_left h a.property, }, .. (pnat.left_cancel_semigroup), .. (pnat.right_cancel_semigroup), .. (pnat.linear_order), .. (pnat.comm_monoid)} instance : distrib ℕ+ := { left_distrib := λ a b c, eq (mul_add a b c), right_distrib := λ a b c, eq (add_mul a b c), ..(pnat.add_comm_semigroup), ..(pnat.comm_monoid) } /-- Subtraction a - b is defined in the obvious way when a > b, and by a - b = 1 if a ≤ b. -/ instance : has_sub ℕ+ := ⟨λ a b, to_pnat' (a - b : ℕ)⟩ theorem sub_coe (a b : ℕ+) : ((a - b : ℕ+) : ℕ) = ite (b < a) (a - b : ℕ) 1 := begin change ((to_pnat' ((a : ℕ) - (b : ℕ)) : ℕ)) = ite ((a : ℕ) > (b : ℕ)) ((a : ℕ) - (b : ℕ)) 1, split_ifs with h, { exact to_pnat'_coe (nat.sub_pos_of_lt h) }, { rw [nat.sub_eq_zero_iff_le.mpr (le_of_not_gt h)], refl } end theorem add_sub_of_lt {a b : ℕ+} : a < b → a + (b - a) = b := λ h, eq $ by { rw [add_coe, sub_coe, if_pos h], exact nat.add_sub_of_le (le_of_lt h) } instance : has_well_founded ℕ+ := ⟨(<), measure_wf coe⟩ /-- Strong induction on `pnat`. -/ lemma strong_induction_on {p : pnat → Prop} : ∀ (n : pnat) (h : ∀ k, (∀ m, m < k → p m) → p k), p n | n := λ IH, IH _ (λ a h, strong_induction_on a IH) using_well_founded { dec_tac := `[assumption] } /-- If `(n : pnat)` is different from `1`, then it is the successor of some `(k : pnat)`. -/ lemma exists_eq_succ_of_ne_one : ∀ {n : pnat} (h1 : n ≠ 1), ∃ (k : pnat), n = k + 1 | ⟨1, _⟩ h1 := false.elim $ h1 rfl | ⟨n+2, _⟩ _ := ⟨⟨n+1, by simp⟩, rfl⟩ lemma case_strong_induction_on {p : pnat → Prop} (a : pnat) (hz : p 1) (hi : ∀ n, (∀ m, m ≤ n → p m) → p (n + 1)) : p a := begin apply strong_induction_on a, intros k hk, by_cases h1 : k = 1, { rwa h1 }, obtain ⟨b, rfl⟩ := exists_eq_succ_of_ne_one h1, simp only [lt_add_one_iff] at hk, exact hi b hk end /-- An induction principle for `pnat`: it takes values in `Sort*`, so it applies also to Types, not only to `Prop`. -/ @[elab_as_eliminator] def rec_on (n : pnat) {p : pnat → Sort*} (p1 : p 1) (hp : ∀ n, p n → p (n + 1)) : p n := begin rcases n with ⟨n, h⟩, induction n with n IH, { exact absurd h dec_trivial }, { cases n with n, { exact p1 }, { exact hp _ (IH n.succ_pos) } } end @[simp] theorem rec_on_one {p} (p1 hp) : @pnat.rec_on 1 p p1 hp = p1 := rfl @[simp] theorem rec_on_succ (n : pnat) {p : pnat → Sort*} (p1 hp) : @pnat.rec_on (n + 1) p p1 hp = hp n (@pnat.rec_on n p p1 hp) := by { cases n with n h, cases n; [exact absurd h dec_trivial, refl] } /-- We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div_aux : ℕ+ → ℕ → ℕ → ℕ+ × ℕ | k 0 q := ⟨k, q.pred⟩ | k (r + 1) q := ⟨⟨r + 1, nat.succ_pos r⟩, q⟩ lemma mod_div_aux_spec : ∀ (k : ℕ+) (r q : ℕ) (h : ¬ (r = 0 ∧ q = 0)), (((mod_div_aux k r q).1 : ℕ) + k * (mod_div_aux k r q).2 = (r + k * q)) | k 0 0 h := (h ⟨rfl, rfl⟩).elim | k 0 (q + 1) h := by { change (k : ℕ) + (k : ℕ) * (q + 1).pred = 0 + (k : ℕ) * (q + 1), rw [nat.pred_succ, nat.mul_succ, zero_add, add_comm]} | k (r + 1) q h := rfl /-- `mod_div m k = (m % k, m / k)`. We define `m % k` and `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` and `m / k = n - 1`. This ensures that `m % k` is always positive and `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def mod_div (m k : ℕ+) : ℕ+ × ℕ := mod_div_aux k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) /-- We define `m % k` in the same way as for `ℕ` except that when `m = n * k` we take `m % k = k` This ensures that `m % k` is always positive. -/ def mod (m k : ℕ+) : ℕ+ := (mod_div m k).1 /-- We define `m / k` in the same way as for `ℕ` except that when `m = n * k` we take `m / k = n - 1`. This ensures that `m = (m % k) + k * (m / k)` in all cases. Later we define a function `div_exact` which gives the usual `m / k` in the case where `k` divides `m`. -/ def div (m k : ℕ+) : ℕ := (mod_div m k).2 theorem mod_add_div (m k : ℕ+) : ((mod m k) + k * (div m k) : ℕ) = m := begin let h₀ := nat.mod_add_div (m : ℕ) (k : ℕ), have : ¬ ((m : ℕ) % (k : ℕ) = 0 ∧ (m : ℕ) / (k : ℕ) = 0), by { rintro ⟨hr, hq⟩, rw [hr, hq, mul_zero, zero_add] at h₀, exact (m.ne_zero h₀.symm).elim }, have := mod_div_aux_spec k ((m : ℕ) % (k : ℕ)) ((m : ℕ) / (k : ℕ)) this, exact (this.trans h₀), end theorem div_add_mod (m k : ℕ+) : (k * (div m k) + mod m k : ℕ) = m := (add_comm _ _).trans (mod_add_div _ _) lemma mod_add_div' (m k : ℕ+) : ((mod m k) + (div m k) * k : ℕ) = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : ℕ+) : ((div m k) * k + mod m k : ℕ) = m := by { rw mul_comm, exact div_add_mod _ _ } theorem mod_coe (m k : ℕ+) : ((mod m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) (k : ℕ) ((m : ℕ) % (k : ℕ)) := begin dsimp [mod, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem div_coe (m k : ℕ+) : ((div m k) : ℕ) = ite ((m : ℕ) % (k : ℕ) = 0) ((m : ℕ) / (k : ℕ)).pred ((m : ℕ) / (k : ℕ)) := begin dsimp [div, mod_div], cases (m : ℕ) % (k : ℕ), { rw [if_pos rfl], refl }, { rw [if_neg n.succ_ne_zero], refl } end theorem mod_le (m k : ℕ+) : mod m k ≤ m ∧ mod m k ≤ k := begin change ((mod m k) : ℕ) ≤ (m : ℕ) ∧ ((mod m k) : ℕ) ≤ (k : ℕ), rw [mod_coe], split_ifs, { have hm : (m : ℕ) > 0 := m.pos, rw [← nat.mod_add_div (m : ℕ) (k : ℕ), h, zero_add] at hm ⊢, by_cases h' : ((m : ℕ) / (k : ℕ)) = 0, { rw [h', mul_zero] at hm, exact (lt_irrefl _ hm).elim}, { let h' := nat.mul_le_mul_left (k : ℕ) (nat.succ_le_of_lt (nat.pos_of_ne_zero h')), rw [mul_one] at h', exact ⟨h', le_refl (k : ℕ)⟩ } }, { exact ⟨nat.mod_le (m : ℕ) (k : ℕ), le_of_lt (nat.mod_lt (m : ℕ) k.pos)⟩ } end theorem dvd_iff {k m : ℕ+} : k ∣ m ↔ (k : ℕ) ∣ (m : ℕ) := begin split; intro h, rcases h with ⟨_, rfl⟩, apply dvd_mul_right, rcases h with ⟨a, h⟩, cases a, { contrapose h, apply ne_zero, }, use a.succ, apply nat.succ_pos, rw [← coe_inj, h, mul_coe, mk_coe], end theorem dvd_iff' {k m : ℕ+} : k ∣ m ↔ mod m k = k := begin rw dvd_iff, rw [nat.dvd_iff_mod_eq_zero], split, { intro h, apply eq, rw [mod_coe, if_pos h] }, { intro h, by_cases h' : (m : ℕ) % (k : ℕ) = 0, { exact h'}, { replace h : ((mod m k) : ℕ) = (k : ℕ) := congr_arg _ h, rw [mod_coe, if_neg h'] at h, exact (ne_of_lt (nat.mod_lt (m : ℕ) k.pos) h).elim } } end lemma le_of_dvd {m n : ℕ+} : m ∣ n → m ≤ n := by { rw dvd_iff', intro h, rw ← h, apply (mod_le n m).left } /-- If `h : k | m`, then `k * (div_exact m k) = m`. Note that this is not equal to `m / k`. -/ def div_exact (m k : ℕ+) : ℕ+ := ⟨(div m k).succ, nat.succ_pos _⟩ theorem mul_div_exact {m k : ℕ+} (h : k ∣ m) : k * (div_exact m k) = m := begin apply eq, rw [mul_coe], change (k : ℕ) * (div m k).succ = m, rw [← div_add_mod m k, dvd_iff'.mp h, nat.mul_succ] end theorem dvd_antisymm {m n : ℕ+} : m ∣ n → n ∣ m → m = n := λ hmn hnm, le_antisymm (le_of_dvd hmn) (le_of_dvd hnm) theorem dvd_one_iff (n : ℕ+) : n ∣ 1 ↔ n = 1 := ⟨λ h, dvd_antisymm h (one_dvd n), λ h, h.symm ▸ (dvd_refl 1)⟩ lemma pos_of_div_pos {n : ℕ+} {a : ℕ} (h : a ∣ n) : 0 < a := begin apply pos_iff_ne_zero.2, intro hzero, rw hzero at h, exact pnat.ne_zero n (eq_zero_of_zero_dvd h) end end pnat section can_lift instance nat.can_lift_pnat : can_lift ℕ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' n, pnat.to_pnat'_coe hn⟩⟩ instance int.can_lift_pnat : can_lift ℤ ℕ+ := ⟨coe, λ n, 0 < n, λ n hn, ⟨nat.to_pnat' (int.nat_abs n), by rw [coe_coe, nat.to_pnat'_coe, if_pos (int.nat_abs_pos_of_ne_zero (ne_of_gt hn)), int.nat_abs_of_nonneg hn.le]⟩⟩ end can_lift
a2c76909546593af2c2430d016a72ee0f8a47400
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Elab/Tactic/Conv.lean
42feba3db7387e32fb9745c7fdda227e74ecab72
[ "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
413
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.Tactic.Conv.Basic import Lean.Elab.Tactic.Conv.Congr import Lean.Elab.Tactic.Conv.Rewrite import Lean.Elab.Tactic.Conv.Change import Lean.Elab.Tactic.Conv.Simp import Lean.Elab.Tactic.Conv.Pattern import Lean.Elab.Tactic.Conv.Delta
72c6ccfa55f65076a007c1c3ffd646041f03f410
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/hott/equiv.lean
01400a871e520a7bd2dfc2177c9e984fa6c342a9
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,980
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad, Jakob von Raumer -- Ported from Coq HoTT import .path open path function -- Equivalences -- ------------ definition Sect {A B : Type} (s : A → B) (r : B → A) := Πx : A, r (s x) ≈ x -- -- TODO: need better means of declaring structures -- -- TODO: note that Coq allows projections to be declared to be coercions on the fly -- Structure IsEquiv inductive IsEquiv [class] {A B : Type} (f : A → B) := mk : Π (inv : B → A) (retr : Sect inv f) (sect : Sect f inv) (adj : Πx, retr (f x) ≈ ap f (sect x)), IsEquiv f namespace IsEquiv definition inv {A B : Type} (f : A → B) [H : IsEquiv f] : B → A := IsEquiv.rec (λinv retr sect adj, inv) H -- TODO: note: does not type check without giving the type definition retr {A B : Type} (f : A → B) [H : IsEquiv f] : Sect (inv f) f := IsEquiv.rec (λinv retr sect adj, retr) H definition sect {A B : Type} (f : A → B) [H : IsEquiv f] : Sect f (inv f) := IsEquiv.rec (λinv retr sect adj, sect) H definition adj {A B : Type} (f : A → B) [H : IsEquiv f] : Πx, retr f (f x) ≈ ap f (sect f x) := IsEquiv.rec (λinv retr sect adj, adj) H postfix `⁻¹` := inv end IsEquiv -- Structure Equiv inductive Equiv (A B : Type) : Type := mk : Π (equiv_fun : A → B) (equiv_isequiv : IsEquiv equiv_fun), Equiv A B namespace Equiv --Note: No coercion here definition equiv_fun {A B : Type} (e : Equiv A B) : A → B := Equiv.rec (λequiv_fun equiv_isequiv, equiv_fun) e definition equiv_isequiv [instance] {A B : Type} (e : Equiv A B) : IsEquiv (equiv_fun e) := Equiv.rec (λequiv_fun equiv_isequiv, equiv_isequiv) e infix `≃`:25 := Equiv end Equiv -- Some instances and closure properties of equivalences namespace IsEquiv variables {A B C : Type} {f : A → B} {g : B → C} {f' : A → B} -- The identity function is an equivalence. definition id_closed [instance] : (@IsEquiv A A id) := IsEquiv.mk id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition comp_closed [instance] (Hf : IsEquiv f) (Hg : IsEquiv g) : (IsEquiv (g ∘ f)) := IsEquiv.mk ((inv f) ∘ (inv g)) (λc, ap g (retr f (g⁻¹ c)) ⬝ retr g c) (λa, ap (inv f) (sect g (f a)) ⬝ sect f a) (λa, (whiskerL _ (adj g (f a))) ⬝ (ap_pp g _ _)⁻¹ ⬝ ap02 g (concat_A1p (retr f) (sect g (f a))⁻¹ ⬝ (ap_compose (inv f) f _ ◾ adj f a) ⬝ (ap_pp f _ _)⁻¹ ) ⬝ (ap_compose f g _)⁻¹ ) -- Any function equal to an equivalence is an equivlance as well. definition path_closed (Hf : IsEquiv f) (Heq : f ≈ f') : (IsEquiv f') := path.rec_on Heq Hf -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopic (Hf : IsEquiv f) (Heq : f ∼ f') : (IsEquiv f') := let sect' := (λ b, (Heq (inv f b))⁻¹ ⬝ retr f b) in let retr' := (λ a, (ap (inv f) (Heq a))⁻¹ ⬝ sect f a) in let adj' := (λ (a : A), let ff'a := Heq a in let invf := inv f in let secta := sect f a in let retrfa := retr f (f a) in let retrf'a := retr f (f' a) in have eq1 : _ ≈ _, from calc ap f secta ⬝ ff'a ≈ retrfa ⬝ ff'a : (ap _ (adj f _ ))⁻¹ ... ≈ ap (f ∘ invf) ff'a ⬝ retrf'a : !concat_A1p⁻¹ ... ≈ ap f (ap invf ff'a) ⬝ retr f (f' a) : {ap_compose invf f _}, have eq2 : _ ≈ _, from calc retrf'a ≈ (ap f (ap invf ff'a))⁻¹ ⬝ (ap f secta ⬝ ff'a) : moveL_Vp _ _ _ (eq1⁻¹) ... ≈ ap f (ap invf ff'a)⁻¹ ⬝ (ap f secta ⬝ Heq a) : {ap_V invf ff'a} ... ≈ ap f (ap invf ff'a)⁻¹ ⬝ (Heq (invf (f a)) ⬝ ap f' secta) : {!concat_Ap} ... ≈ (ap f (ap invf ff'a)⁻¹ ⬝ Heq (invf (f a))) ⬝ ap f' secta : {!concat_pp_p⁻¹} ... ≈ (ap f ((ap invf ff'a)⁻¹) ⬝ Heq (invf (f a))) ⬝ ap f' secta : {!ap_V⁻¹} ... ≈ (Heq (invf (f' a)) ⬝ ap f' ((ap invf ff'a)⁻¹)) ⬝ ap f' secta : {!concat_Ap} ... ≈ (Heq (invf (f' a)) ⬝ (ap f' (ap invf ff'a))⁻¹) ⬝ ap f' secta : {!ap_V} ... ≈ Heq (invf (f' a)) ⬝ ((ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta) : !concat_pp_p, have eq3 : _ ≈ _, from calc (Heq (invf (f' a)))⁻¹ ⬝ retr f (f' a) ≈ (ap f' (ap invf ff'a))⁻¹ ⬝ ap f' secta : moveR_Vp _ _ _ eq2 ... ≈ (ap f' ((ap invf ff'a)⁻¹)) ⬝ ap f' secta : {!ap_V⁻¹} ... ≈ ap f' ((ap invf ff'a)⁻¹ ⬝ secta) : !ap_pp⁻¹, eq3) in IsEquiv.mk (inv f) sect' retr' adj' end IsEquiv namespace IsEquiv variables {A B : Type} (f : A → B) (g : B → A) (ret : Sect g f) (sec : Sect f g) context set_option unifier.max_steps 30000 --To construct an equivalence it suffices to state the proof that the inverse is a quasi-inverse. definition adjointify : IsEquiv f := let sect' := (λx, ap g (ap f (inverse (sec x))) ⬝ ap g (ret (f x)) ⬝ sec x) in let adj' := (λ (a : A), let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f ((sec a)⁻¹))) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) ≈ _, from calc ap f (sec a) ≈ idp ⬝ ap f (sec a) : !concat_1p⁻¹ ... ≈ (ret (f a) ⬝ (ret (f a)⁻¹)) ⬝ ap f (sec a) : {!concat_pV⁻¹} ... ≈ ((ret (fgfa))⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : {!concat_pA1⁻¹} ... ≈ ((ret (fgfa))⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : {ap_compose g f _} ... ≈ (ret (fgfa))⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : !concat_pp_p, have eq2 : ap f (sec a) ⬝ idp ≈ (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !concat_p1 ⬝ eq1, have eq3 : idp ≈ _, from calc idp ≈ (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : moveL_Vp _ _ _ eq2 ... ≈ (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : !concat_p_pp ... ≈ (ap f ((sec a)⁻¹) ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : {!ap_V⁻¹} ... ≈ ((ap f ((sec a)⁻¹) ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : !concat_p_pp ... ≈ ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f ((sec a)⁻¹))) ⬝ fgretrfa) ⬝ ap f (sec a) : {!concat_pA1⁻¹} ... ≈ ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : {ap_compose g f _} ... ≈ (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : {!concat_p_pp⁻¹} ... ≈ retrfa⁻¹ ⬝ ap f (ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : {!ap_pp⁻¹} ... ≈ retrfa⁻¹ ⬝ (ap f (ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : !concat_p_pp⁻¹ ... ≈ retrfa⁻¹ ⬝ ap f ((ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ sec a) : {!ap_pp⁻¹}, have eq4 : ret (f a) ≈ ap f ((ap g (ap f ((sec a)⁻¹)) ⬝ ap g (ret (f a))) ⬝ sec a), from moveR_M1 _ _ eq3, eq4) in IsEquiv.mk g ret sect' adj' end end IsEquiv namespace IsEquiv variables {A B: Type} (f : A → B) --The inverse of an equivalence is, again, an equivalence. definition inv_closed [instance] [Hf : IsEquiv f] : (IsEquiv (inv f)) := adjointify (inv f) f (sect f) (retr f) end IsEquiv namespace IsEquiv variables {A : Type} section variables {B C : Type} (f : A → B) {f' : A → B} [Hf : IsEquiv f] include Hf definition cancel_R (g : B → C) [Hgf : IsEquiv (g ∘ f)] : (IsEquiv g) := homotopic (comp_closed !inv_closed Hgf) (λb, ap g (retr f b)) definition cancel_L (g : C → A) [Hgf : IsEquiv (f ∘ g)] : (IsEquiv g) := homotopic (comp_closed Hgf !inv_closed) (λa, sect f (g a)) --Rewrite rules definition moveR_M {x : A} {y : B} (p : x ≈ (inv f) y) : (f x ≈ y) := (ap f p) ⬝ (retr f y) definition moveL_M {x : A} {y : B} (p : (inv f) y ≈ x) : (y ≈ f x) := (moveR_M f (p⁻¹))⁻¹ definition moveR_V {x : B} {y : A} (p : x ≈ f y) : (inv f) x ≈ y := ap (inv f) p ⬝ sect f y definition moveL_V {x : B} {y : A} (p : f y ≈ x) : y ≈ (inv f) x := (moveR_V f (p⁻¹))⁻¹ definition ap_closed [instance] (x y : A) : IsEquiv (ap f) := adjointify (ap f) (λq, (inverse (sect f x)) ⬝ ap (f⁻¹) q ⬝ sect f y) (λq, !ap_pp ⬝ whiskerR !ap_pp _ ⬝ ((!ap_V ⬝ inverse2 ((adj f _)⁻¹)) ◾ (inverse (ap_compose (f⁻¹) f _)) ◾ (adj f _)⁻¹) ⬝ concat_pA1_p (retr f) _ _ ⬝ whiskerR !concat_Vp _ ⬝ !concat_1p) (λp, whiskerR (whiskerL _ ((ap_compose f (f⁻¹) _)⁻¹)) _ ⬝ concat_pA1_p (sect f) _ _ ⬝ whiskerR !concat_Vp _ ⬝ !concat_1p) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition equiv_rect (P : B -> Type) : (Πx, P (f x)) → (Πy, P y) := (λg y, path.transport _ (retr f y) (g (f⁻¹ y))) definition equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) ≈ df x := let eq1 := (apD df (sect f x)) in calc equiv_rect f P df (f x) ≈ transport P (retr f (f x)) (df (f⁻¹ (f x))) : idp ... ≈ transport P (ap f (sect f x)) (df (f⁻¹ (f x))) : adj f ... ≈ transport (P ∘ f) (sect f x) (df (f⁻¹ (f x))) : transport_compose ... ≈ df x : eq1 end --Transporting is an equivalence protected definition transport [instance] (P : A → Type) {x y : A} (p : x ≈ y) : (IsEquiv (transport P p)) := IsEquiv.mk (transport P (p⁻¹)) (transport_pV P p) (transport_Vp P p) (transport_pVp P p) end IsEquiv namespace Equiv context parameters {A B C : Type} (eqf : A ≃ B) private definition f : A → B := equiv_fun eqf private definition Hf : IsEquiv f := equiv_isequiv eqf protected definition id : A ≃ A := Equiv.mk id IsEquiv.id_closed protected theorem compose (eqg: B ≃ C) : A ≃ C := Equiv.mk ((equiv_fun eqg) ∘ f) (IsEquiv.comp_closed Hf (equiv_isequiv eqg)) theorem path_closed (f' : A → B) (Heq : equiv_fun eqf ≈ f') : A ≃ B := Equiv.mk f' (IsEquiv.path_closed Hf Heq) theorem inv_closed : B ≃ A := Equiv.mk (IsEquiv.inv f) !IsEquiv.inv_closed theorem cancel_R {g : B → C} (Hgf : IsEquiv (g ∘ f)) : B ≃ C := Equiv.mk g (IsEquiv.cancel_R f _) theorem cancel_L {g : C → A} (Hgf : IsEquiv (f ∘ g)) : C ≃ A := Equiv.mk g (IsEquiv.cancel_L f _) protected theorem transport (P : A → Type) {x y : A} {p : x ≈ y} : (P x) ≃ (P y) := Equiv.mk (transport P p) (IsEquiv.transport P p) end context parameters {A B : Type} (eqf eqg : A ≃ B) private definition Hf [instance] : IsEquiv (equiv_fun eqf) := equiv_isequiv eqf private definition Hg [instance] : IsEquiv (equiv_fun eqg) := equiv_isequiv eqg theorem inv_eq (p : eqf ≈ eqg) : IsEquiv.inv (equiv_fun eqf) ≈ IsEquiv.inv (equiv_fun eqg) := path.rec_on p idp end -- calc enviroment -- Note: Calculating with substitutions needs univalence calc_trans compose calc_refl id calc_symm inv_closed end Equiv
b4cd98ffee5f3fab320b9aa6f9884e4b30b31fe9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/lint/type_classes.lean
23f96c4a8e5883ef79ad878b5e26211911a92bca
[]
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
2,485
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.lint.basic import Mathlib.PostPort namespace Mathlib /-! # Linters about type classes This file defines several linters checking the correct usage of type classes and the appropriate definition of instances: * `instance_priority` ensures that blanket instances have low priority * `has_inhabited_instances` checks that every type has an `inhabited` instance * `impossible_instance` checks that there are no instances which can never apply * `incorrect_type_class_argument` checks that only type classes are used in instance-implicit arguments * `dangerous_instance` checks for instances that generate subproblems with metavariables * `fails_quickly` checks that type class resolution finishes quickly * `has_coe_variable` checks that there is no instance of type `has_coe α t` * `inhabited_nonempty` checks whether `[inhabited α]` arguments could be generalized to `[nonempty α]` * `decidable_classical` checks propositions for `[decidable_... p]` hypotheses that are not used in the statement, and could thus be removed by using `classical` in the proof. * `linter.has_coe_to_fun` checks whether necessary `has_coe_to_fun` instances are declared -/ /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ /-- checks whether an instance that always applies has priority ≥ 1000. -/ /-- There are places where typeclass arguments are specified with implicit `{}` brackets instead of the usual `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type of one of the other arguments. When they can be inferred from these other arguments, it is faster to use this method than to use type class inference. For example, when writing lemmas about `(f : α →+* β)`, it is faster to specify the fact that `α` and `β` are `semiring`s as `{rα : semiring α} {rβ : semiring β}` rather than the usual `[semiring α] [semiring β]`. -/ /-- Certain instances always apply during type-class resolution. For example, the instance
898e890f711c219aca3f19451684c1c72c9dd7e6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/sequences.lean
e2366013b5186f87001aa2b9bc5f72b1b2b53982
[ "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
18,814
lean
/- Copyright (c) 2018 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Patrick Massot -/ import topology.bases import topology.subset_properties import topology.metric_space.basic /-! # Sequences in topological spaces In this file we define sequences in topological spaces and show how they are related to filters and the topology. In particular, we * define the sequential closure of a set and prove that it's contained in the closure, * define a type class "sequential_space" in which closure and sequential closure agree, * define sequential continuity and show that it coincides with continuity in sequential spaces, * provide an instance that shows that every first-countable (and in particular metric) space is a sequential space. * define sequential compactness, prove that compactness implies sequential compactness in first countable spaces, and prove they are equivalent for uniform spaces having a countable uniformity basis (in particular metric spaces). -/ open set filter open_locale topological_space variables {α : Type*} {β : Type*} local notation f ` ⟶ ` limit := tendsto f at_top (𝓝 limit) /-! ### Sequential closures, sequential continuity, and sequential spaces. -/ section topological_space variables [topological_space α] [topological_space β] /-- A sequence converges in the sence of topological spaces iff the associated statement for filter holds. -/ lemma topological_space.seq_tendsto_iff {x : ℕ → α} {limit : α} : tendsto x at_top (𝓝 limit) ↔ ∀ U : set α, limit ∈ U → is_open U → ∃ N, ∀ n ≥ N, (x n) ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens limit)).trans $ by simp only [and_imp, exists_prop, true_and, set.mem_Ici, ge_iff_le, id] /-- The sequential closure of a subset M ⊆ α of a topological space α is the set of all p ∈ α which arise as limit of sequences in M. -/ def sequential_closure (M : set α) : set α := {p | ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ M) ∧ (x ⟶ p)} lemma subset_sequential_closure (M : set α) : M ⊆ sequential_closure M := assume p (_ : p ∈ M), show p ∈ sequential_closure M, from ⟨λ n, p, assume n, ‹p ∈ M›, tendsto_const_nhds⟩ /-- A set `s` is sequentially closed if for any converging sequence `x n` of elements of `s`, the limit belongs to `s` as well. -/ def is_seq_closed (s : set α) : Prop := s = sequential_closure s /-- A convenience lemma for showing that a set is sequentially closed. -/ lemma is_seq_closed_of_def {A : set α} (h : ∀(x : ℕ → α) (p : α), (∀ n : ℕ, x n ∈ A) → (x ⟶ p) → p ∈ A) : is_seq_closed A := show A = sequential_closure A, from subset.antisymm (subset_sequential_closure A) (show ∀ p, p ∈ sequential_closure A → p ∈ A, from (assume p ⟨x, _, _⟩, show p ∈ A, from h x p ‹∀ n : ℕ, ((x n) ∈ A)› ‹(x ⟶ p)›)) /-- The sequential closure of a set is contained in the closure of that set. The converse is not true. -/ lemma sequential_closure_subset_closure (M : set α) : sequential_closure M ⊆ closure M := assume p ⟨x, xM, xp⟩, mem_closure_of_tendsto xp (univ_mem_sets' xM) /-- A set is sequentially closed if it is closed. -/ lemma is_seq_closed_of_is_closed (M : set α) (_ : is_closed M) : is_seq_closed M := suffices sequential_closure M ⊆ M, from set.eq_of_subset_of_subset (subset_sequential_closure M) this, calc sequential_closure M ⊆ closure M : sequential_closure_subset_closure M ... = M : is_closed.closure_eq ‹is_closed M› /-- The limit of a convergent sequence in a sequentially closed set is in that set.-/ lemma mem_of_is_seq_closed {A : set α} (_ : is_seq_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : (x ⟶ limit)) : limit ∈ A := have limit ∈ sequential_closure A, from show ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ A) ∧ (x ⟶ limit), from ⟨x, ‹∀ n, x n ∈ A›, ‹(x ⟶ limit)›⟩, eq.subst (eq.symm ‹is_seq_closed A›) ‹limit ∈ sequential_closure A› /-- The limit of a convergent sequence in a closed set is in that set.-/ lemma mem_of_is_closed_sequential {A : set α} (_ : is_closed A) {x : ℕ → α} (_ : ∀ n, x n ∈ A) {limit : α} (_ : x ⟶ limit) : limit ∈ A := mem_of_is_seq_closed (is_seq_closed_of_is_closed A ‹is_closed A›) ‹∀ n, x n ∈ A› ‹(x ⟶ limit)› /-- A sequential space is a space in which 'sequences are enough to probe the topology'. This can be formalised by demanding that the sequential closure and the closure coincide. The following statements show that other topological properties can be deduced from sequences in sequential spaces. -/ class sequential_space (α : Type*) [topological_space α] : Prop := (sequential_closure_eq_closure : ∀ M : set α, sequential_closure M = closure M) /-- In a sequential space, a set is closed iff it's sequentially closed. -/ lemma is_seq_closed_iff_is_closed [sequential_space α] {M : set α} : is_seq_closed M ↔ is_closed M := iff.intro (assume _, closure_eq_iff_is_closed.mp (eq.symm (calc M = sequential_closure M : by assumption ... = closure M : sequential_space.sequential_closure_eq_closure M))) (is_seq_closed_of_is_closed M) /-- In a sequential space, a point belongs to the closure of a set iff it is a limit of a sequence taking values in this set. -/ lemma mem_closure_iff_seq_limit [sequential_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∃ x : ℕ → α, (∀ n : ℕ, x n ∈ s) ∧ (x ⟶ a) := by { rw ← sequential_space.sequential_closure_eq_closure, exact iff.rfl } /-- A function between topological spaces is sequentially continuous if it commutes with limit of convergent sequences. -/ def sequentially_continuous (f : α → β) : Prop := ∀ (x : ℕ → α), ∀ {limit : α}, (x ⟶ limit) → (f∘x ⟶ f limit) /- A continuous function is sequentially continuous. -/ lemma continuous.to_sequentially_continuous {f : α → β} (_ : continuous f) : sequentially_continuous f := assume x limit (_ : x ⟶ limit), have tendsto f (𝓝 limit) (𝓝 (f limit)), from continuous.tendsto ‹continuous f› limit, show (f ∘ x) ⟶ (f limit), from tendsto.comp this ‹(x ⟶ limit)› /-- In a sequential space, continuity and sequential continuity coincide. -/ lemma continuous_iff_sequentially_continuous {f : α → β} [sequential_space α] : continuous f ↔ sequentially_continuous f := iff.intro (assume _, ‹continuous f›.to_sequentially_continuous) (assume : sequentially_continuous f, show continuous f, from suffices h : ∀ {A : set β}, is_closed A → is_seq_closed (f ⁻¹' A), from continuous_iff_is_closed.mpr (assume A _, is_seq_closed_iff_is_closed.mp $ h ‹is_closed A›), assume A (_ : is_closed A), is_seq_closed_of_def $ assume (x : ℕ → α) p (_ : ∀ n, f (x n) ∈ A) (_ : x ⟶ p), have (f ∘ x) ⟶ (f p), from ‹sequentially_continuous f› x ‹(x ⟶ p)›, show f p ∈ A, from mem_of_is_closed_sequential ‹is_closed A› ‹∀ n, f (x n) ∈ A› ‹(f∘x ⟶ f p)›) end topological_space namespace topological_space namespace first_countable_topology variables [topological_space α] [first_countable_topology α] /-- Every first-countable space is sequential. -/ @[priority 100] -- see Note [lower instance priority] instance : sequential_space α := ⟨show ∀ M, sequential_closure M = closure M, from assume M, suffices closure M ⊆ sequential_closure M, from set.subset.antisymm (sequential_closure_subset_closure M) this, -- For every p ∈ closure M, we need to construct a sequence x in M that converges to p: assume (p : α) (hp : p ∈ closure M), -- Since we are in a first-countable space, the neighborhood filter around `p` has a decreasing -- basis `U` indexed by `ℕ`. let ⟨U, hU⟩ := (nhds_generated_countable p).exists_antimono_basis in -- Since `p ∈ closure M`, there is an element in each `M ∩ U i` have hp : ∀ (i : ℕ), ∃ (y : α), y ∈ M ∧ y ∈ U i, by simpa using (mem_closure_iff_nhds_basis hU.1).mp hp, begin -- The axiom of (countable) choice builds our sequence from the later fact choose u hu using hp, rw forall_and_distrib at hu, -- It clearly takes values in `M` use [u, hu.1], -- and converges to `p` because the basis is decreasing. apply hU.tendsto hu.2, end⟩ end first_countable_topology end topological_space section seq_compact open topological_space topological_space.first_countable_topology variables [topological_space α] /-- A set `s` is sequentially compact if every sequence taking values in `s` has a converging subsequence. -/ def is_seq_compact (s : set α) := ∀ ⦃u : ℕ → α⦄, (∀ n, u n ∈ s) → ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) /-- A space `α` is sequentially compact if every sequence in `α` has a converging subsequence. -/ class seq_compact_space (α : Type*) [topological_space α] : Prop := (seq_compact_univ : is_seq_compact (univ : set α)) lemma is_seq_compact.subseq_of_frequently_in {s : set α} (hs : is_seq_compact s) {u : ℕ → α} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨ψ, hψ, huψ⟩ := extraction_of_frequently_at_top hu, ⟨x, x_in, φ, hφ, h⟩ := hs huψ in ⟨x, x_in, ψ ∘ φ, hψ.comp hφ, h⟩ lemma seq_compact_space.tendsto_subseq [seq_compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := let ⟨x, _, φ, mono, h⟩ := seq_compact_space.seq_compact_univ (by simp : ∀ n, u n ∈ univ) in ⟨x, φ, mono, h⟩ section first_countable_topology variables [first_countable_topology α] open topological_space.first_countable_topology lemma is_compact.is_seq_compact {s : set α} (hs : is_compact s) : is_seq_compact s := λ u u_in, let ⟨x, x_in, hx⟩ := @hs (map u at_top) _ (le_principal_iff.mpr (univ_mem_sets' u_in : _)) in ⟨x, x_in, tendsto_subseq hx⟩ lemma is_compact.tendsto_subseq' {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact.subseq_of_frequently_in hu lemma is_compact.tendsto_subseq {s : set α} {u : ℕ → α} (hs : is_compact s) (hu : ∀ n, u n ∈ s) : ∃ (x ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := hs.is_seq_compact hu @[priority 100] -- see Note [lower instance priority] instance first_countable_topology.seq_compact_of_compact [compact_space α] : seq_compact_space α := ⟨compact_univ.is_seq_compact⟩ lemma compact_space.tendsto_subseq [compact_space α] (u : ℕ → α) : ∃ x (φ : ℕ → ℕ), strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 x) := seq_compact_space.tendsto_subseq u end first_countable_topology end seq_compact section uniform_space_seq_compact open_locale uniformity open uniform_space prod variables [uniform_space β] {s : set β} lemma lebesgue_number_lemma_seq {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) (hU : is_countably_generated (𝓤 β)) : ∃ V ∈ 𝓤 β, symmetric_rel V ∧ ∀ x ∈ s, ∃ i, ball x V ⊆ c i := begin classical, obtain ⟨V, hV, Vsymm⟩ : ∃ V : ℕ → set (β × β), (𝓤 β).has_antimono_basis (λ _, true) V ∧ ∀ n, swap ⁻¹' V n = V n, from uniform_space.has_seq_basis hU, clear hU, suffices : ∃ n, ∀ x ∈ s, ∃ i, ball x (V n) ⊆ c i, { cases this with n hn, exact ⟨V n, hV.to_has_basis.mem_of_mem trivial, Vsymm n, hn⟩ }, by_contradiction H, obtain ⟨x, x_in, hx⟩ : ∃ x : ℕ → β, (∀ n, x n ∈ s) ∧ ∀ n i, ¬ ball (x n) (V n) ⊆ c i, { push_neg at H, choose x hx using H, exact ⟨x, forall_and_distrib.mp hx⟩ }, clear H, obtain ⟨x₀, x₀_in, φ, φ_mono, hlim⟩ : ∃ (x₀ ∈ s) (φ : ℕ → ℕ), strict_mono φ ∧ (x ∘ φ ⟶ x₀), from hs x_in, clear hs, obtain ⟨i₀, x₀_in⟩ : ∃ i₀, x₀ ∈ c i₀, { rcases hc₂ x₀_in with ⟨_, ⟨i₀, rfl⟩, x₀_in_c⟩, exact ⟨i₀, x₀_in_c⟩ }, clear hc₂, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ball x₀ (V n₀) ⊆ c i₀, { rcases (nhds_basis_uniformity hV.to_has_basis).mem_iff.mp (is_open_iff_mem_nhds.mp (hc₁ i₀) _ x₀_in) with ⟨n₀, _, h⟩, use n₀, rwa ← ball_eq_of_symmetry (Vsymm n₀) at h }, clear hc₁, obtain ⟨W, W_in, hWW⟩ : ∃ W ∈ 𝓤 β, W ○ W ⊆ V n₀, from comp_mem_uniformity_sets (hV.to_has_basis.mem_of_mem trivial), obtain ⟨N, x_φ_N_in, hVNW⟩ : ∃ N, x (φ N) ∈ ball x₀ W ∧ V (φ N) ⊆ W, { obtain ⟨N₁, h₁⟩ : ∃ N₁, ∀ n ≥ N₁, x (φ n) ∈ ball x₀ W, from tendsto_at_top'.mp hlim _ (mem_nhds_left x₀ W_in), obtain ⟨N₂, h₂⟩ : ∃ N₂, V (φ N₂) ⊆ W, { rcases hV.to_has_basis.mem_iff.mp W_in with ⟨N, _, hN⟩, use N, exact subset.trans (hV.decreasing trivial trivial $ φ_mono.id_le _) hN }, have : φ N₂ ≤ φ (max N₁ N₂), from φ_mono.le_iff_le.mpr (le_max_right _ _), exact ⟨max N₁ N₂, h₁ _ (le_max_left _ _), trans (hV.decreasing trivial trivial this) h₂⟩ }, suffices : ball (x (φ N)) (V (φ N)) ⊆ c i₀, from hx (φ N) i₀ this, calc ball (x $ φ N) (V $ φ N) ⊆ ball (x $ φ N) W : preimage_mono hVNW ... ⊆ ball x₀ (V n₀) : ball_subset_of_comp_subset x_φ_N_in hWW ... ⊆ c i₀ : hn₀, end lemma is_seq_compact.totally_bounded (h : is_seq_compact s) : totally_bounded s := begin classical, apply totally_bounded_of_forall_symm, unfold is_seq_compact at h, contrapose! h, rcases h with ⟨V, V_in, V_symm, h⟩, simp_rw [not_subset] at h, have : ∀ (t : set β), finite t → ∃ a, a ∈ s ∧ a ∉ ⋃ y ∈ t, ball y V, { intros t ht, obtain ⟨a, a_in, H⟩ : ∃ a ∈ s, ∀ (x : β), x ∈ t → (x, a) ∉ V, by simpa [ht] using h t, use [a, a_in], intro H', obtain ⟨x, x_in, hx⟩ := mem_bUnion_iff.mp H', exact H x x_in hx }, cases seq_of_forall_finite_exists this with u hu, clear h this, simp [forall_and_distrib] at hu, cases hu with u_in hu, use [u, u_in], clear u_in, intros x x_in φ, intros hφ huφ, obtain ⟨N, hN⟩ : ∃ N, ∀ p q, p ≥ N → q ≥ N → (u (φ p), u (φ q)) ∈ V, from huφ.cauchy_seq.mem_entourage V_in, specialize hN N (N+1) (le_refl N) (nat.le_succ N), specialize hu (φ $ N+1) (φ N) (hφ $ lt_add_one N), exact hu hN, end protected lemma is_seq_compact.is_compact (h : is_countably_generated $ 𝓤 β) (hs : is_seq_compact s) : is_compact s := begin classical, rw is_compact_iff_finite_subcover, intros ι U Uop s_sub, rcases lebesgue_number_lemma_seq hs Uop s_sub h with ⟨V, V_in, Vsymm, H⟩, rcases totally_bounded_iff_subset.mp hs.totally_bounded V V_in with ⟨t,t_sub, tfin, ht⟩, have : ∀ x : t, ∃ (i : ι), ball x.val V ⊆ U i, { rintros ⟨x, x_in⟩, exact H x (t_sub x_in) }, choose i hi using this, haveI : fintype t := tfin.fintype, use finset.image i finset.univ, transitivity ⋃ y ∈ t, ball y V, { intros x x_in, specialize ht x_in, rw mem_bUnion_iff at *, simp_rw ball_eq_of_symmetry Vsymm, exact ht }, { apply bUnion_subset_bUnion, intros x x_in, exact ⟨i ⟨x, x_in⟩, finset.mem_image_of_mem _ (finset.mem_univ _), hi ⟨x, x_in⟩⟩ }, end protected lemma uniform_space.compact_iff_seq_compact (h : is_countably_generated $ 𝓤 β) : is_compact s ↔ is_seq_compact s := begin haveI := uniform_space.first_countable_topology h, exact ⟨λ H, H.is_seq_compact, λ H, H.is_compact h⟩ end lemma uniform_space.compact_space_iff_seq_compact_space (H : is_countably_generated $ 𝓤 β) : compact_space β ↔ seq_compact_space β := have key : is_compact univ ↔ is_seq_compact univ := uniform_space.compact_iff_seq_compact H, ⟨λ ⟨h⟩, ⟨key.mp h⟩, λ ⟨h⟩, ⟨key.mpr h⟩⟩ end uniform_space_seq_compact section metric_seq_compact variables [metric_space β] {s : set β} open metric /-- A version of Bolzano-Weistrass: in a metric space, is_compact s ↔ is_seq_compact s -/ lemma metric.compact_iff_seq_compact : is_compact s ↔ is_seq_compact s := uniform_space.compact_iff_seq_compact emetric.uniformity_has_countable_basis /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. This version assumes only that the sequence is frequently in some bounded set. -/ lemma tendsto_subseq_of_frequently_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∃ᶠ n in at_top, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := begin have hcs : is_compact (closure s) := compact_iff_closed_bounded.mpr ⟨is_closed_closure, bounded_closure_of_bounded hs⟩, replace hcs : is_seq_compact (closure s), by rwa metric.compact_iff_seq_compact at hcs, have hu' : ∃ᶠ n in at_top, u n ∈ closure s, { apply frequently.mono hu, intro n, apply subset_closure }, exact hcs.subseq_of_frequently_in hu', end /-- A version of Bolzano-Weistrass: in a proper metric space (eg. $ℝ^n$), every bounded sequence has a converging subsequence. -/ lemma tendsto_subseq_of_bounded [proper_space β] (hs : bounded s) {u : ℕ → β} (hu : ∀ n, u n ∈ s) : ∃ b ∈ closure s, ∃ φ : ℕ → ℕ, strict_mono φ ∧ tendsto (u ∘ φ) at_top (𝓝 b) := tendsto_subseq_of_frequently_bounded hs $ frequently_of_forall hu lemma metric.compact_space_iff_seq_compact_space : compact_space β ↔ seq_compact_space β := uniform_space.compact_space_iff_seq_compact_space emetric.uniformity_has_countable_basis lemma seq_compact.lebesgue_number_lemma_of_metric {ι : Type*} {c : ι → set β} (hs : is_seq_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := begin rcases lebesgue_number_lemma_seq hs hc₁ hc₂ emetric.uniformity_has_countable_basis with ⟨V, V_in, _, hV⟩, rcases uniformity_basis_dist.mem_iff.mp V_in with ⟨δ, δ_pos, h⟩, use [δ, δ_pos], intros x x_in, rcases hV x x_in with ⟨i, hi⟩, use i, have := ball_mono h x, rw ball_eq_ball' at this, exact subset.trans this hi, end end metric_seq_compact
cd24e4393a9faff893afba01981ba1ee75485ca0
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/support.lean
0cd9ffd39e7d95afdc43eff0ef6d28f20578ca1a
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
11,476
lean
/- Copyright (c) 2022 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Patrick Massot -/ import topology.separation /-! # The topological support of a function In this file we define the topological support of a function `f`, `tsupport f`, as the closure of the support of `f`. Furthermore, we say that `f` has compact support if the topological support of `f` is compact. ## Main definitions * `function.mul_tsupport` & `function.tsupport` * `function.has_compact_mul_support` & `function.has_compact_support` ## Implementation Notes * We write all lemmas for multiplicative functions, and use `@[to_additive]` to get the more common additive versions. * We do not put the definitions in the `function` namespace, following many other topological definitions that are in the root namespace (compare `embedding` vs `function.embedding`). -/ open function set filter open_locale topological_space variables {X α α' β γ δ M E R : Type*} section one variables [has_one α] variables [topological_space X] /-- The topological support of a function is the closure of its support, i.e. the closure of the set of all elements where the function is not equal to 1. -/ @[to_additive /-" The topological support of a function is the closure of its support. i.e. the closure of the set of all elements where the function is nonzero. "-/] def mul_tsupport (f : X → α) : set X := closure (mul_support f) @[to_additive] lemma subset_mul_tsupport (f : X → α) : mul_support f ⊆ mul_tsupport f := subset_closure @[to_additive] lemma is_closed_mul_tsupport (f : X → α) : is_closed (mul_tsupport f) := is_closed_closure @[to_additive] lemma mul_tsupport_eq_empty_iff {f : X → α} : mul_tsupport f = ∅ ↔ f = 1 := by rw [mul_tsupport, closure_empty_iff, mul_support_eq_empty_iff] @[to_additive] lemma image_eq_zero_of_nmem_mul_tsupport {f : X → α} {x : X} (hx : x ∉ mul_tsupport f) : f x = 1 := mul_support_subset_iff'.mp (subset_mul_tsupport f) x hx @[to_additive] lemma range_subset_insert_image_mul_tsupport (f : X → α) : range f ⊆ insert 1 (f '' mul_tsupport f) := (range_subset_insert_image_mul_support f).trans $ insert_subset_insert $ image_subset _ subset_closure @[to_additive] lemma range_eq_image_mul_tsupport_or (f : X → α) : range f = f '' mul_tsupport f ∨ range f = insert 1 (f '' mul_tsupport f) := (wcovby_insert _ _).eq_or_eq (image_subset_range _ _) (range_subset_insert_image_mul_tsupport f) lemma tsupport_mul_subset_left {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport f := closure_mono (support_mul_subset_left _ _) lemma tsupport_mul_subset_right {α : Type*} [mul_zero_class α] {f g : X → α} : tsupport (λ x, f x * g x) ⊆ tsupport g := closure_mono (support_mul_subset_right _ _) end one section variables [topological_space α] [topological_space α'] variables [has_one β] [has_one γ] [has_one δ] variables {g : β → γ} {f : α → β} {f₂ : α → γ} {m : β → γ → δ} {x : α} @[to_additive] lemma not_mem_closure_mul_support_iff_eventually_eq : x ∉ mul_tsupport f ↔ f =ᶠ[𝓝 x] 1 := by simp_rw [mul_tsupport, mem_closure_iff_nhds, not_forall, not_nonempty_iff_eq_empty, ← disjoint_iff_inter_eq_empty, disjoint_mul_support_iff, eventually_eq_iff_exists_mem] /-- A function `f` *has compact multiplicative support* or is *compactly supported* if the closure of the multiplicative support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `1` outside a compact set. -/ @[to_additive /-" A function `f` *has compact support* or is *compactly supported* if the closure of the support of `f` is compact. In a T₂ space this is equivalent to `f` being equal to `0` outside a compact set. "-/] def has_compact_mul_support (f : α → β) : Prop := is_compact (mul_tsupport f) @[to_additive] lemma has_compact_mul_support_def : has_compact_mul_support f ↔ is_compact (closure (mul_support f)) := by refl @[to_additive] lemma exists_compact_iff_has_compact_mul_support [t2_space α] : (∃ K : set α, is_compact K ∧ ∀ x ∉ K, f x = 1) ↔ has_compact_mul_support f := by simp_rw [← nmem_mul_support, ← mem_compl_iff, ← subset_def, compl_subset_compl, has_compact_mul_support_def, exists_compact_superset_iff] @[to_additive] lemma has_compact_mul_support.intro [t2_space α] {K : set α} (hK : is_compact K) (hfK : ∀ x ∉ K, f x = 1) : has_compact_mul_support f := exists_compact_iff_has_compact_mul_support.mp ⟨K, hK, hfK⟩ @[to_additive] lemma has_compact_mul_support.is_compact (hf : has_compact_mul_support f) : is_compact (mul_tsupport f) := hf @[to_additive] lemma has_compact_mul_support_iff_eventually_eq : has_compact_mul_support f ↔ f =ᶠ[coclosed_compact α] 1 := ⟨ λ h, mem_coclosed_compact.mpr ⟨mul_tsupport f, is_closed_mul_tsupport _, h, λ x, not_imp_comm.mpr $ λ hx, subset_mul_tsupport f hx⟩, λ h, let ⟨C, hC⟩ := mem_coclosed_compact'.mp h in compact_of_is_closed_subset hC.2.1 (is_closed_mul_tsupport _) (closure_minimal hC.2.2 hC.1)⟩ @[to_additive] lemma has_compact_mul_support.is_compact_range [topological_space β] (h : has_compact_mul_support f) (hf : continuous f) : is_compact (range f) := begin cases range_eq_image_mul_tsupport_or f with h2 h2; rw [h2], exacts [h.image hf, (h.image hf).insert 1] end @[to_additive] lemma has_compact_mul_support.mono' {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_tsupport f) : has_compact_mul_support f' := compact_of_is_closed_subset hf is_closed_closure $ closure_minimal hff' is_closed_closure @[to_additive] lemma has_compact_mul_support.mono {f' : α → γ} (hf : has_compact_mul_support f) (hff' : mul_support f' ⊆ mul_support f) : has_compact_mul_support f' := hf.mono' $ hff'.trans subset_closure @[to_additive] lemma has_compact_mul_support.comp_left (hf : has_compact_mul_support f) (hg : g 1 = 1) : has_compact_mul_support (g ∘ f) := hf.mono $ mul_support_comp_subset hg f @[to_additive] lemma has_compact_mul_support_comp_left (hg : ∀ {x}, g x = 1 ↔ x = 1) : has_compact_mul_support (g ∘ f) ↔ has_compact_mul_support f := by simp_rw [has_compact_mul_support_def, mul_support_comp_eq g @hg f] @[to_additive] lemma has_compact_mul_support.comp_closed_embedding (hf : has_compact_mul_support f) {g : α' → α} (hg : closed_embedding g) : has_compact_mul_support (f ∘ g) := begin rw [has_compact_mul_support_def, function.mul_support_comp_eq_preimage], refine compact_of_is_closed_subset (hg.is_compact_preimage hf) is_closed_closure _, rw [hg.to_embedding.closure_eq_preimage_closure_image], exact preimage_mono (closure_mono $ image_preimage_subset _ _) end @[to_additive] lemma has_compact_mul_support.comp₂_left (hf : has_compact_mul_support f) (hf₂ : has_compact_mul_support f₂) (hm : m 1 1 = 1) : has_compact_mul_support (λ x, m (f x) (f₂ x)) := begin rw [has_compact_mul_support_iff_eventually_eq] at hf hf₂ ⊢, filter_upwards [hf, hf₂] using λ x hx hx₂, by simp_rw [hx, hx₂, pi.one_apply, hm] end end section monoid variables [topological_space α] [monoid β] variables {f f' : α → β} {x : α} @[to_additive] lemma has_compact_mul_support.mul (hf : has_compact_mul_support f) (hf' : has_compact_mul_support f') : has_compact_mul_support (f * f') := by apply hf.comp₂_left hf' (mul_one 1) -- `by apply` speeds up elaboration end monoid section distrib_mul_action variables [topological_space α] [monoid_with_zero R] [add_monoid M] [distrib_mul_action R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_left (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero]) end end distrib_mul_action section smul_with_zero variables [topological_space α] [has_zero R] [has_zero M] [smul_with_zero R M] variables {f : α → R} {f' : α → M} {x : α} lemma has_compact_support.smul_right (hf : has_compact_support f) : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, zero_smul]) end lemma has_compact_support.smul_left' (hf : has_compact_support f') : has_compact_support (f • f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.smul_apply', hx, pi.zero_apply, smul_zero']) end end smul_with_zero section mul_zero_class variables [topological_space α] [mul_zero_class β] variables {f f' : α → β} {x : α} lemma has_compact_support.mul_right (hf : has_compact_support f) : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, zero_mul]) end lemma has_compact_support.mul_left (hf : has_compact_support f') : has_compact_support (f * f') := begin rw [has_compact_support_iff_eventually_eq] at hf ⊢, refine hf.mono (λ x hx, by simp_rw [pi.mul_apply, hx, pi.zero_apply, mul_zero]) end end mul_zero_class namespace locally_finite variables {ι : Type*} {U : ι → set X} [topological_space X] [has_one R] /-- If a family of functions `f` has locally-finite multiplicative support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are not equal to 1. -/ @[to_additive /-" If a family of functions `f` has locally-finite support, subordinate to a family of open sets, then for any point we can find a neighbourhood on which only finitely-many members of `f` are non-zero. "-/] lemma exists_finset_nhd_mul_support_subset {f : ι → X → R} (hlf : locally_finite (λ i, mul_support (f i))) (hso : ∀ i, mul_tsupport (f i) ⊆ U i) (ho : ∀ i, is_open (U i)) (x : X) : ∃ (is : finset ι) {n : set X} (hn₁ : n ∈ 𝓝 x) (hn₂ : n ⊆ ⋂ i ∈ is, U i), ∀ (z ∈ n), mul_support (λ i, f i z) ⊆ is := begin obtain ⟨n, hn, hnf⟩ := hlf x, classical, let is := hnf.to_finset.filter (λ i, x ∈ U i), let js := hnf.to_finset.filter (λ j, x ∉ U j), refine ⟨is, n ∩ (⋂ j ∈ js, (mul_tsupport (f j))ᶜ) ∩ (⋂ i ∈ is, U i), inter_mem (inter_mem hn _) _, inter_subset_right _ _, λ z hz, _⟩, { exact (bInter_finset_mem js).mpr (λ j hj, is_closed.compl_mem_nhds (is_closed_mul_tsupport _) (set.not_mem_subset (hso j) (finset.mem_filter.mp hj).2)), }, { exact (bInter_finset_mem is).mpr (λ i hi, (ho i).mem_nhds (finset.mem_filter.mp hi).2) }, { have hzn : z ∈ n, { rw inter_assoc at hz, exact mem_of_mem_inter_left hz, }, replace hz := mem_of_mem_inter_right (mem_of_mem_inter_left hz), simp only [finset.mem_filter, finite.mem_to_finset, mem_set_of_eq, mem_Inter, and_imp] at hz, suffices : mul_support (λ i, f i z) ⊆ hnf.to_finset, { refine hnf.to_finset.subset_coe_filter_of_subset_forall _ this (λ i hi, _), specialize hz i ⟨z, ⟨hi, hzn⟩⟩, contrapose hz, simp [hz, subset_mul_tsupport (f i) hi], }, intros i hi, simp only [finite.coe_to_finset, mem_set_of_eq], exact ⟨z, ⟨hi, hzn⟩⟩, }, end end locally_finite
82e62f17292d076c6b03e4bbfd5d9687045bd79d
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/analysis/normed_space/operator_norm.lean
b025d92265e70e9e1ea0630de6478616a448ad17
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
44,773
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import linear_algebra.finite_dimensional import analysis.normed_space.riesz_lemma import analysis.asymptotics /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. -/ noncomputable theory open_locale classical nnreal variables {𝕜 : Type*} {E : Type*} {F : Type*} {G : Type*} [normed_group E] [normed_group F] [normed_group G] open metric continuous_linear_map lemma exists_pos_bound_of_bound {f : E → F} (M : ℝ) (h : ∀x, ∥f x∥ ≤ M * ∥x∥) : ∃ N, 0 < N ∧ ∀x, ∥f x∥ ≤ N * ∥x∥ := ⟨max M 1, lt_of_lt_of_le zero_lt_one (le_max_right _ _), λx, calc ∥f x∥ ≤ M * ∥x∥ : h x ... ≤ max M 1 * ∥x∥ : mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg _) ⟩ section normed_field /- Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (nnreal.of_real C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) theorem linear_map.antilipschitz_of_bound {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.bound_of_antilipschitz {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ∥x∥ ≤ K * ∥f x∥ := by simpa only [dist_zero_right, f.map_zero] using h.le_mul_dist x 0 lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →L[𝕜] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_bound {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] F := ⟨f, h_add, h_smul⟩ in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (continuous_iff_is_closed.1 h) {0} (t1_space.t1 0), λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], norm_num }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, normed_field.norm_mul, normed_field.norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field section add_monoid_hom lemma add_monoid_hom.isometry_of_norm (f : E →+ F) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := begin intros x y, simp_rw [edist_dist], congr', simp_rw [dist_eq_norm, ←add_monoid_hom.map_sub], exact hf (x - y), end end add_monoid_hom variables [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] [normed_space 𝕜 G] (c : 𝕜) (f g : E →L[𝕜] F) (h : F →L[𝕜] G) (x y z : E) include 𝕜 lemma linear_map.bound_of_shell (f : E →ₗ[𝕜] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) (x : E) : ∥f x∥ ≤ C * ∥x∥ := begin by_cases hx : x = 0, { simp [hx] }, rcases rescale_to_shell hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, simpa only [f.map_smul, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ)] using hf (δ • x) leδx δxle end /-- A continuous linear map between normed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `ε`. The nondiscreteness is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₗ[𝕜] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin have : continuous_at f 0 := continuous_iff_continuous_at.1 hf _, rcases (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).1 this 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [mem_closed_ball, dist_zero_right, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨ε⁻¹ * ∥c∥, mul_pos (inv_pos.2 ε_pos) (lt_trans zero_lt_one hc), _⟩, suffices : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ ε⁻¹ * ∥c∥ * ∥x∥, from f.bound_of_shell ε_pos hc this, intros x hle hlt, refine (hε _ hlt.le).trans _, rwa [mul_assoc, ← div_le_iff' (inv_pos.2 ε_pos), div_eq_mul_inv, inv_inv', one_mul, ← div_le_iff' (zero_lt_one.trans hc)] end namespace continuous_linear_map theorem bound : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open asymptotics filter theorem is_O_id (l : filter E) : is_O f (λ x, x) l := let ⟨M, hMp, hM⟩ := f.bound in is_O_of_le' l hM theorem is_O_comp {α : Type*} (g : F →L[𝕜] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_id ⊤).comp_tendsto le_top theorem is_O_sub (f : E →L[𝕜] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₗ[𝕜] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →L[𝕜] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `E` to the span of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →L[𝕜] F) := ⟨op_norm⟩ lemma norm_def : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `real.Inf_le` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty {f : E →L[𝕜] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →L[𝕜] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma op_norm_nonneg : 0 ≤ ∥f∥ := lb_le_Inf _ bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := classical.by_cases (λ heq : x = 0, by { rw heq, simp }) (λ hne, have hlt : 0 < ∥x∥, from norm_pos_iff.2 hne, (div_le_iff hlt).mp ((le_Inf _ bounds_nonempty bounds_bdd_below).2 (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc }))) theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : E) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ⟨∥f∥, op_norm_nonneg f⟩ f := lipschitz_with.of_dist_le_mul $ λ x y, by { rw [dist_eq_norm, dist_eq_norm, ←map_sub], apply le_op_norm } lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_iff_of_nonneg_of_le (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := Inf_le _ bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →L[𝕜] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_le_of_shell {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := f.op_norm_le_bound hC $ (f : E →ₗ[𝕜] F).bound_of_shell ε_pos hc hf lemma op_norm_le_of_ball {f : E →L[𝕜] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_0_eq end lemma op_norm_le_of_shell' {f : E →L[𝕜] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ∥c∥ < 1) (hf : ∀ x, ε * ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_0_eq at hx } }, { rw [← inv_inv' c, normed_field.norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [normed_field.norm_inv, div_eq_mul_inv, inv_inv'] } end lemma op_norm_eq_of_bounds {φ : E →L[𝕜] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := show ∥f + g∥ ≤ (coe : ℝ≥0 → ℝ) (⟨_, f.op_norm_nonneg⟩ + ⟨_, g.op_norm_nonneg⟩), from op_norm_le_of_lipschitz (f.lipschitz.add g.lipschitz) /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (Inf_le _ bounds_bdd_below ⟨ge_of_eq rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If a space is non-trivial, then the norm of the identity equals `1`. -/ lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := exists_ne (0 : E) in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self (ne_of_gt $ norm_pos_iff.2 hx)] at this @[simp] lemma norm_id_field : ∥id 𝕜 𝕜∥ = 1 := norm_id @[simp] lemma norm_id_field' : ∥(1 : 𝕜 →L[𝕜] 𝕜)∥ = 1 := norm_id_field lemma op_norm_smul_le : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) lemma op_norm_neg : ∥-f∥ = ∥f∥ := by { rw norm_def, apply congr_arg, ext, simp } /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group : normed_group (E →L[𝕜] F) := normed_group.of_core _ ⟨op_norm_zero_iff, op_norm_add_le, op_norm_neg⟩ instance to_normed_space : normed_space 𝕜 (E →L[𝕜] F) := ⟨op_norm_smul_le⟩ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →L[𝕜] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (Inf_le _ bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } /-- For a nonzero normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra [nontrivial E] : normed_algebra 𝕜 (E →L[𝕜] E) := { norm_algebra_map_eq := λ c, show ∥c • id 𝕜 E∥ = ∥c∥, by {rw [norm_smul, norm_id], simp}, .. continuous_linear_map.algebra } /-- A continuous linear map is automatically uniformly continuous. -/ protected theorem uniform_continuous : uniform_continuous f := f.lipschitz.uniform_continuous variable {f} /-- A continuous linear map is an isometry if and only if it preserves the norm. -/ lemma isometry_iff_norm_image_eq_norm : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := begin rw isometry_emetric_iff_metric, split, { assume H x, have := H x 0, rwa [dist_eq_norm, dist_eq_norm, f.map_zero, sub_zero, sub_zero] at this }, { assume H x y, rw [dist_eq_norm, dist_eq_norm, ← f.map_sub, H] } end lemma homothety_norm [nontrivial E] (f : E →L[𝕜] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, have ha : 0 ≤ a, { apply nonneg_of_mul_nonneg_right, rw ← hf x, apply norm_nonneg, exact norm_pos_iff.mpr hx }, refine le_antisymm_iff.mpr ⟨_, _⟩, { exact continuous_linear_map.op_norm_le_bound f ha (λ y, le_of_eq (hf y)) }, { rw continuous_linear_map.norm_def, apply real.lb_le_Inf _ continuous_linear_map.bounds_nonempty, intros c h, rw mem_set_of_eq at h, apply (mul_le_mul_right (norm_pos_iff.mpr hx)).mp, rw ← hf x, exact h.2 x } end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : ℝ≥0} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { refine (hε _).le, rw [f.map_zero, dist_zero_right], exact hx.trans_lt (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * nnnorm c, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxlt, ledx, dinv⟩, rw [← f.map_smul d] at dxlt, have : ∥d • x∥ ≤ 1 := H dxlt.le, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← normed_field.norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. -/ instance [complete_space F] : complete_space (E →L[𝕜] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- We now expand out the definition of a Cauchy sequence, rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩, clear hf, -- and establish that the evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), { assume v, apply cauchy_seq_iff_le_tendsto_0.2 ⟨λ n, b n * ∥v∥, λ n, _, _, _⟩, { exact mul_nonneg (b0 n) (norm_nonneg _) }, { assume n m N hn hm, rw dist_eq_norm, apply le_trans ((f n - f m).le_op_norm v) _, exact mul_le_mul_of_nonneg_right (b_bound n m N hn hm) (norm_nonneg v) }, { simpa using b_lim.mul tendsto_const_nhds } }, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is linear, let Glin : E →ₗ[𝕜] F := { to_fun := G, map_add' := λ v w, begin have A := hG (v + w), have B := (hG v).add (hG w), simp only [map_add] at A B, exact tendsto_nhds_unique A B, end, map_smul' := λ c v, begin have A := hG (c • v), have B := filter.tendsto.smul (@tendsto_const_nhds _ ℕ _ c _) (hG v), simp only [map_smul] at A B, exact tendsto_nhds_unique A B end }, -- and that `G` has norm at most `(b 0 + ∥f 0∥)`. have Gnorm : ∀ v, ∥G v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume v, have A : ∀ n, ∥f n v∥ ≤ (b 0 + ∥f 0∥) * ∥v∥, { assume n, apply le_trans ((f n).le_op_norm _) _, apply mul_le_mul_of_nonneg_right _ (norm_nonneg v), calc ∥f n∥ = ∥(f n - f 0) + f 0∥ : by { congr' 1, abel } ... ≤ ∥f n - f 0∥ + ∥f 0∥ : norm_add_le _ _ ... ≤ b 0 + ∥f 0∥ : begin apply add_le_add_right, simpa [dist_eq_norm] using b_bound n 0 0 (zero_le _) (zero_le _) end }, exact le_of_tendsto (hG v).norm (eventually_of_forall A) }, -- Thus `G` is continuous, and we propose that as the limit point of our original Cauchy sequence. let Gcont := Glin.mk_continuous _ Gnorm, use Gcont, -- Our last task is to establish convergence to `G` in norm. have : ∀ n, ∥f n - Gcont∥ ≤ b n, { assume n, apply op_norm_le_bound _ (b0 n) (λ v, _), have A : ∀ᶠ m in at_top, ∥(f n - f m) v∥ ≤ b n * ∥v∥, { refine eventually_at_top.2 ⟨n, λ m hm, _⟩, apply le_trans ((f n - f m).le_op_norm _) _, exact mul_le_mul_of_nonneg_right (b_bound n m n (le_refl _) hm) (norm_nonneg v) }, have B : tendsto (λ m, ∥(f n - f m) v∥) at_top (𝓝 (∥(f n - Gcont) v∥)) := tendsto.norm (tendsto_const_nhds.sub (hG v)), exact le_of_tendsto B A }, erw tendsto_iff_norm_tendsto_zero, exact squeeze_zero (λ n, norm_nonneg _) this b_lim, end end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] G) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →L[𝕜] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] G`. -/ def extend : G →L[𝕜] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const.smul continuous_id)) ((continuous_const.smul continuous_id).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smul _ _ _ }, end, cont := cont } lemma extend_unique (g : G →L[𝕜] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.injective_coe_fn $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →L[𝕜] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : ℝ≥0} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma linear_map.mk_continuous_norm_le (f : E →ₗ[𝕜] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h namespace continuous_linear_map /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : ∥f∥ = 0, { rw h, simp [norm_nonneg] }, { have : 0 < ∥f∥ := lt_of_le_of_ne (norm_nonneg _) (ne.symm h), rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥((smul_right c f) : E → F) x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- Given `c : c : E →L[𝕜] 𝕜`, `c.smul_rightL` is the continuous linear map from `F` to `E →L[𝕜] F` sending `f` to `λ e, c e • f`. -/ def smul_rightL (c : E →L[𝕜] 𝕜) : F →L[𝕜] (E →L[𝕜] F) := (c.smul_rightₗ : F →ₗ[𝕜] (E →L[𝕜] F)).mk_continuous _ (λ f, le_of_eq $ c.norm_smul_right_apply f) @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : F) : ∥c.smul_rightL f∥ = ∥c∥ * ∥f∥ := by simp [continuous_linear_map.smul_rightL, continuous_linear_map.smul_rightₗ] @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial F] : ∥(c.smul_rightL : F →L[𝕜] (E →L[𝕜] F))∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜 F) /-- The linear map obtained by applying a continuous linear map at a given vector. -/ def applyₗ (v : E) : (E →L[𝕜] F) →ₗ[𝕜] F := { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v } lemma continuous_applyₗ (v : E) : continuous (continuous_linear_map.applyₗ 𝕜 F v) := begin apply (continuous_linear_map.applyₗ 𝕜 F v).continuous_of_bound, intro f, rw mul_comm, exact f.le_op_norm v, end /-- The continuous linear map obtained by applying a continuous linear map at a given vector. -/ def apply (v : E) : (E →L[𝕜] F) →L[𝕜] F := ⟨continuous_linear_map.applyₗ 𝕜 F v, continuous_linear_map.continuous_applyₗ _ _ _⟩ variables {𝕜 F} @[simp] lemma apply_apply (v : E) (f : E →L[𝕜] F) : apply 𝕜 F v f = f v := rfl section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_left 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw algebra.lmul_left_apply, exact norm_mul_le x y}) /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' → (𝕜' →L[𝕜] 𝕜') := λ x, (algebra.lmul_right 𝕜 x).mk_continuous ∥x∥ (λ y, by {rw [algebra.lmul_right_apply, mul_comm], exact norm_mul_le y x}) /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_left_right (vw : 𝕜' × 𝕜') : 𝕜' →L[𝕜] 𝕜' := (lmul_right 𝕜 𝕜' vw.2).comp (lmul_left 𝕜 𝕜' vw.1) @[simp] lemma lmul_left_apply (x y : 𝕜') : lmul_left 𝕜 𝕜' x y = x * y := rfl @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma lmul_left_right_apply (vw : 𝕜' × 𝕜') (x : 𝕜') : lmul_left_right 𝕜 𝕜' vw x = vw.1 * x * vw.2 := rfl end multiplication_linear section restrict_scalars variable (𝕜) variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] [normed_space 𝕜' E'] variables [is_scalar_tower 𝕜 𝕜' E'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] /-- `𝕜`-linear continuous function induced by a `𝕜'`-linear continuous function when `𝕜'` is a normed algebra over `𝕜`. -/ def restrict_scalars (f : E' →L[𝕜'] F') : E' →L[𝕜] F' := { cont := f.cont, ..linear_map.restrict_scalars 𝕜 (f.to_linear_map) } @[simp, norm_cast] lemma restrict_scalars_coe_eq_coe (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' →ₗ[𝕜] F') = (f : E' →ₗ[𝕜'] F').restrict_scalars 𝕜 := rfl @[simp, norm_cast squash] lemma restrict_scalars_coe_eq_coe' (f : E' →L[𝕜'] F') : (f.restrict_scalars 𝕜 : E' → F') = f := rfl end restrict_scalars section extend_scalars variables {𝕜' : Type*} [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] variables {F' : Type*} [normed_group F'] [normed_space 𝕜 F'] [normed_space 𝕜' F'] variables [is_scalar_tower 𝕜 𝕜' F'] instance has_scalar_extend_scalars : has_scalar 𝕜' (E →L[𝕜] F') := { smul := λ c f, (c • f.to_linear_map).mk_continuous (∥c∥ * ∥f∥) begin assume x, calc ∥c • (f x)∥ = ∥c∥ * ∥f x∥ : norm_smul c _ ... ≤ ∥c∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left (le_op_norm f x) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : (mul_assoc _ _ _).symm end } instance module_extend_scalars : module 𝕜' (E →L[𝕜] F') := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } instance normed_space_extend_scalars : normed_space 𝕜' (E →L[𝕜] F') := { norm_smul_le := λ c f, linear_map.mk_continuous_norm_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _ } /-- When `f` is a continuous linear map taking values in `S`, then `λb, f b • x` is a continuous linear map. -/ def smul_algebra_right (f : E →L[𝕜] 𝕜') (x : F') : E →L[𝕜] F' := { cont := by continuity!, .. f.to_linear_map.smul_algebra_right x } @[simp] theorem smul_algebra_right_apply (f : E →L[𝕜] 𝕜') (x : F') (c : E) : smul_algebra_right f x c = f c • x := rfl end extend_scalars end continuous_linear_map /-- The continuous linear map of inclusion from a submodule of `K` into `E`. -/ def submodule.subtype_continuous (K : submodule 𝕜 E) : K →L[𝕜] E := linear_map.mk_continuous K.subtype 1 (λ x, by { simp only [one_mul, submodule.subtype_apply], refl }) @[simp] lemma submodule.subtype_continuous_apply (K : submodule 𝕜 E) (v : K) : submodule.subtype_continuous K v = (v : E) := rfl section has_sum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variables {ι R M M₂ : Type*} [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid M₂] [semimodule R M₂] [topological_space M] [topological_space M₂] omit 𝕜 /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →L[R] M₂) {x : M} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous alias continuous_linear_map.has_sum ← has_sum.mapL protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : summable (λ b:ι, φ (f b)) := (hf.has_sum.mapL φ).summable alias continuous_linear_map.summable ← summable.mapL protected lemma continuous_linear_map.map_tsum [t2_space M₂] {f : ι → M} (φ : M →L[R] M₂) (hf : summable f) : φ (∑' z, f z) = ∑' z, φ (f z) := (hf.has_sum.mapL φ).tsum_eq.symm /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) := ⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →L[R] M), λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →L[R] M₂).has_sum h⟩ protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃L[R] M₂) : summable (λ b:ι, e (f b)) ↔ summable f := ⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →L[R] M₂).summable⟩ lemma continuous_linear_equiv.tsum_eq_iff [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) {y : M₂} : (∑' z, e (f z)) = y ↔ (∑' z, f z) = e.symm y := begin by_cases hf : summable f, { exact ⟨λ h, (e.has_sum.mp ((e.summable.mpr hf).has_sum_iff.mpr h)).tsum_eq, λ h, (e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩ }, { have hf' : ¬summable (λ z, e (f z)) := λ h, hf (e.summable.mp h), rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'], exact ⟨by { rintro rfl, simp }, λ H, by simpa using (congr_arg (λ z, e z) H)⟩ } end protected lemma continuous_linear_equiv.map_tsum [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃L[R] M₂) : e (∑' z, f z) = ∑' z, e (f z) := by { refine symm (e.tsum_eq_iff.mpr _), rw e.symm_apply_apply _ } end has_sum namespace continuous_linear_equiv variable (e : E ≃L[𝕜] F) protected lemma lipschitz : lipschitz_with (nnnorm (e : E →L[𝕜] F)) e := (e : E →L[𝕜] F).lipschitz protected lemma antilipschitz : antilipschitz_with (nnnorm (e.symm : F →L[𝕜] E)) e := e.symm.lipschitz.to_right_inverse e.left_inv theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →L[𝕜] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →L[𝕜] F).is_O_sub l x theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ /-- A continuous linear equiv is a uniform embedding. -/ lemma uniform_embedding : uniform_embedding e := e.antilipschitz.uniform_embedding e.lipschitz.uniform_continuous lemma one_le_norm_mul_norm_symm [nontrivial E] : 1 ≤ ∥(e : E →L[𝕜] F)∥ * ∥(e.symm : F →L[𝕜] E)∥ := begin rw [mul_comm], convert (e.symm : F →L[𝕜] E).op_norm_comp_le (e : E →L[𝕜] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end lemma norm_pos [nontrivial E] : 0 < ∥(e : E →L[𝕜] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma norm_symm_pos [nontrivial E] : 0 < ∥(e.symm : F →L[𝕜] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma subsingleton_or_norm_symm_pos : subsingleton E ∨ 0 < ∥(e.symm : F →L[𝕜] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos : subsingleton E ∨ 0 < (nnnorm $ (e.symm : F →L[𝕜] E)) := subsingleton_or_norm_symm_pos e lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₗ[𝕜] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end variable (𝕜) /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₗ[𝕜] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear equivalence from `E` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (𝕜 ∙ x) := of_homothety 𝕜 (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ abbreviation coord (x : E) (h : x ≠ 0) : (𝕜 ∙ x) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (𝕜 ∙ x) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : 𝕜 ∙ x) = 1 := linear_equiv.coord_self 𝕜 E x h end continuous_linear_equiv lemma linear_equiv.uniform_embedding (e : E ≃ₗ[𝕜] F) (h₁ : continuous e) (h₂ : continuous e.symm) : uniform_embedding e := continuous_linear_equiv.uniform_embedding { continuous_to_fun := h₁, continuous_inv_fun := h₂, .. e } /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₗ[𝕜] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃L[𝕜] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } namespace continuous_linear_map variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma lmul_left_norm (v : 𝕜') : ∥lmul_left 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_left 𝕜 𝕜' v) (1:𝕜') } end @[simp] lemma lmul_right_norm (v : 𝕜') : ∥lmul_right 𝕜 𝕜' v∥ = ∥v∥ := begin refine le_antisymm _ _, { exact linear_map.mk_continuous_norm_le _ (norm_nonneg v) _ }, { simpa [@normed_algebra.norm_one 𝕜 _ 𝕜' _ _] using le_op_norm (lmul_right 𝕜 𝕜' v) (1:𝕜') } end lemma lmul_left_right_norm_le (vw : 𝕜' × 𝕜') : ∥lmul_left_right 𝕜 𝕜' vw∥ ≤ ∥vw.1∥ * ∥vw.2∥ := by simpa [mul_comm] using op_norm_comp_le (lmul_right 𝕜 𝕜' vw.2) (lmul_left 𝕜 𝕜' vw.1) end continuous_linear_map
5c6d79b85e3e78928276131a3c03024ce685aa7c
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/while/BigStepEquiv.lean
85a66b6fdd82cececd84df97f509f0d2cd990dea
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
3,531
lean
import Stmt import BigStep import Reduce import CloReduce open Stmt open Reduce open CloReduce lemma SeqCompatL : ∀ (e₁ e₁' e₂:Stmt) (s s':Env), CloReduce e₁ s e₁' s' → CloReduce (e₁ ;; e₂) s (e₁' ;; e₂) s' := begin intros e₁ e₁' e₂ s s' H1, induction H1 with _ _ e₁ e₁' e₁'' s₁ s₁' s₁'' H1 H2 H3, { constructor }, { apply cloStep, { apply SEQ_STEP, assumption}, { assumption}} end lemma BigStepCloReduce : ∀ (e:Stmt) (s t:Env), BigStep e s t → CloReduce e s skip t := begin intros e s t H1, induction H1 with _ x a s e₁ e₂ s u t H1 H2 IH1 IH2 b e₁ e₂ s t H1 H2 H3 b e₁ e₂ s t H1 H2 H3 b e₁ s u t H1 H2 H3 H4 H5 b e₁ s H1, { constructor }, { constructor, constructor, constructor }, { cases IH1 with _ _ _ e₁' _ _ s' _ H1 H2, { constructor, { apply SEQ_SKIP }, { assumption }}, { apply CloReduceTrans, { apply SeqCompatL, apply cloStep, { apply H1}, { apply H2}}, { apply cloStep, { apply SEQ_SKIP }, { assumption }}}}, { apply cloStep, { constructor, assumption }, { assumption }}, { apply cloStep , { apply IF_F, assumption }, { assumption }}, { apply CloReduceTrans _ (while b e₁) skip s u t, { apply CloReduceTrans _ (skip ;; while b e₁) _ s u u, { apply CloReduceTrans _ (e₁ ;; while b e₁) _ _ s _, { apply CloReduceTrans _ (ite b (e₁ ;; while b e₁) skip) _ _ s _, { apply cloStep; constructor}, { apply cloStep _ (e₁ ;; while b e₁) _ _ s _, { constructor, assumption }, { constructor }}}, { apply SeqCompatL, assumption }}, { apply cloStep _ (while b e₁) _ _ u _; constructor }}, { assumption }}, { apply cloStep _ (ite b (e₁ ;; while b e₁) skip) _ _ s _, { constructor }, { apply cloStep _ skip _ _ s _, { apply IF_F, assumption }, { constructor }}}, end lemma ReduceBigStep : ∀ (e₁ e₂:Stmt) (s₁ s₂ s₃:Env), Reduce e₁ s₁ e₂ s₂ → BigStep e₂ s₂ s₃ → BigStep e₁ s₁ s₃ := begin intros e₁ e₂ s₁ s₂ s₃ H1, revert s₃, induction H1 with x a s e₁ e₁' e₂ s s' H1 H2 e₁ s₁ b e₁ e₂ s₁ H1 b e₁ e₂ s₁ H1 b e₁ s₁, { intros t H1, cases H1, constructor }, { intros t H2, cases H2 with _ _ _ _ _ _ _ u _ H3 H4, constructor, { apply H2, apply H3 }, { apply H4 }}, { intros s₂ H1, constructor, { constructor }, { assumption }}, { intros s₂ H2, apply BigStep.IF_T; assumption }, { intros s₂ H2, apply BigStep.IF_F; assumption }, { intros s₂ H1, cases H1 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H1 H2 _ _ _ _ _ H1 H2, { cases H2, { apply BigStep.WHILE_T; assumption }}, { cases H2, apply BigStep.WHILE_F; assumption }} end lemma CloReduceBigStep : ∀ (e:Stmt) (s t:Env), CloReduce e s skip t → BigStep e s t := begin intros e₁ s₁ s₃ H1, generalize H2 : skip = e₃, rw H2 at H1, revert H2, induction H1 with e s e₁ e₂ e₃ s₁ s₂ s₃ H1 H2 H3, { intros H1, rw ← H1, constructor }, { intros H4, apply ReduceBigStep, { assumption }, { apply H3, assumption }} end lemma BigStepCloReduceEquiv : ∀ (e:Stmt) (s t:Env), BigStep e s t ↔ CloReduce e s skip t := begin intros e s t, split, { apply BigStepCloReduce }, { apply CloReduceBigStep } end
5c4c168d8adc21a95c7bcdcd31053c84939b0a36
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/InternalExceptionId.lean
771966215e7dc341e4296abc7730097eb1156533
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
1,052
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 -/ namespace Lean structure InternalExceptionId where idx : Nat := 0 deriving Inhabited, BEq builtin_initialize internalExceptionsRef : IO.Ref (Array Name) ← IO.mkRef #[] def registerInternalExceptionId (name : Name) : IO InternalExceptionId := do let exs ← internalExceptionsRef.get if exs.contains name then throw $ IO.userError s!"invalid internal exception id, '{name}' has already been used" let nextIdx := exs.size internalExceptionsRef.modify fun a => a.push name pure { idx := nextIdx } def InternalExceptionId.toString (id : InternalExceptionId) : String := s!"internal exception #{id.idx}" def InternalExceptionId.getName (id : InternalExceptionId) : IO Name := do let exs ← internalExceptionsRef.get let i := id.idx; if h : i < exs.size then pure $ exs.get ⟨i, h⟩ else throw $ IO.userError "invalid internal exception id" end Lean
de4c61afb48480e1e9c979aeb87ac256e5488d29
94935fb4ab68d4ce640296d02911624a93282575
/src/solutions/thursday/afternoon/category_theory/exercise11.lean
6e2a4b19a6dd9086537eddbada06368fea780d75
[]
permissive
marius-leonhardt/lftcm2020
41c0d7fe3457c1cf3b72cbb1c312b48fc94b85d2
a3eb53f18d9be9a5be748dfe8fe74d0d31a0c1f7
refs/heads/master
1,668,623,789,936
1,594,710,949,000
1,594,710,949,000
279,514,936
0
0
MIT
1,594,711,916,000
1,594,711,916,000
null
UTF-8
Lean
false
false
1,313
lean
import algebra.category.CommRing import category_theory.yoneda open category_theory open opposite open polynomial noncomputable theory /-! We show that the forgetful functor `CommRing ⥤ Type` is (co)representable. There are a sequence of hints available in `hints/thursday/afternoon/category_theory/hintX.lean`, for `X = 1,2,3,4`. -/ -- Because we'll be working with `polynomial ℤ`, which is in `Type 0`, -- we just restrict to that universe for this exercise. notation `CommRing` := CommRing.{0} /-! One bonus hint before we start, showing you how to obtain the ring homomorphism from `ℤ` into any commutative ring. -/ example (R : CommRing) : ℤ →+* R := by library_search /-! Also useful may be the functions -/ #print polynomial.eval₂ #print polynomial.eval₂_ring_hom /-! The actual exercise! -/ def CommRing_forget_representable : Σ (R : CommRing), (forget CommRing) ≅ coyoneda.obj (op R) := -- sorry ⟨CommRing.of (polynomial ℤ), { hom := { app := λ R r, polynomial.eval₂_ring_hom (algebra_map ℤ R) r, }, inv := { app := λ R f, by { dsimp at f, exact f X, }, }, }⟩ -- sorry /- If you get an error message ``` synthesized type class instance is not definitionally equal to expression inferred by typing rules ``` while solving this exercise, see hint4.lean. -/
a0e9d6c5310f68113aa08c76d8ab8f2a549901d7
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/indicator_function.lean
cc4c221a06b5f69cc71e2a9dedee4fb0b06f3c59
[ "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
26,396
lean
/- Copyright (c) 2020 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import algebra.support /-! # Indicator function - `indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `0` otherwise. - `mul_indicator (s : set α) (f : α → β) (a : α)` is `f a` if `a ∈ s` and is `1` otherwise. ## Implementation note In mathematics, an indicator function or a characteristic function is a function used to indicate membership of an element in a set `s`, having the value `1` for all elements of `s` and the value `0` otherwise. But since it is usually used to restrict a function to a certain set `s`, we let the indicator function take the value `f x` for some function `f`, instead of `1`. If the usual indicator function is needed, just set `f` to be the constant function `λx, 1`. The indicator function is implemented non-computably, to avoid having to pass around `decidable` arguments. This is in contrast with the design of `pi.single` or `set.piecewise`. ## Tags indicator, characteristic -/ open_locale big_operators open function variables {α β ι M N : Type*} namespace set section has_one variables [has_one M] [has_one N] {s t : set α} {f g : α → M} {a : α} /-- `indicator s f a` is `f a` if `a ∈ s`, `0` otherwise. -/ noncomputable def indicator {M} [has_zero M] (s : set α) (f : α → M) : α → M | x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 0 /-- `mul_indicator s f a` is `f a` if `a ∈ s`, `1` otherwise. -/ @[to_additive] noncomputable def mul_indicator (s : set α) (f : α → M) : α → M | x := by haveI := classical.dec_pred (∈ s); exact if x ∈ s then f x else 1 @[simp, to_additive] lemma piecewise_eq_mul_indicator [decidable_pred (∈ s)] : s.piecewise f 1 = s.mul_indicator f := funext $ λ x, @if_congr _ _ _ _ (id _) _ _ _ _ iff.rfl rfl rfl @[to_additive] lemma mul_indicator_apply (s : set α) (f : α → M) (a : α) [decidable (a ∈ s)] : mul_indicator s f a = if a ∈ s then f a else 1 := by convert rfl @[simp, to_additive] lemma mul_indicator_of_mem (h : a ∈ s) (f : α → M) : mul_indicator s f a = f a := by { letI := classical.dec (a ∈ s), exact if_pos h } @[simp, to_additive] lemma mul_indicator_of_not_mem (h : a ∉ s) (f : α → M) : mul_indicator s f a = 1 := by { letI := classical.dec (a ∈ s), exact if_neg h } @[to_additive] lemma mul_indicator_eq_one_or_self (s : set α) (f : α → M) (a : α) : mul_indicator s f a = 1 ∨ mul_indicator s f a = f a := begin by_cases h : a ∈ s, { exact or.inr (mul_indicator_of_mem h f) }, { exact or.inl (mul_indicator_of_not_mem h f) } end @[simp, to_additive] lemma mul_indicator_apply_eq_self : s.mul_indicator f a = f a ↔ (a ∉ s → f a = 1) := by letI := classical.dec (a ∈ s); exact ite_eq_left_iff.trans (by rw [@eq_comm _ (f a)]) @[simp, to_additive] lemma mul_indicator_eq_self : s.mul_indicator f = f ↔ mul_support f ⊆ s := by simp only [funext_iff, subset_def, mem_mul_support, mul_indicator_apply_eq_self, not_imp_comm] @[to_additive] lemma mul_indicator_eq_self_of_superset (h1 : s.mul_indicator f = f) (h2 : s ⊆ t) : t.mul_indicator f = f := by { rw mul_indicator_eq_self at h1 ⊢, exact subset.trans h1 h2 } @[simp, to_additive] lemma mul_indicator_apply_eq_one : mul_indicator s f a = 1 ↔ (a ∈ s → f a = 1) := by letI := classical.dec (a ∈ s); exact ite_eq_right_iff @[simp, to_additive] lemma mul_indicator_eq_one : mul_indicator s f = (λ x, 1) ↔ disjoint (mul_support f) s := by simp only [funext_iff, mul_indicator_apply_eq_one, set.disjoint_left, mem_mul_support, not_imp_not] @[simp, to_additive] lemma mul_indicator_eq_one' : mul_indicator s f = 1 ↔ disjoint (mul_support f) s := mul_indicator_eq_one @[to_additive] lemma mul_indicator_apply_ne_one {a : α} : s.mul_indicator f a ≠ 1 ↔ a ∈ s ∩ mul_support f := by simp only [ne.def, mul_indicator_apply_eq_one, not_imp, mem_inter_iff, mem_mul_support] @[simp, to_additive] lemma mul_support_mul_indicator : function.mul_support (s.mul_indicator f) = s ∩ function.mul_support f := ext $ λ x, by simp [function.mem_mul_support, mul_indicator_apply_eq_one] /-- If a multiplicative indicator function is not equal to `1` at a point, then that point is in the set. -/ @[to_additive "If an additive indicator function is not equal to `0` at a point, then that point is in the set."] lemma mem_of_mul_indicator_ne_one (h : mul_indicator s f a ≠ 1) : a ∈ s := not_imp_comm.1 (λ hn, mul_indicator_of_not_mem hn f) h @[to_additive] lemma eq_on_mul_indicator : eq_on (mul_indicator s f) f s := λ x hx, mul_indicator_of_mem hx f @[to_additive] lemma mul_support_mul_indicator_subset : mul_support (s.mul_indicator f) ⊆ s := λ x hx, hx.imp_symm (λ h, mul_indicator_of_not_mem h f) @[simp, to_additive] lemma mul_indicator_mul_support : mul_indicator (mul_support f) f = f := mul_indicator_eq_self.2 subset.rfl @[simp, to_additive] lemma mul_indicator_range_comp {ι : Sort*} (f : ι → α) (g : α → M) : mul_indicator (range f) g ∘ f = g ∘ f := by letI := classical.dec_pred (∈ range f); exact piecewise_range_comp _ _ _ @[to_additive] lemma mul_indicator_congr (h : eq_on f g s) : mul_indicator s f = mul_indicator s g := funext $ λx, by { simp only [mul_indicator], split_ifs, { exact h h_1 }, refl } @[simp, to_additive] lemma mul_indicator_univ (f : α → M) : mul_indicator (univ : set α) f = f := mul_indicator_eq_self.2 $ subset_univ _ @[simp, to_additive] lemma mul_indicator_empty (f : α → M) : mul_indicator (∅ : set α) f = λa, 1 := mul_indicator_eq_one.2 $ disjoint_empty _ @[to_additive] lemma mul_indicator_empty' (f : α → M) : mul_indicator (∅ : set α) f = 1 := mul_indicator_empty f variable (M) @[simp, to_additive] lemma mul_indicator_one (s : set α) : mul_indicator s (λx, (1:M)) = λx, (1:M) := mul_indicator_eq_one.2 $ by simp only [mul_support_one, empty_disjoint] @[simp, to_additive] lemma mul_indicator_one' {s : set α} : s.mul_indicator (1 : α → M) = 1 := mul_indicator_one M s variable {M} @[to_additive] lemma mul_indicator_mul_indicator (s t : set α) (f : α → M) : mul_indicator s (mul_indicator t f) = mul_indicator (s ∩ t) f := funext $ λx, by { simp only [mul_indicator], split_ifs, repeat {simp * at * {contextual := tt}} } @[simp, to_additive] lemma mul_indicator_inter_mul_support (s : set α) (f : α → M) : mul_indicator (s ∩ mul_support f) f = mul_indicator s f := by rw [← mul_indicator_mul_indicator, mul_indicator_mul_support] @[to_additive] lemma comp_mul_indicator (h : M → β) (f : α → M) {s : set α} {x : α} [decidable_pred (∈ s)] : h (s.mul_indicator f x) = s.piecewise (h ∘ f) (const α (h 1)) x := by letI := classical.dec_pred (∈ s); convert s.apply_piecewise f (const α 1) (λ _, h) @[to_additive] lemma mul_indicator_comp_right {s : set α} (f : β → α) {g : α → M} {x : β} : mul_indicator (f ⁻¹' s) (g ∘ f) x = mul_indicator s g (f x) := by { simp only [mul_indicator], split_ifs; refl } @[to_additive] lemma mul_indicator_image {s : set α} {f : β → M} {g : α → β} (hg : injective g) {x : α} : mul_indicator (g '' s) f (g x) = mul_indicator s (f ∘ g) x := by rw [← mul_indicator_comp_right, preimage_image_eq _ hg] @[to_additive] lemma mul_indicator_comp_of_one {g : M → N} (hg : g 1 = 1) : mul_indicator s (g ∘ f) = g ∘ (mul_indicator s f) := begin funext, simp only [mul_indicator], split_ifs; simp [*] end @[to_additive] lemma comp_mul_indicator_const (c : M) (f : M → N) (hf : f 1 = 1) : (λ x, f (s.mul_indicator (λ x, c) x)) = s.mul_indicator (λ x, f c) := (mul_indicator_comp_of_one hf).symm @[to_additive] lemma mul_indicator_preimage (s : set α) (f : α → M) (B : set M) : (mul_indicator s f)⁻¹' B = s.ite (f ⁻¹' B) (1 ⁻¹' B) := by letI := classical.dec_pred (∈ s); exact piecewise_preimage s f 1 B @[to_additive] lemma mul_indicator_one_preimage (s : set M) : t.mul_indicator 1 ⁻¹' s ∈ ({set.univ, ∅} : set (set α)) := begin classical, rw [mul_indicator_one', preimage_one], split_ifs; simp end @[to_additive] lemma mul_indicator_const_preimage_eq_union (U : set α) (s : set M) (a : M) [decidable (a ∈ s)] [decidable ((1 : M) ∈ s)] : U.mul_indicator (λ x, a) ⁻¹' s = (if a ∈ s then U else ∅) ∪ (if (1 : M) ∈ s then Uᶜ else ∅) := begin rw [mul_indicator_preimage, preimage_one, preimage_const], split_ifs; simp [← compl_eq_univ_diff] end @[to_additive] lemma mul_indicator_const_preimage (U : set α) (s : set M) (a : M) : U.mul_indicator (λ x, a) ⁻¹' s ∈ ({set.univ, U, Uᶜ, ∅} : set (set α)) := begin classical, rw [mul_indicator_const_preimage_eq_union], split_ifs; simp end lemma indicator_one_preimage [has_zero M] (U : set α) (s : set M) : U.indicator 1 ⁻¹' s ∈ ({set.univ, U, Uᶜ, ∅} : set (set α)) := indicator_const_preimage _ _ 1 @[to_additive] lemma mul_indicator_preimage_of_not_mem (s : set α) (f : α → M) {t : set M} (ht : (1:M) ∉ t) : (mul_indicator s f)⁻¹' t = f ⁻¹' t ∩ s := by simp [mul_indicator_preimage, pi.one_def, set.preimage_const_of_not_mem ht] @[to_additive] lemma mem_range_mul_indicator {r : M} {s : set α} {f : α → M} : r ∈ range (mul_indicator s f) ↔ (r = 1 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by simp [mul_indicator, ite_eq_iff, exists_or_distrib, eq_univ_iff_forall, and_comm, or_comm, @eq_comm _ r 1] @[to_additive] lemma mul_indicator_rel_mul_indicator {r : M → M → Prop} (h1 : r 1 1) (ha : a ∈ s → r (f a) (g a)) : r (mul_indicator s f a) (mul_indicator s g a) := by { simp only [mul_indicator], split_ifs with has has, exacts [ha has, h1] } end has_one section monoid variables [mul_one_class M] {s t : set α} {f g : α → M} {a : α} @[to_additive] lemma mul_indicator_union_mul_inter_apply (f : α → M) (s t : set α) (a : α) : mul_indicator (s ∪ t) f a * mul_indicator (s ∩ t) f a = mul_indicator s f a * mul_indicator t f a := by by_cases hs : a ∈ s; by_cases ht : a ∈ t; simp * @[to_additive] lemma mul_indicator_union_mul_inter (f : α → M) (s t : set α) : mul_indicator (s ∪ t) f * mul_indicator (s ∩ t) f = mul_indicator s f * mul_indicator t f := funext $ mul_indicator_union_mul_inter_apply f s t @[to_additive] lemma mul_indicator_union_of_not_mem_inter (h : a ∉ s ∩ t) (f : α → M) : mul_indicator (s ∪ t) f a = mul_indicator s f a * mul_indicator t f a := by rw [← mul_indicator_union_mul_inter_apply f s t, mul_indicator_of_not_mem h, mul_one] @[to_additive] lemma mul_indicator_union_of_disjoint (h : disjoint s t) (f : α → M) : mul_indicator (s ∪ t) f = λa, mul_indicator s f a * mul_indicator t f a := funext $ λa, mul_indicator_union_of_not_mem_inter (λ ha, h.le_bot ha) _ @[to_additive] lemma mul_indicator_mul (s : set α) (f g : α → M) : mul_indicator s (λa, f a * g a) = λa, mul_indicator s f a * mul_indicator s g a := by { funext, simp only [mul_indicator], split_ifs, { refl }, rw mul_one } @[to_additive] lemma mul_indicator_mul' (s : set α) (f g : α → M) : mul_indicator s (f * g) = mul_indicator s f * mul_indicator s g := mul_indicator_mul s f g @[simp, to_additive] lemma mul_indicator_compl_mul_self_apply (s : set α) (f : α → M) (a : α) : mul_indicator sᶜ f a * mul_indicator s f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_compl_mul_self (s : set α) (f : α → M) : mul_indicator sᶜ f * mul_indicator s f = f := funext $ mul_indicator_compl_mul_self_apply s f @[simp, to_additive] lemma mul_indicator_self_mul_compl_apply (s : set α) (f : α → M) (a : α) : mul_indicator s f a * mul_indicator sᶜ f a = f a := classical.by_cases (λ ha : a ∈ s, by simp [ha]) (λ ha, by simp [ha]) @[simp, to_additive] lemma mul_indicator_self_mul_compl (s : set α) (f : α → M) : mul_indicator s f * mul_indicator sᶜ f = f := funext $ mul_indicator_self_mul_compl_apply s f @[to_additive] lemma mul_indicator_mul_eq_left {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support f).mul_indicator (f * g) = f := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : g x = 1, from nmem_mul_support.1 (disjoint_left.1 h hx), rw [pi.mul_apply, this, mul_one] end @[to_additive] lemma mul_indicator_mul_eq_right {f g : α → M} (h : disjoint (mul_support f) (mul_support g)) : (mul_support g).mul_indicator (f * g) = g := begin refine (mul_indicator_congr $ λ x hx, _).trans mul_indicator_mul_support, have : f x = 1, from nmem_mul_support.1 (disjoint_right.1 h hx), rw [pi.mul_apply, this, one_mul] end @[to_additive] lemma mul_indicator_mul_compl_eq_piecewise [decidable_pred (∈ s)] (f g : α → M) : s.mul_indicator f * sᶜ.mul_indicator g = s.piecewise f g := begin ext x, by_cases h : x ∈ s, { rw [piecewise_eq_of_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_mem h, set.mul_indicator_of_not_mem (set.not_mem_compl_iff.2 h), mul_one] }, { rw [piecewise_eq_of_not_mem _ _ _ h, pi.mul_apply, set.mul_indicator_of_not_mem h, set.mul_indicator_of_mem (set.mem_compl h), one_mul] }, end /-- `set.mul_indicator` as a `monoid_hom`. -/ @[to_additive "`set.indicator` as an `add_monoid_hom`."] noncomputable def mul_indicator_hom {α} (M) [mul_one_class M] (s : set α) : (α → M) →* (α → M) := { to_fun := mul_indicator s, map_one' := mul_indicator_one M s, map_mul' := mul_indicator_mul s } end monoid section distrib_mul_action variables {A : Type*} [add_monoid A] [monoid M] [distrib_mul_action M A] lemma indicator_smul_apply (s : set α) (r : α → M) (f : α → A) (x : α) : indicator s (λ x, r x • f x) x = r x • indicator s f x := by { dunfold indicator, split_ifs, exacts [rfl, (smul_zero (r x)).symm] } lemma indicator_smul (s : set α) (r : α → M) (f : α → A) : indicator s (λ (x : α), r x • f x) = λ (x : α), r x • indicator s f x := funext $ indicator_smul_apply s r f lemma indicator_const_smul_apply (s : set α) (r : M) (f : α → A) (x : α) : indicator s (λ x, r • f x) x = r • indicator s f x := indicator_smul_apply s (λ x, r) f x lemma indicator_const_smul (s : set α) (r : M) (f : α → A) : indicator s (λ (x : α), r • f x) = λ (x : α), r • indicator s f x := funext $ indicator_const_smul_apply s r f end distrib_mul_action section group variables {G : Type*} [group G] {s t : set α} {f g : α → G} {a : α} @[to_additive] lemma mul_indicator_inv' (s : set α) (f : α → G) : mul_indicator s (f⁻¹) = (mul_indicator s f)⁻¹ := (mul_indicator_hom G s).map_inv f @[to_additive] lemma mul_indicator_inv (s : set α) (f : α → G) : mul_indicator s (λa, (f a)⁻¹) = λa, (mul_indicator s f a)⁻¹ := mul_indicator_inv' s f @[to_additive] lemma mul_indicator_div (s : set α) (f g : α → G) : mul_indicator s (λ a, f a / g a) = λ a, mul_indicator s f a / mul_indicator s g a := (mul_indicator_hom G s).map_div f g @[to_additive] lemma mul_indicator_div' (s : set α) (f g : α → G) : mul_indicator s (f / g) = mul_indicator s f / mul_indicator s g := mul_indicator_div s f g @[to_additive indicator_compl'] lemma mul_indicator_compl (s : set α) (f : α → G) : mul_indicator sᶜ f = f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ s.mul_indicator_compl_mul_self f lemma indicator_compl {G} [add_group G] (s : set α) (f : α → G) : indicator sᶜ f = f - indicator s f := by rw [sub_eq_add_neg, indicator_compl'] @[to_additive indicator_diff'] lemma mul_indicator_diff (h : s ⊆ t) (f : α → G) : mul_indicator (t \ s) f = mul_indicator t f * (mul_indicator s f)⁻¹ := eq_mul_inv_of_mul_eq $ by { rw [pi.mul_def, ←mul_indicator_union_of_disjoint, diff_union_self, union_eq_self_of_subset_right h], exact disjoint_sdiff_self_left } lemma indicator_diff {G : Type*} [add_group G] {s t : set α} (h : s ⊆ t) (f : α → G) : indicator (t \ s) f = indicator t f - indicator s f := by rw [indicator_diff' h, sub_eq_add_neg] end group section comm_monoid variables [comm_monoid M] /-- Consider a product of `g i (f i)` over a `finset`. Suppose `g` is a function such as `pow`, which maps a second argument of `1` to `1`. Then if `f` is replaced by the corresponding multiplicative indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ @[to_additive] lemma prod_mul_indicator_subset_of_eq_one [has_one N] (f : α → N) (g : α → N → M) {s t : finset α} (h : s ⊆ t) (hg : ∀ a, g a 1 = 1) : ∏ i in s, g i (f i) = ∏ i in t, g i (mul_indicator ↑s f i) := begin rw ← finset.prod_subset h _, { apply finset.prod_congr rfl, intros i hi, congr, symmetry, exact mul_indicator_of_mem hi _ }, { refine λ i hi hn, _, convert hg i, exact mul_indicator_of_not_mem hn _ } end /-- Consider a sum of `g i (f i)` over a `finset`. Suppose `g` is a function such as multiplication, which maps a second argument of 0 to 0. (A typical use case would be a weighted sum of `f i * h i` or `f i • h i`, where `f` gives the weights that are multiplied by some other function `h`.) Then if `f` is replaced by the corresponding indicator function, the `finset` may be replaced by a possibly larger `finset` without changing the value of the sum. -/ add_decl_doc set.sum_indicator_subset_of_eq_zero /-- Taking the product of an indicator function over a possibly larger `finset` is the same as taking the original function over the original `finset`. -/ @[to_additive "Summing an indicator function over a possibly larger `finset` is the same as summing the original function over the original `finset`."] lemma prod_mul_indicator_subset (f : α → M) {s t : finset α} (h : s ⊆ t) : ∏ i in s, f i = ∏ i in t, mul_indicator ↑s f i := prod_mul_indicator_subset_of_eq_one _ (λ a b, b) h (λ _, rfl) @[to_additive] lemma _root_.finset.prod_mul_indicator_eq_prod_filter (s : finset ι) (f : ι → α → M) (t : ι → set α) (g : ι → α) [decidable_pred (λ i, g i ∈ t i)]: ∏ i in s, mul_indicator (t i) (f i) (g i) = ∏ i in s.filter (λ i, g i ∈ t i), f i (g i) := begin refine (finset.prod_filter_mul_prod_filter_not s (λ i, g i ∈ t i) _).symm.trans _, refine eq.trans _ (mul_one _), exact congr_arg2 (*) (finset.prod_congr rfl $ λ x hx, mul_indicator_of_mem (finset.mem_filter.1 hx).2 _) (finset.prod_eq_one $ λ x hx, mul_indicator_of_not_mem (finset.mem_filter.1 hx).2 _) end @[to_additive] lemma mul_indicator_finset_prod (I : finset ι) (s : set α) (f : ι → α → M) : mul_indicator s (∏ i in I, f i) = ∏ i in I, mul_indicator s (f i) := (mul_indicator_hom M s).map_prod _ _ @[to_additive] lemma mul_indicator_finset_bUnion {ι} (I : finset ι) (s : ι → set α) {f : α → M} : (∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) → mul_indicator (⋃ i ∈ I, s i) f = λ a, ∏ i in I, mul_indicator (s i) f a := begin classical, refine finset.induction_on I _ _, { intro h, funext, simp }, assume a I haI ih hI, funext, rw [finset.prod_insert haI, finset.set_bUnion_insert, mul_indicator_union_of_not_mem_inter, ih _], { assume i hi j hj hij, exact hI i (finset.mem_insert_of_mem hi) j (finset.mem_insert_of_mem hj) hij }, simp only [not_exists, exists_prop, mem_Union, mem_inter_iff, not_and], assume hx a' ha', refine disjoint_left.1 (hI a (finset.mem_insert_self _ _) a' (finset.mem_insert_of_mem ha') _) hx, exact (ne_of_mem_of_not_mem ha' haI).symm end @[to_additive] lemma mul_indicator_finset_bUnion_apply {ι} (I : finset ι) (s : ι → set α) {f : α → M} (h : ∀ (i ∈ I) (j ∈ I), i ≠ j → disjoint (s i) (s j)) (x : α) : mul_indicator (⋃ i ∈ I, s i) f x = ∏ i in I, mul_indicator (s i) f x := by rw set.mul_indicator_finset_bUnion I s h end comm_monoid section mul_zero_class variables [mul_zero_class M] {s t : set α} {f g : α → M} {a : α} lemma indicator_mul (s : set α) (f g : α → M) : indicator s (λa, f a * g a) = λa, indicator s f a * indicator s g a := by { funext, simp only [indicator], split_ifs, { refl }, rw mul_zero } lemma indicator_mul_left (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = indicator s f a * g a := by { simp only [indicator], split_ifs, { refl }, rw [zero_mul] } lemma indicator_mul_right (s : set α) (f g : α → M) : indicator s (λa, f a * g a) a = f a * indicator s g a := by { simp only [indicator], split_ifs, { refl }, rw [mul_zero] } lemma inter_indicator_mul {t1 t2 : set α} (f g : α → M) (x : α) : (t1 ∩ t2).indicator (λ x, f x * g x) x = t1.indicator f x * t2.indicator g x := by { rw [← set.indicator_indicator], simp [indicator] } end mul_zero_class section mul_zero_one_class variables [mul_zero_one_class M] lemma inter_indicator_one {s t : set α} : (s ∩ t).indicator (1 : _ → M) = s.indicator 1 * t.indicator 1 := funext (λ _, by simpa only [← inter_indicator_mul, pi.mul_apply, pi.one_apply, one_mul]) lemma indicator_prod_one {s : set α} {t : set β} {x : α} {y : β} : (s ×ˢ t).indicator (1 : _ → M) (x, y) = s.indicator 1 x * t.indicator 1 y := by { classical, simp [indicator_apply, ←ite_and] } variables (M) [nontrivial M] lemma indicator_eq_zero_iff_not_mem {U : set α} {x : α} : indicator U 1 x = (0 : M) ↔ x ∉ U := by { classical, simp [indicator_apply, imp_false] } lemma indicator_eq_one_iff_mem {U : set α} {x : α} : indicator U 1 x = (1 : M) ↔ x ∈ U := by { classical, simp [indicator_apply, imp_false] } lemma indicator_one_inj {U V : set α} (h : indicator U (1 : α → M) = indicator V 1) : U = V := by { ext, simp_rw [← indicator_eq_one_iff_mem M, h] } end mul_zero_one_class section order variables [has_one M] {s t : set α} {f g : α → M} {a : α} {y : M} section variables [has_le M] @[to_additive] lemma mul_indicator_apply_le' (hfg : a ∈ s → f a ≤ y) (hg : a ∉ s → 1 ≤ y) : mul_indicator s f a ≤ y := begin by_cases ha : a ∈ s, { simpa [ha] using hfg ha }, { simpa [ha] using hg ha }, end @[to_additive] lemma mul_indicator_le' (hfg : ∀ a ∈ s, f a ≤ g a) (hg : ∀ a ∉ s, 1 ≤ g a) : mul_indicator s f ≤ g := λ a, mul_indicator_apply_le' (hfg _) (hg _) @[to_additive] lemma le_mul_indicator_apply {y} (hfg : a ∈ s → y ≤ g a) (hf : a ∉ s → y ≤ 1) : y ≤ mul_indicator s g a := @mul_indicator_apply_le' α Mᵒᵈ ‹_› _ _ _ _ _ hfg hf @[to_additive] lemma le_mul_indicator (hfg : ∀ a ∈ s, f a ≤ g a) (hf : ∀ a ∉ s, f a ≤ 1) : f ≤ mul_indicator s g := λ a, le_mul_indicator_apply (hfg _) (hf _) end variables [preorder M] @[to_additive indicator_apply_nonneg] lemma one_le_mul_indicator_apply (h : a ∈ s → 1 ≤ f a) : 1 ≤ mul_indicator s f a := le_mul_indicator_apply h (λ _, le_rfl) @[to_additive indicator_nonneg] lemma one_le_mul_indicator (h : ∀ a ∈ s, 1 ≤ f a) (a : α) : 1 ≤ mul_indicator s f a := one_le_mul_indicator_apply (h a) @[to_additive] lemma mul_indicator_apply_le_one (h : a ∈ s → f a ≤ 1) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le' h (λ _, le_rfl) @[to_additive] lemma mul_indicator_le_one (h : ∀ a ∈ s, f a ≤ 1) (a : α) : mul_indicator s f a ≤ 1 := mul_indicator_apply_le_one (h a) @[to_additive] lemma mul_indicator_le_mul_indicator (h : f a ≤ g a) : mul_indicator s f a ≤ mul_indicator s g a := mul_indicator_rel_mul_indicator le_rfl (λ _, h) attribute [mono] mul_indicator_le_mul_indicator indicator_le_indicator @[to_additive] lemma mul_indicator_le_mul_indicator_of_subset (h : s ⊆ t) (hf : ∀ a, 1 ≤ f a) (a : α) : mul_indicator s f a ≤ mul_indicator t f a := mul_indicator_apply_le' (λ ha, le_mul_indicator_apply (λ _, le_rfl) (λ hat, (hat $ h ha).elim)) (λ ha, one_le_mul_indicator_apply (λ _, hf _)) @[to_additive] lemma mul_indicator_le_self' (hf : ∀ x ∉ s, 1 ≤ f x) : mul_indicator s f ≤ f := mul_indicator_le' (λ _ _, le_rfl) hf @[to_additive] lemma mul_indicator_Union_apply {ι M} [complete_lattice M] [has_one M] (h1 : (⊥:M) = 1) (s : ι → set α) (f : α → M) (x : α) : mul_indicator (⋃ i, s i) f x = ⨆ i, mul_indicator (s i) f x := begin by_cases hx : x ∈ ⋃ i, s i, { rw [mul_indicator_of_mem hx], rw [mem_Union] at hx, refine le_antisymm _ (supr_le $ λ i, mul_indicator_le_self' (λ x hx, h1 ▸ bot_le) x), rcases hx with ⟨i, hi⟩, exact le_supr_of_le i (ge_of_eq $ mul_indicator_of_mem hi _) }, { rw [mul_indicator_of_not_mem hx], simp only [mem_Union, not_exists] at hx, simp [hx, ← h1] } end end order section canonically_ordered_monoid variables [canonically_ordered_monoid M] @[to_additive] lemma mul_indicator_le_self (s : set α) (f : α → M) : mul_indicator s f ≤ f := mul_indicator_le_self' $ λ _ _, one_le _ @[to_additive] lemma mul_indicator_apply_le {a : α} {s : set α} {f g : α → M} (hfg : a ∈ s → f a ≤ g a) : mul_indicator s f a ≤ g a := mul_indicator_apply_le' hfg $ λ _, one_le _ @[to_additive] lemma mul_indicator_le {s : set α} {f g : α → M} (hfg : ∀ a ∈ s, f a ≤ g a) : mul_indicator s f ≤ g := mul_indicator_le' hfg $ λ _ _, one_le _ end canonically_ordered_monoid lemma indicator_le_indicator_nonneg {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) : s.indicator f ≤ {x | 0 ≤ f x}.indicator f := begin intro x, classical, simp_rw indicator_apply, split_ifs, { exact le_rfl, }, { exact (not_le.mp h_1).le, }, { exact h_1, }, { exact le_rfl, }, end lemma indicator_nonpos_le_indicator {β} [linear_order β] [has_zero β] (s : set α) (f : α → β) : {x | f x ≤ 0}.indicator f ≤ s.indicator f := @indicator_le_indicator_nonneg α βᵒᵈ _ _ s f end set @[to_additive] lemma monoid_hom.map_mul_indicator {M N : Type*} [mul_one_class M] [mul_one_class N] (f : M →* N) (s : set α) (g : α → M) (x : α) : f (s.mul_indicator g x) = s.mul_indicator (f ∘ g) x := congr_fun (set.mul_indicator_comp_of_one f.map_one).symm x
639a67518c4bda7ce2ace53d850f7c58c12c8e41
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/show2.lean
bac2639eb3d312461c4e7c67d5859a35264ee472
[ "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
260
lean
import data.nat open nat example : ∀ a b, a + b = b + a := show ∀ a b : nat, a + b = b + a | 0 0 := rfl | 0 (succ b) := by rewrite zero_add | (succ a) 0 := by rewrite zero_add | (succ a) (succ b) := by rewrite [succ_add, this]